본문 바로가기
AI 인공지능

파이토치 신경망 구성하기

by 테크구루스 2023. 3. 24.

이 글은 파이토치로 배우는 자연어처리(O'REILLY, 한빛미디어)를 공부한 내용을 바탕으로 작성하였습니다.

 

 

1. 퍼셉트론 구현

y = f(wx + b)

 

x : 입력

w : 가중치

b : 편향, 절편

y : 출력

f(): 활성화 함수

 

선형 함수 표현인 wx + b 는 아핀 변환(affine transform)이라고 불린다.

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):
        """퍼셉트론의 정방향 계산
        
        매개변수:
            x_in (torch.Tensor): 입력 데이터 텐서
                x_in.shape는 (batch, num_features)입니다.
        반환값:
            결과 텐서. tensor.shape는 (batch,)입니다.
        """
        return torch.sigmoid(self.fc1(x_in))

super() : 하위 클래스에서 부모 클래스의 메소드를 사용할수 있도록 한다.

nn.Linear(): 가중치와 절편에 관련된 작업, 아핀 변환 수행

forward() : 순전파를 수행하고, 활성화 함수를 거친 값을 반환


2. 활성화 함수

2-1. 시그모이드(sigmoid)

import torch
import matplotlib.pyplot as plt

x = torch.arange(-5., 5., 0.1)
y = torch.sigmoid(x)
plt.plot(x.numpy(), y.detach().numpy())
plt.show()

detach() : 해당 층에서 gradient의 전파를 멈추는 역할

sigmoid 그래프

출력층에서 활용, 0 ~ 1 사이의 값을 반환하기 때문에 출력을 확률로 압축하는데 사용.


2-2. 하이퍼볼릭 탄젠트(tanh)

import torch
import matplotlib.pyplot as plt

x = torch.arange(-5., 5., 0.1)
y = torch.tanh(x)

plt.plot(x.numpy(), y.detach().numpy())
plt.show()

tanh 그래프

출력이 -1 ~ 1 사이의 값을 가져 sigmoid보다 반환값의 변화폭이 크기에 기울기 소실 증상이 적음.

은닉층에서 sigmoid 보다 많이 사용.


2.3. 렐루(ReLU)

import torch
import matplotlib.pyplot as plt

relu = torch.nn.ReLU()
x = torch.arange(-5., 5., 0.1)
y = relu(x)

plt.plot(x.numpy(), y.detach().numpy())
plt.show()

ReLU 그래프

음수를 제거하고 양수에서는 입력값을 그대로 출력하여 그래디언트 소실문제를 막음.

특정 출력이 0이되면 돌아오지 않고 소멸되는 '죽은 렐루' 현상 생김.


2.4 PReLU

import torch.nn as nn
import matplotlib.pyplot as plt

prelu = nn.PReLU(num_parameters=1)
x = torch.arange(-5., 5., 0.1)
y = prelu(x)

plt.plot(x.numpy(), y.detach().numpy())
plt.show()

PReLU

죽은 렐루 현상을 제거한 함수


2.5 소프트맥스(softmax)

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))

모든 출력의 합으로 각 출력을 나누어 k개 클래스에 대한 이산 확률 분포 생성

다중 분류 작업에서 출력을 해석할 때 이용