Deep Learning/Pytorch

Pytorch 의 nn.module 상속의미

판교데싸 2022. 11. 19. 14:40

간단한 layer 구성 예시

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 20, 5, 1)
        self.conv2 = nn.Conv2d(20, 50, 5, 1)
        self.fc1 = nn.Linear(4*4*50, 500)
        self.fc2 = nn.Linear(500, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(x, 2, 2)
        x = F.relu(self.conv2(x))
        x = F.max_pool2d(x, 2, 2)
        x = x.view(-1, 4*4*50)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return F.log_softmax(x, dim=1)

 

nn.module  

파이토치에서 레이어 혹은 모델 구성시 nn.Module을 상속 받는데  이유는 무엇일까?

-> nn.Module의 __init__ 함수를 보면  self._modules는 nn.Module의 __init__에서 선언 및 초기화 되어 있음

여기서 super(Net, self).__init__() 은 nn.module을 상속받기 위해 필수적인 과정

(nn.Module을 상속한 subclass가 신경망 모델로 사용되기 위해선 앞서 소개한 두 메소드를 override 해야한다. 

  • __init__(self): initialize; 내가 사용하고 싶은, 내 신경망 모델에 사용될 구성품들을 정의 및 초기화 하는 메소드이다. 
  • forward(self, x): specify the connections;  이닛에서 정의된 구성품들을 연결하는 메소드이다. )
def __init__(self):
    """
    Initializes internal Module state, shared by both nn.Module and ScriptModule.
    """
    torch._C._log_api_usage_once("python.nn_module")

    self.training = True
    self._parameters = OrderedDict()
    self._buffers = OrderedDict()
    self._non_persistent_buffers_set = set()
    self._backward_hooks = OrderedDict()
    self._forward_hooks = OrderedDict()
    self._forward_pre_hooks = OrderedDict()
    self._state_dict_hooks = OrderedDict()
    self._load_state_dict_pre_hooks = OrderedDict()
    self._modules = OrderedDict() ## _modules 선언 및 초기화

 nn.Module을 extend함으로써 custom model or custom layer는 위와 같은 여러 속성들 또한 상속받게 된다.

위와 같은 속성들은 parameter, modules 등의 네트워크 학습에 있어서 중요한 특성을 포함하는데

파이토치에서 제공하는 layer를 사용하여 모델 빌드를 간편하게 하기 위해서는 위와 같이 nn.Module을 상속받고, 이를 초기화 함으로써 nn.Module에서 상속받는 특성들을 초기화해주는 것이 필요

 

 

참고 : https://anweh.tistory.com/21

반응형

'Deep Learning > Pytorch' 카테고리의 다른 글

Pytorch 코드 컨셉  (0) 2022.11.23
반응형