【Pytorch tensor】Tensor的进阶操作

文章目录

主题

记录有关tensor操作的进阶版,有一个初级版,可以在此参考
后续用到之后进行更新

梯度相关

  • torch.stack;通常而言我们在拿到一个list of tensors的时候,需要通过将内部tensor进行detach clone cpu numpy等系列操作后才能通过构造函数 torch.tensor 得到一个数据相同的tensor of tensors。但是其中的操作detach 与 clone都是会清除当前gradient的方法。当我们需要得到当前数据的同时保存当前梯度时,需要使用torch.stack这个函数。值得注意的是,该方法允许我们直接传入list of tensors,十分方便。当我们需要将 list of tensors -> higher dim tensor的时候,可以直接调用torch.stack,然后手动禁止或者清除gradient。即test_tensor = torch.stack(list_of_tensor) + test_tensor.grad = None
    Document source

猜你喜欢

转载自blog.csdn.net/Petersburg/article/details/124194379