20210801 TIL
2021.08.01
pytorch의 nn.Module을 사용해서 linear layer 구현 방법
import torch.nn as nn
# nn.Module 이라고 하는 추상 클래스를 불러와서 하나의 클래스로 구현하여 계산에 이용한다.
class MyLinear(nn.Module):
def __init__(self, input_dim=3, output_dim=2):
self.input_dim = input_dim
self.output_dim = output_dim
super().__init__()
self.W = nn.Parameter(torch.FloatTensor(input_dim, output_dim))
self.b = nn.Parameter(torch.FloatTensor(output_dim))
def forward(self, x):
y = torch.matmul(x, self.W) + self.b
return y
linear = MyLinear(3, 2)
# parameters라는 함수를 통해 trainable한 값들을 iterate 해줌.
for p in linear.parameters():
print(p)
사실 위에 처럼 복잡하게 안함ㅋ
# 사실 위와 같이 low level에서 실행하지 않아도 된다.
# 미리 구현되어 있는 아래와 같은 코드로 단순하게 돌려도 된다.
# 다만 위와는 다르게 W 가 transpose되어 있다.
linear = nn.Linear(3, 2)
y = linear(x)
위 처럼 간단하게 linear layer 하나를 생성하고 그 것들이 여러 개 들어있는 multi-linear layer를 아래와 같이 구현한다.
class MyLinear(nn.Module):
def __init__(self, input_dim=3, output_dim=2):
self.input_dim = input_dim
self.output_dim = output_dim
super().__init__()
# 위에서 처럼 low lever에서 parameter를 등록하는 것이 아니라
# 아래와 같이 nn.Linear로 등록해주면 된다.
# 여러개의 linear들로 구성된 뉴럴 넷웤을 구성할 수 있다.
self.linear = nn.Linear(input_dim, output_dim)
def forward(self, x):
# |x| = (batch_size, input_dim)
y = self.linear(x)
# |y| = (batch_size, output_dim)
return y
오호링.
댓글을 작성해보세요.