다시 이음

Pytorch 모델 생성 및 layer 설정 본문

Pre_Onboarding by Wanted(자연어 처리)

Pytorch 모델 생성 및 layer 설정

Taeho(Damon) 2022. 3. 2. 18:26

안녕하세요.

 

오늘은 Pytorch에서 모델을 생성하고 배정하는 방법에 대해서 알아보겠습니다.

 

모델을 정의하는 방법에서 tensorflow와 다른 점이 보여서 그 점을 비교하면서 하면 좋을 것 같습니다.

 

Pytorch

- Module 클래스

 

Model 을 정의할 때에는 Module 클래스를 무조건 상속 받아야합니다.

forward() 메소드는 모든 자식클래스에서 반드시 오버라이딩 해야합니다.

 

공식문서 // https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module 

공식 문서를 통해 메소드를 보면 좋습니다.(eval(), train(), parameters(), state_dict(), to() 등등)

class Model(nn.Module):
    def __init__(self, input_shape):
        super(Model, self).__init__()
        self.layer1 = nn.Linear(input_shape, 32)
        self.layer2 = nn.Linear(32, 64)
        self.layer_out = nn.Linear(64,1)
        
        self.relu = nn.ReLU()

    def forward(self, x):
        x = self.relu(self.layer1(x))
        x = self.relu(self.layer2(x))
        x = self.layer_out(x)
        return x

 

- Sequential 클래스

model = nn.Sequential(
          nn.Linear(30, 32),
          nn.ReLU(),
          nn.Linear(32,64),
          nn.ReLU(),
          nn.Linear(64,1)
        )

 

 

TensorFlow

- Sequential 클래스

from keras import models
from keras import layers

model = models.Sequential()
model.add(layers.Dense(32, activation='relu', input_shape=(784,)))
model.add(layers.Dense(10, activation='softmax'))

- 함수형 API

input_tensor = layers.Input(shape=(784,))
x = layers.Dense(32, activation='relu')(input_tensor)
output_tensor = layers.Dense(10, activation='softmax')(x)

model = models.Model(inputs=input_tensor, outputs=output_tensor)

 

 

이제 Layer을 어떻게 사용하면 될까요?

Pytorch layer 링크를 들어가서 공식문서를 통해 레이어가 어떻게 정의되는지 확인하세요.