【问题标题】:Custom weight initialization in PyTorchPyTorch 中的自定义权重初始化
【发布时间】:2018-07-03 01:52:54
【问题描述】:

PyTorch 中实现custom weight initialization 方法的正确方法是什么?

我相信我不能直接向“torch.nn.init”添加任何方法,但希望使用我自己的专有方法初始化模型的权重。

【问题讨论】:

    标签: python pytorch


    【解决方案1】:

    你可以定义一个方法来根据每一层初始化权重:

    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)
    

    【讨论】:

      【解决方案2】:

      请参阅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)
      

      【讨论】:

        猜你喜欢
        • 2019-07-21
        • 1970-01-01
        • 2018-09-05
        • 2018-09-01
        • 1970-01-01
        • 2020-03-15
        • 2021-06-25
        • 1970-01-01
        相关资源
        最近更新 更多