【发布时间】:2018-07-03 01:52:54
【问题描述】:
在PyTorch 中实现custom weight initialization 方法的正确方法是什么?
我相信我不能直接向“torch.nn.init”添加任何方法,但希望使用我自己的专有方法初始化模型的权重。
【问题讨论】:
在PyTorch 中实现custom weight initialization 方法的正确方法是什么?
我相信我不能直接向“torch.nn.init”添加任何方法,但希望使用我自己的专有方法初始化模型的权重。
【问题讨论】:
你可以定义一个方法来根据每一层初始化权重:
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv2d') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
然后将其应用到您的网络:
model = create_your_model()
model.apply(weights_init)
【讨论】:
请参阅https://discuss.pytorch.org/t/how-to-initialize-weights-bias-of-rnn-lstm-gru/2879/2 以供参考。
你可以的
weight_dict = net.state_dict()
new_weight_dict = {}
for param_key in state_dict:
# custom initialization in new_weight_dict,
# You can initialize partially i.e only some of the variables and let others stay as it is
weight_dict.update(new_weight_dict)
net.load_state_dict(new_weight_dict)
【讨论】: