Neural network 从张量复制构造:用户警告

Neural network 从张量复制构造:用户警告,neural-network,pytorch,torch,Neural Network,Pytorch,Torch,我正在从正态分布创建一个随机张量,由于该张量用作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_g

我正在从正态分布创建一个随机张量,由于该张量用作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).
我收到如下用户警告错误:

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\u 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