更改 np 数组不会自动更改 Torch 张量?

Changing the np array does not change the Torch Tensor automatically?

我正在学习 PyTorch 的基础教程,遇到了 NumPy 数组和 Torch 张量之间的转换。文档说:

The Torch Tensor and NumPy array will share their underlying memory locations, and changing one will change the other.

但是,在下面的代码中似乎并非如此:

import numpy as np

a = np.ones((3,3))
b = torch.from_numpy(a)

np.add(a,1,out=a)
print(a)
print(b)

在上述情况下,我看到更改自动反映在输出中:

[[2. 2. 2.]
 [2. 2. 2.]
 [2. 2. 2.]]
tensor([[2., 2., 2.],
        [2., 2., 2.],
        [2., 2., 2.]], dtype=torch.float64)

但是当我写这样的东西时不会发生同样的事情:

a = np.ones((3,3))
b = torch.from_numpy(a)

a = a + 1
print(a)
print(b)

我得到以下输出:

[[2. 2. 2.]
 [2. 2. 2.]
 [2. 2. 2.]]
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]], dtype=torch.float64)

我在这里错过了什么?

任何时候你写一个 = 登录 Python 你都在创建一个新对象。

所以在 第二种情况 中表达式的右侧使用原始 a 然后计算为一个新对象,即 a + 1,它替换了原来的一种。 b仍然指向原来a的内存位置,但现在a指向内存中的新对象。

换句话说,在 a = a + 1 中,表达式 a + 1 创建一个新对象,然后 Python 将该新对象分配给名称 a

然而,对于 a += 1,Python 使用参数 1 调用 a 的就地添加方法 (__iadd__)。

numpy 代码:np.add(a,1,out=a),在第一种情况下负责将该值添加到现有数组中。

(感谢@Engineero and @Warren Weckesser在评论中指出这些解释)