Pytorch UserWarning:要从tensor复制构造,建议使用sourceTensor.clone().detach()

Pytorch UserWarning:要从tensor复制构造,建议使用sourceTensor.clone().detach(),pytorch,Pytorch,我是PyTorch的新手,我正在尝试用它编码 所以我有一个名为OH的函数,它固定一个数字,然后返回一个像这样的向量 def OH(x,end=10,l=12): x = T.LongTensor([[x]]) end = T.LongTensor([[end]]) one_hot_x = T.FloatTensor(1,l) one_hot_end = T.FloatTensor(1,l) first=one_hot_x.zero_().scatter

我是PyTorch的新手,我正在尝试用它编码 所以我有一个名为
OH
的函数,它固定一个数字,然后返回一个像这样的向量

  def OH(x,end=10,l=12):
    x = T.LongTensor([[x]])
    end = T.LongTensor([[end]])
    one_hot_x = T.FloatTensor(1,l)
    one_hot_end = T.FloatTensor(1,l)
    first=one_hot_x.zero_().scatter_(1,x,1)
    second=one_hot_end.zero_().scatter_(1,end,1)
    vector=T.cat((one_hot_x,one_hot_end),dim=1)
    return vector
OH(0)
output:
tensor([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
         0., 0., 0., 0., 1., 0.]])
  def act(self,obs):
    #state=T.tensor(obs).to(device)
    state=obs.to(device)
    actions=self.forward(state)
    action=T.argmax(actions).item()
现在我有一个NN,它接受这个输出和返回数字,但是这个警告总是出现在我的编译中

online.act(OH(obs))
output:
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:17: 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).
4
我试图使用
online.act(OH(obs.clone().detach())
,但它给了我同样的警告

代码运行良好,结果良好,但我需要理解这个警告

编辑 以下是具有act功能的我的NN

class Network(nn.Module):
  def __init__(self,lr,n_action,input_dim):
    super(Network,self).__init__()
    self.f1=nn.Linear(input_dim,128)
    self.f2=nn.Linear(128,64)
    self.f3=nn.Linear(64,32)
    self.f4=nn.Linear(32,n_action)
    #self.optimizer=optim.Adam(self.parameters(),lr=lr)
    #self.loss=nn.MSELoss()
    self.device=T.device('cuda' if T.cuda.is_available() else 'cpu')
    self.to(self.device)

  def forward(self,x):
    x=F.relu(self.f1(x))
    x=F.relu(self.f2(x))
    x=F.relu(self.f3(x))
    x=self.f4(x)
    return x

  def act(self,obs):
    state=T.tensor(obs).to(device)
    actions=self.forward(state)
    action=T.argmax(actions).item()

    return action

问题是,您正在网络上接收act函数的张量,然后将其另存为张量 只要去掉像这样的动作中的张量

  def OH(x,end=10,l=12):
    x = T.LongTensor([[x]])
    end = T.LongTensor([[end]])
    one_hot_x = T.FloatTensor(1,l)
    one_hot_end = T.FloatTensor(1,l)
    first=one_hot_x.zero_().scatter_(1,x,1)
    second=one_hot_end.zero_().scatter_(1,end,1)
    vector=T.cat((one_hot_x,one_hot_end),dim=1)
    return vector
OH(0)
output:
tensor([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
         0., 0., 0., 0., 1., 0.]])
  def act(self,obs):
    #state=T.tensor(obs).to(device)
    state=obs.to(device)
    actions=self.forward(state)
    action=T.argmax(actions).item()
非常感谢你