首页 > 解决方案 > 用函数包装 Pytorch 模型的所有参数

问题描述

我希望能够用一个函数包装我的 PyTorch 模型的所有卷积参数(权重和偏差),例如 softmax(权重)、sigmoid(权重)或 alpha*weight 等。有没有办法让这个函数成为使用钩子等的图表?

例如:假设我有一个名为 net 的模型,它具有我感兴趣的可训练参数,仅在卷积层中:

for module in net.modules():
   if is_conv_layer(module):
      module.weight # This is the weight I am interested in.

因此,替换权重的值很容易:

for module in net.modules():
   if is_conv_layer(module):
      module.weight.data = sigmoid(module.weight.data)

但是,我还想在图中添加 sigmoid,以便在计算反向传播时也考虑 sigmoid。

标签: pytorch

解决方案


推荐阅读