从张量复制构造:用户警告
copy construct from a tensor: USER WARNING
我正在从正态分布中创建一个随机张量,因为这个张量在 NN 中用作权重,要添加 requires_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
我正在从正态分布中创建一个随机张量,因为这个张量在 NN 中用作权重,要添加 requires_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