[英]How to mask weights in PyTorch weight parameters?
我試圖在 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
。 我不確定為什么這里有錯誤。
按元素操作總是返回一個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)
免責聲明:在權重上使用=
(賦值)時,您將替換參數的權重張量。 這可能會對圖形產生不良影響。 優化步驟。
將 Tensorfloat 變量更改為參數變量的一種有效方法:
self.wfx.weight = torch.nn.parameter.Parameter((self.wfx.weight.data * self.mask_use))
我希望這會很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.