본문 바로가기
PROGRAMMING/Pytorch

[PYTORCH] nn.sequential을 활용한 신경망 구현하기

by HYUNHP 2023. 3. 5.
반응형

안녕하세요, HELLO

 

신경망은 딥러닝의 핵심으로, 컴퓨터가 데이터를 통해 학습하고 예측이나 의사 결정을 더욱 정확하게 내릴 수 있게 해 줍니다. PyTorch는 신경망 구축과 훈련을 위한 유연하고 직관적인 플랫폼을 제공하는 인기 있는 오픈소스 딥러닝 프레임워크입니다. 신경망을 생성하기 위한 PyTorch의 핵심 모듈 중 하나는 nn으로, 맞춤형 신경망 아키텍처를 설계하고 훈련하기 위한 사전 정의된 레이어와 유틸리티 세트를 제공합니다.

 

이번 포스팅에서는 PyTorch의 nn 모듈을 사용하여 합성곱 신경망(CNN), 심층 신경망(DNN), 강화 학습(RL) 아키텍처를 포함한 다양한 신경망을 생성하는 방법을 정리했습니다. 이러한 신경망을 구축하는 과정을 단계별로 안내하고 코드 샘플과 실용적인 팁을 제공하여 PyTorch를 사용하여 딥러닝 프로젝트를 시작하는 데 도움을 드리고자 합니다. 


STEP 1. 'Pytorch torch.nn Library Import'

 

STEP 2. 'Pytorch torch.nn' 코드 샘플


STEP 1. 'Pytorch torch.nn Library Import'

 

딥러닝, 합성곱 신경망 등 딥러닝 네트워크를 생성하기 위해서는 Pytorch 라이브로리, torch.nn을 불러와야 합니다.

 

import torch
import torch.nn as nn

 

반응형

 

STEP 2. 'Pytorch torch.nn' 코드 샘플

 

Creating a simple feedforward neural network with two hidden layers and ReLU activation

 

model = nn.Sequential(
          nn.Linear(784, 256),  # input layer -> hidden layer 1
          nn.ReLU(),  # activation function
          nn.Linear(256, 128),  # hidden layer 1 -> hidden layer 2
          nn.ReLU(),  # activation function
          nn.Linear(128, 10)  # hidden layer 2 -> output layer
        )

 

위의 예에서는 두 개의 숨겨진 레이어(은닉층)와 ReLU 활성화 함수가 있는 간단한 feedforward 신경망을 생성하고 있습니다. 입력층에는 784개의 노드(28x28 픽셀 이미지에 해당), 첫 번째 숨겨진 레이어 (은닉층)에는 256개의 노드, 두 번째 숨겨진 레이어 (은닉층)에는 128개의 노드, 출력층에는 10개의 노드(분류 작업에서 가능한 클래스 10개에 해당)가 있습니다.


■ Creating a convolutional neural network (CNN) with two convolutional layers, max pooling, and dropout

 

model = nn.Sequential(
          nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1),  # input layer -> conv layer 1
          nn.ReLU(),  # activation function
          nn.MaxPool2d(kernel_size=2),  # max pooling layer
          nn.Dropout(p=0.25),  # dropout layer
          nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),  # conv layer 1 -> conv layer 2
          nn.ReLU(),  # activation function
          nn.MaxPool2d(kernel_size=2),  # max pooling layer
          nn.Dropout(p=0.25),  # dropout layer
          nn.Flatten(),  # flatten the output of the convolutional layers
          nn.Linear(64 * 7 * 7, 512),  # fully connected layer 1
          nn.ReLU(),  # activation function
          nn.Dropout(p=0.5),  # dropout layer
          nn.Linear(512, 10)  # fully connected layer 2 -> output layer
        )

 

위의 예에서는 두 개의 컨볼루션 레이어, max pooling 및 드롭아웃 (dropout)이 있는 CNN을 생성하고 있습니다. 첫 번째 컨볼루션 레이어에는 3x3 크기의 필터 32개, 두 번째 컨볼루션 레이어에는 3x3 크기의 필터 64개가 있으며, 두 레이어 모두 공간 차원을 유지하기 위해 패딩이 1입니다. 이를 통해 원본 크기가 그대로 유지됩니다. 각 컨볼루션 레이어 후에 ReLU 활성화 함수를 적용한 다음, 커널 크기가 2x2인 max pooling 레이어를 적용합니다. 그런 다음 0.25 확률로 드롭아웃을 적용하여 모델을 정규화합니다. 마지막으로 컨볼루션 레이어의 출력을 평탄화 (flatten)하여 ReLU 활성화와 드롭아웃을 통해 fully connected 두 개의 레이어를 통과시킨 후 최종 분류 결과를 출력합니다.


■ Creating a convolutional neural network (CNN) with three convolutional layers with batch normalization and ReLU activation, followed by two fully connected layers with ReLU activation.

 

import torch
import torch.nn as nn

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        
        self.conv1 = nn.Conv2d(1, 16, kernel_size=3, padding=1)
        self.bn1 = nn.BatchNorm2d(16)
        self.relu1 = nn.ReLU(inplace=True)
        
        self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1)
        self.bn2 = nn.BatchNorm2d(32)
        self.relu2 = nn.ReLU(inplace=True)
        
        self.conv3 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
        self.bn3 = nn.BatchNorm2d(64)
        self.relu3 = nn.ReLU(inplace=True)
        
        self.fc1 = nn.Linear(64 * 7 * 7, 128)
        self.relu4 = nn.ReLU(inplace=True)
        
        self.fc2 = nn.Linear(128, 10)
    
    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu1(x)
        
        x = self.conv2(x)
        x = self.bn2(x)
        x = self.relu2(x)
        
        x = self.conv3(x)
        x = self.bn3(x)
        x = self.relu3(x)
        
        x = x.view(-1, 64 * 7 * 7)
        
        x = self.fc1(x)
        x = self.relu4(x)
        
        x = self.fc2(x)
        
        return x

 

728x90

 

■ Creating a Deep Neural Network (DNN) architecture consists of two fully connected layers with ReLU activation.

 

import torch
import torch.nn as nn

class DNN(nn.Module):
    def __init__(self):
        super(DNN, self).__init__()
        
        self.fc1 = nn.Linear(784, 512)
        self.relu1 = nn.ReLU(inplace=True)
        
        self.fc2 = nn.Linear(512, 256)
        self.relu2 = nn.ReLU(inplace=True)
        
        self.fc3 = nn.Linear(256, 10)
    
    def forward(self, x):
        x = x.view(-1, 784)
        
        x = self.fc1(x)
        x = self.relu1(x)
        
        x = self.fc2(x)
        x = self.relu2(x)
        
        x = self.fc3(x)
        
        return x

■ Creating a Reinforcement Learning Architecture

 

import torch
import torch.nn as nn

class ReinforcementLearning(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(ReinforcementLearning, self).__init__()
        
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.relu1 = nn.ReLU(inplace=True)
        
        self.fc2 = nn.Linear(hidden_size, hidden_size)
        self.relu2 = nn.ReLU(inplace=True)
        
        self.fc3 = nn.Linear(hidden_size, output_size)
    
    def forward(self, x):
        x = self.fc1(x)
        x = self.relu1(x)
        
        x = self.fc2(x)
        x = self.relu2(x)
        
        x = self.fc3(x)

■ 마무리

'nn.sequential을 활용한 신경망 구현하기'에 대해서 알아봤습니다.

좋아요댓글 부탁드리며,

오늘 하루도 즐거운 날 되시길 기도하겠습니다 :)

감사합니다.

반응형

댓글