입력(x), 출력(y), 가중치(w), 절편(b)
⇒ y=f(wx+b)
(➕ wx+b를 아핀 변환이라고도 부른다고…)
#퍼셉트론 기본 구조
import torch
import torch.nn as nn
class Perceptron(nn.Module):
def __init__(self, input_dim):
'''
매개변수: input_dim(int) 입력 특성의 크기
'''
super(Perceptron, self).__init__()
self.fc1=nn.Linear(input_dim, 1)
def forward(self, x_in):
'''퍼셉트론의 정방향 계산 feed forward~~
매개변수: x_in (torch.Tensor) 입력 데이터 텐서
반환값: 결과 텐서.
'''
return torch.sigmoid(self.fc1(x_in)).squeeze()
#squeeze() -> 차원이 1인 부분 제거.(차원 축소..) vs unsqueeze() -> size 1인 차원 생성.
시그모이드
import torch
import matplotlib.pyplot as plt
x=torch.range(-5.,5.,0.1)
y=torch.sigmoid(x)
plt.plot(x.numpy(), y.numpy())
plt.show()
하이퍼볼릭 탄젠트
import torch
import matplotlib.pyplot as plt
x=torch.range(-5.,5.,0.1)
y=torch.tanh(x)
plt.plot(x.numpy(),y.numpy())
plt.show()
렐루 (ReLU)
import torch
import matplotlib.pyplot as plot
relu=torch.nn.ReLU()
x=torch.range(-5,5,0.1)
y=relu(x)
plt.plot(x.numpy(),y.numpy())
plt.show()
소프트맥스 (softmax)
import torch.nn as nn
import torch
softmax=nn.Softmax(dim=1)
x_input=torch.randn(1,3)
y_output=softmax(x_input)
print(x_input)
print(y_output)
print(torch.sum(y_output, dim=1)) #확률 분포라서 합이 1
>>>tensor([[-0.2528, -0.3826, -1.0988]]) tensor([[0.4334, 0.3806, 0.1860]]) tensor([1.])
올바른 파라미터를 선택하도록 훈련 알고리즘을 도움.
평균 제곱 오차 (MSE)
import torch
import torch.nn as nn
mse_loss=nn.MSELoss()
outputs=torch.randn(3,5, requires_grad=True)
targets=torch.randn(3,5)
loss=mse_loss(outputs, targets)
print(loss)
>>> tensor(2.3196, grad_fn=<MseLossBackward0>)
범주형 크로스 엔트로피 (Cross Entropy)
log_softmax() + NLLLoss() = CrossEntropyLoss()
import torch
import torch.nn as nn
ce_loss=nn.CrossEntropyLoss()
outputs=torch.randn(3,5, requires_grad=True) #샘플 3개마다 5가지 클래스에 대한 확률값
targets=torch.tensor([1,0,3], dtype=torch.int64) #각 샘플의 정답 클래스
loss=ce_loss(outputs, targets)
print(loss)
이진 크로스 엔트로피 (Binary Cross Entropy, BCE)
bce_loss=nn.BCELoss()
sigmoid=nn.Sigmoid()
probabilities=sigmoid(torch.randn(4,1,requires_grad=True)) #출력
targets=torch.tensor([1,0,1,0], dtype=torch.float32).view(4,1)
#view=reshape (1,4)->(4,1)
loss=bce_loss(probabilities, targets)
print(probabilities)
print(loss)
>>> tensor([[0.5639], [0.4057], [0.8600], [0.6237]], grad_fn=<SigmoidBackward0>) tensor(0.5554, grad_fn=<BinaryCrossEntropyBackward0>)
나의 쁘띠한 그림실력..
참고