HAZEL

Torch : DNN ( Deep Neural Network ), Torch 코드로 ANN, DNN구현, Torch로 모델링하기 본문

DATA ANALYSIS/ML & DL

Torch : DNN ( Deep Neural Network ), Torch 코드로 ANN, DNN구현, Torch로 모델링하기

Rmsid01 2022. 1. 5. 12:27

boostcourse 의 파이토치로 시작하는 딥러닝 기초 강의를 듣고 정리한 내용입니다. 


1. 신경 세포(뉴런)

: 여러 신호를 받아, 하나의 신호를 만들어 전달하는 역할. 출력을 내기전에 활성 함수(activation function)을 통해 비선형 특성을 가할 수 있다.  앞 단계에서는 linear한 연산만 가능한데, 활성화 함수를 통해 비선형 특성을 가할 수 있게 된다.  

: node는 단일 뉴런 연산 , edge는 뉴런의 연결성의 의미한다.

: 활성화 함수의 특징은 선형 함수가 아닌 비선형 함수여야 한다는 것이다.

2.  얕은 신경망 ( Shallow Neural Network )

: input layer, hidden layer , output layer 3가지 계층으로 되어 있으며, 은닉 계층과 출력 계층이 Fully Connected 계층인 모델

: 얕은 신경망의 반대는 Deep Neural Network 이다. 

 

- 코드 

1 ) torch 를 import 하고, device 정의, 데이터를 불러와서 device에 할당하기

import torch

device = torch.device('cpu')
x = torch.FloatTensor([[0,0],[0,1],[1,0],[1,1]]).to(device)
y = torch.FloatTensor([[0],[1],[1],[0]]).to(device)

 

2 )  Layer 을 쌓기.

: torch 에서는 torch.nn.Linear 를 하면 레이어가 쌓인다. 

linear = torch.nn.Linear(2,1, bias =True)

 

+ ) torch.nn.Linear 에 대한 추가적인 설명

https://pytorch.org/docs/stable/generated/torch.nn.Linear.html

torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None
  • in_features – size of each input sample
  • out_features – size of each output sample
  • bias – If set to False, the layer will not learn an additive bias. Default: True

 

3) 활성화 함수을 선언해준다.

: 아래 코드는 다양한 활성화 함수 중에서, sigmoid를 불러온 것이다.

sigmoid = torch.nn.Sigmoid()

 

4) 모델 정의

: 아래에서는 torch.nn.Sequential 을 이용하여 모델을 정의해주었다.

torch.nn.Sequential 을 이용하면, __init__() 에서 사용할 네트워크 모델들을 정의해줄 뿐만 아니라, forward()함수에서 구현될 순전파를 layer형태로 구현해주어 가독성이 높아진다. 모델을 편하게 순차적으로 실행할 수 있게 도와주는 container 개념이라고 이해하면 된다.

model = torch.nn.Sequential(linear,sigmoid).to(device)

 

5) loss함수와 optimizer정의

: 아래에서는 0,1  분류모델이므로 binary cross_entropy loss 사용하였고, 기본적인 SGD 옵티마이저를 사용한다.

criterion = torch.nn.BCELoss().to(device) 
optimizer= torch.optim.SGD(model.parameters(), lr=1)

 

6 ) 학습하기 ( 반복적으로 학습하기 위해 for 문 사용 )

- gradients를 clear :  gradients를 clear해서 새로운 최적화 값을 찾기 위해 준비

optimizer.zero_grad()

 

- 준비한 데이터를 model 에 input 으로 넣어 output을 얻음

: 데이터를 model에 넣어줌 keras는 보통 perdict , torch는 output이라 보통 씀

hypothesis = model(x)

 

- Model 에서 예측한 결과를 Loss Functoon 에 넣음. 위에서 정의한 loss함수 이다.

cost = criterion(hypothesis, y)

 

- Back Propagation을 통해 Gradients를 계산

cost.backward()

 

- weight parameter update

: 계산된 Gradients는 계산한 것으로 마무리 되는 것이 아니라 , Parameter 에 Update

optimizer.step()

 

- 위의 과정을 for문으로 정리 한것

# train
for step in range(1000):
    optimizer.zero_grad()
    hypothesis = model(x)
    
    # cost, loss function
    cost = criterion(hypothesis, y)
    cost.backward()
    optimizer.step()
    if step % 100 == 0:
        print(step, cost.item())

 

3. Muti Layer Perceptron

위에서 하나의 층을 가지는 layer로 훈련을 할 경우에는 학습의 결과가 별로 좋지 못함을 확인 할 수있다. 과거에는 Muti Layer Perceptron 를 학습할 수 있는 방법이 없었으나, Backpropagation 알고리즘이 개발되면서, Muti Layer model 에 대해서도 학습할 수 있게 되었다.

 

- Backpropagation 이란, 어떤 입력 X 가 들어왔을 때 neural network을 통해서 output y를 구하게 되는데, 이 output과 원래 정답인 G(t)간의 차이인 cost(loss)에 대해서 neural network에 있는 weight 들에 대한 미분값을 계산하는 것이다. gradient를 가지고 뒷단에 있는 weight부터 loss를 최소화할 수 있도록 weight를 업데이트하는 방식이다.

 

- 코드 

: 코드는 위에서 단층으로 구현했을 때와 유사하다. 다만, 단층이 아니라 여러 레이어를 쌓는 부분에만 차이가 있다.

아래의 코드를 보면, linear1 , linear2가 존재하고 그것을 torch.nn.Sequential이 다 감쌓아있는 것을 확인 할 수있다.

 

device = torch.device('cpu')
x = torch.FloatTensor([[0,0],[0,1],[1,0],[1,1]]).to(device)
y = torch.FloatTensor([[0],[1],[1],[0]]).to(device)

# nn Layers
linear1 = torch.nn.Linear(2,2, bias=True)
linear2 = torch.nn.Linear(2,1, bias=True)

sigmoid = torch.nn.Sigmoid()
model = torch.nn.Sequential(linear1, sigmoid, linear2, sigmoid).to(device)

criterion = torch.nn.BCELoss().to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=1)

for step in range(10001):
    optimizer.zero_grad()  
    hypothesis = model(x)   
    cost = criterion(hypothesis, y) 
    cost.backward()            
    optimizer.step()        
    if step % 1000 == 0:
        print(step, cost.item())