- x.data 与 x.detach() 返回的 tensor :
相同:
都和 x 共享同一块数据
都和 x 的 计算历史无关
requires_grad = False
不同:
y=x.data 在某些情况下不安全, 某些情况, 指的就是 上述 inplace operation 的第二种情况
- .detach(),从反向传播图中切割出来,不参与反向传播。但是会参与前向计算,因为储存空间共享。
- .cpu().item() 标量可以这样提取数值。
- .cpu().detach().numpy(),使用numpy之前,一定要先.cpu();因为numpy只支持cpu上的数据。没有使用numpy和item的数据操作,返回的都是Tensor类型。
- 转移数据到GPU上
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
a = torch.rand([3,3]).to(device)
参考博客:
浅谈 PyTorch 中的 tensor 及使用