torch.tensor(sourcetensor)使用和复制张量有什么区别tensor.clone().detach()?
就像torch.tensor(srctsr)总是复制数据一样,tensor.clone().detach()也复制数据。
x = torch.tensor([1, 2, 3])
y1 = x.clone().detach()
y2 = torch.tensor(x)
x[0] = 0
print(y1, y2) # both are same
Run Code Online (Sandbox Code Playgroud)
所以他们看起来是完全一样的。torch.tensor()下面是 PyTorch 文档中给出的关于和 的解释torch.clone().detach()
因此 torch.tensor(x) 等价于 x.clone().detach() 且 torch.tensor(x, require_grad=True) 等价于 x.clone().detach().requires_grad_(True)。建议使用 clone() 和 detach() 的等效方法。
那么,如果它们彼此相当,为什么.clone().detach()比另一个更受青睐呢?
pytorch ×1