在《动手深度学习-Pytorch》教程中看到了如下内容:
索引
我们还可以使用类似NumPy的索引操作来访问Tensor的一部分,需要注意的是:索引出来的结果与原数据共享内存,也即修改一个,另一个会跟着修改。
y = x[0, :]
y += 1
print(y)
print(x[0, :]) # 源tensor也被改了
输出
tensor([1.6035, 1.8110, 0.9549])
tensor([1.6035, 1.8110, 0.9549])
然后我自己也试了一下
import torch
x = torch.zeros(5, 3, dtype=torch.long)
y = x[0,:]
y = y+1
print(y)
print(x[0,:])
输出
tensor([1, 1, 1])
tensor([0, 0, 0])
为什么x张量不变呢。后来发现是因为y=y+1 跟 y += 1 是不一样的,改成如下就好了
import torch
x = torch.zeros(5, 3, dtype=torch.long)
y = x[0,:]
y += 1
print(y)
print(x[0,:])
输出
tensor([1, 1, 1])
tensor([1, 1, 1])