我正在从正态分布中创建一个随机张量,并且由于该张量在NN中用作权重,因此要添加require_grad属性,我使用torch.tensor()如下:
import torch
input_dim, hidden_dim = 3, 5
norm = torch.distributions.normal.Normal(loc=0, scale=0.01)
W = norm.sample((input_dim, hidden_dim))
W = torch.tensor(W, requires_grad=True)
我收到如下用户警告错误:
UserWarning: To copy construct from a tensor,
it is recommended to use sourceTensor.clone().detach() or
sourceTensor.clone().detach().requires_grad_(True),
rather than torch.tensor(sourceTensor).
是否有其他方法可以实现上述目标?谢谢
您可以仅将W.requires_grad
设置为True
import torch
input_dim, hidden_dim = 3, 5
norm = torch.distributions.normal.Normal(loc=0, scale=0.01)
W = norm.sample((input_dim, hidden_dim))
W.requires_grad = True