我正在尝试在PyTorch中屏蔽(强制为零)特定的重量值。我尝试掩盖的权重在def __init__
class LSTM_MASK(nn.Module):
def __init__(self, options, inp_dim):
super(LSTM_MASK, self).__init__()
....
self.wfx = nn.Linear(input_dim, curernt_output, bias=add_bias)
掩码在def __init__
中也定义为
self.mask_use = torch.Tensor(curernt_output, input_dim)
掩码是一个常量,掩码参数的.requires_grad_()
是False
。现在,在课程的def forward
部分中,我尝试在完成线性运算之前对权重参数和掩码进行逐元素乘法
def forward(self, x):
....
self.wfx.weight = self.wfx.weight * self.mask_use
wfx_out = self.wfx(x)
我收到一条错误消息:
self.wfx.weight = self.wfx.weight * self.mask_use
File "/home/xyz/anaconda2/lib/python2.7/site-packages/torch/nn/modules/module.py", line 537, in __setattr__
.format(torch.typename(value), name))
TypeError: cannot assign 'torch.cuda.FloatTensor' as parameter 'weight' (torch.nn.Parameter or None expected)
但是,当我使用.type()
检查两个参数时,它们都以torch.cuda.FloatTensor
出现。我不确定为什么这里有错误。
答案 0 :(得分:1)
按元素操作总是返回FloatTensor
。无法将法线张量分配为weight
层。
有两种可能的解决方法。您可以将其分配给权重的data
属性,可以分配法线张量。
或者您也可以将结果转换为nn.Parameter
本身,然后可以将其分配给wfx.weight
。
以下是同时显示两种方式的示例:
import torch
import torch.nn as nn
wfx = nn.Linear(10, 10)
mask_use = torch.rand(10, 10)
#wfx.weight = wfx.weight * mask_use #your example - this raises an error
# Option 1: write directly to data
wfx.weight.data = wfx.weight * mask_use
# Option 2: convert result to nn.Parameter and write to weight
wfx.weight = nn.Parameter(wfx.weight * mask_use)
免责声明:在权重上使用=
(分配)时,您正在替换参数的权重张量。这可能会对图形的响应产生不良影响。优化步骤。
答案 1 :(得分:0)
将 Tensorfloat 变量更改为参数变量的一种有效方法:
self.wfx.weight = torch.nn.parameter.Parameter((self.wfx.weight.data * self.mask_use))
我希望这会有用。