꺼내먹는지식 준

Pytorch parameters initilization 본문

AI/PyTorch

Pytorch parameters initilization

알 수 없는 사용자 2022. 7. 25. 17:18

Single layer

싱글 layer의 weight 초기화를 위해 torch.nn.init함수를 사용할 수 있다. 

conv1 = torch.nn.Conv2d(...)
torch.nn.init.xavier_uniform(conv1.weight)

대안으로, parameters 를 weight.data 에 접근하여 조정할 수 있다. (torch.Tensor)

conv1.weight.data.fill_(0.01)

biases에도 동일하게 적용된다. 

conv1.bias.data.fill_(0.01)

nn.Sequential or custom nn.Module

 

초기화 함수를 torch.nn.Module.apply로 넘긴다. 이는 nn.Module의 모든 weight 를 recursive 하게 초기화 한다. 

apply(fn): Applies fn recursively to every submodule (as returned by .children()) as well as self. Typical use includes initializing the parameters of a model (see also torch-nn-init).

Example:

def init_weights(m):
    if isinstance(m, nn.Linear):
        torch.nn.init.xavier_uniform(m.weight)
        m.bias.data.fill_(0.01)

net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
net.apply(init_weights)
 
Comments