가중치와 신호의 곱을 합한 것
전달함수라고도 함.
→ 노드의 가중합이 계산되면 이 가중합을 활성화 함수로 보내기 때문
가중합 공식
활성화 함수(Activation Function) : 신호를 입력받아 이를 적절히 처리하여 출력해주는 함수
Ex) Sigmoid, Hyperbolic Tangent, ReLU 등
Sigmoid
Hyperbolic Tangent
ReLU
Leaky ReLU
Softmax
ReLU & Softmax 구현(PyTorch)
class Net(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer
self.relu = torch.nn.ReLU(inplace=True)
self.out = torch.nn.Linear(n_hidden, n_output) # output layer
self.softmax = torch.nn,Softmax(dim=n_output)
def forward(self, x):
x = self.hidden(x)
x = self.relu(x) # hidden layer를 위한 Relu 함수
x = self.out(x)
x = self.softmax(x) # output layer를 위한 Softmax 함수
return x
손실 함수(Loss Function) : 가중치 학습을 위해 출력 함수의 결과와 실제 값 간의 오차를 측정하는 함수
평균 제곱 오차(Mean Squared Error)
실제 값과 예측 값의 차이(error)를 제곱하여 평균을 낸 것
회귀에서 손실 함수로 주로 사용됨.
구현 (PyTorch)
import torch
loss_fn = torch.nn.MSELoss(reduction='sum')
y_pred = model(x)
loss = loss_fn(y_pred, y)
크로스 엔트로피 오차(Cross Entropy Error)
classification(분류) 문제에서 원-핫 인코딩(One-Hot Encoding) 했을 때만 사용할 수 있는 오차 계산법
일반적인 분류 문제에서 데이터의 출력을 0과 1로 구분하기 위해 Sigmoid 함수를 사용하지만, 이 함수에 포함된 자연 상수 e 때문에 평균 제곱 오차 적용 시 매끄럽지 못한 그래프가 출력됨.
경사 하강법 과정에서 학습이 지역 최소점에서 멈출 수 있음.
구현 (PyTorch)
loss = nn.CrossEntropyLoss()
# torch.randn: 평균이 0이고 표준편차가 1인 가우시안 정규분포를 이용하여 숫자 생성
input = torch.randn(5, 6, requires_grad=True)
target = torch.empty(3, dtype=torch.long).random_(5)
output = loss(input, target)
output.backward()