PyTorch 报 “AttributeError: ‘Tensor’ object has no attribute ‘detach’” 的原因是因为 detach()
方法只在PyTorch 1.5 版本及以上可用,而较老的版本中可能不存在该方法。
解决办法有两种:
- 升级 PyTorch 版本。在命令行中使用以下命令更新 PyTorch:
pip install --upgrade torch
这会将 PyTorch 更新至最新版本,从而解决 detach()
方法不可用的问题。
- 使用
.cpu().detach()
方式代替detach()
方法,即将detach()
改为.cpu().detach()
。
例如:
import torch
x = torch.tensor([1, 2, 3], requires_grad=True)
y = x ** 2
# detach() 方法(只在 PyTorch 1.5 及以上可用)
z1 = y.detach()
print(z1) # tensor([1, 4, 9])
# .cpu().detach() 方式
z2 = y.cpu().detach()
print(z2) # tensor([1, 4, 9])
以上是关于 PyTorch 报 AttributeError: 'Tensor' object has no attribute 'detach'
错误的原因和解决办法攻略。