【问题标题】:Pytorch: how to change requires_grad to be true in an OrderedDictPytorch:如何在 OrderedDict 中将 requires_grad 更改为 true
【发布时间】:2021-07-04 17:38:44
【问题描述】:

假设我有一个来自torch.nn 的神经网络对象,默认情况下requires_grad 的参数是False。我想把它改成True。但是以下幼稚的方法失败了:

From torch import nn
a = nn.Linear(1, 1)
a.state_dict()[‘weight’].requires_grad = True
print(a.state_dict()[‘weight’].requires_grad)

结果是False。谁能解释问题是什么以及如何解决?谢谢!我的 Torch 版本是 1.7.1。

【问题讨论】:

    标签: pytorch ordereddict


    【解决方案1】:

    默认情况下 trainable nn 对象 parameters 将具有 requires_grad=True。 您可以通过以下方式验证:

    import torch.nn as nn
    
    layer = nn.Linear(1, 1)
    
    for param in layer.parameters():
        print(param.requires_grad)
    
    # or use
    print(layer.weight.requires_grad)
    print(layer.bias.requires_grad)
    

    更改requires_grad 状态:

    for param in layer.parameters():
        param.requires_grad = False # or True
    

    【讨论】:

      猜你喜欢
      • 2019-01-15
      • 2018-10-09
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 2013-05-10
      • 2011-06-16
      相关资源
      最近更新 更多