【问题标题】:Is there a PyTorch counterpart of Tensorflow Keras methods get_weights and set_weights?是否有 Tensorflow Keras 方法 get_weights 和 set_weights 的 PyTorch 对应物?
【发布时间】:2021-11-17 16:46:58
【问题描述】:

PyTorch 框架中是否有 TF/Keras 方法 get_weights()set_weights() 的对应物,用于快速获取模型的权重并设置新的权重? 或者也许还有其他简单的方法可以实现这一点?

【问题讨论】:

    标签: python tensorflow keras deep-learning pytorch


    【解决方案1】:

    set_weightsTENSORFLOW

    How to change the weights of a pytorch model?

    您要手动更改权重吗?

    如果是这样,您可以将代码包装在 torch.no_grad() 守卫中:

    with torch.no_grad():
        model.fc.weight[0, 0] = 1.
    

    防止 Autograd 跟踪这些更改。

    How to manually set the weights in a two layer linear model?

    您只需将其包装在 torch.no_grad() 块中并根据需要操作参数:

    model = torch.nn.Sequential(nn.Linear(10, 1, bias=False))
    
    with torch.no_grad():
        model[0].weight = nn.Parameter(torch.ones_like(model[0].weight))
        model[0].weight[0, 0] = 2.
        model[0].weight.fill_(3.)
    

    【讨论】:

      猜你喜欢
      • 2019-04-25
      • 2022-08-21
      • 2019-02-02
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 2018-03-30
      相关资源
      最近更新 更多