torch.nn
basic building block
m = nn.Linear(20, 30)
input = torch.randn(128, 20)
output = m(input)
print(output.size())
torch.Size([128, 30])
X = torch.Tensor([[1, 2],
[3, 4]])
m = nn.Identity()
m(X)
tensor([[1., 2.],
[3., 4.]])
모델로 추상화 할 수 있는 클래스
model = nn.Sequential(
nn.Conv2d(1,20,5),
nn.ReLU(),
nn.Conv2d(20,64,5),
nn.ReLU()
)
class MyModule(nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])
def forward(self, x):
# ModuleList can act as an iterable, or be indexed using ints
for i, l in enumerate(self.linears):
x = self.linears[i // 2](x) + l(x)
return x
class MyModule(nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.choices = nn.ModuleDict({
'conv': nn.Conv2d(10, 10, 3),
'pool': nn.MaxPool2d(3)
})
self.activations = nn.ModuleDict([
['lrelu', nn.LeakyReLU()],
['prelu', nn.PReLU()]
])
def forward(self, x, choice, act):
x = self.choices[choice](x)
x = self.activations[act](x)
return x
from torch.nn.parameter import Parameter
self.W = Parameter(torch.ones((out_features, in_features)))
self.b = Parameter(torch.ones(out_features))
self.register_buffer('name', tensor)
model.get_submodule('path')
model.get_parameter('path')
model.get_buffer('path')
모델의 layer name을 따라 path 로 지정 cd.c.duck 요로코롬
가장 낮은 단위인 module간 참조는 불필요
class Function_A(nn.Module):
def __init__(self, name):
super().__init__()
self.name = name
def forward(self, x):
x = x * 2
return x
def extra_repr(self):
return str('name='+self.name)
package 중간중간에 custom code를 실행할 수 있도록 미리 만들어놓은 인터페이스
model.register_forward_pre_hook(hook)
model.register_forward_hook(hook)
model.register_full_backward_hook(hook)
model.W.register_hook(tensor_hook)
module을 입력으로 받아 모든 module에 함수를 적용시켜주는 코드
일반적으로 가중치 초기화에 많이 사용
# apply가 적용된 module을 return
returned_module = model.apply(print_module)