gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:04:42 26 4
gpt4 key购买 nike

我正在阅读 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)

在上述情况下,我看到更改自动反射(reflect)在输出中:

[[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 += 1,Python 调用 a 的就地加法 (__iadd__) 并带有参数 1。

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

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

关于python - 更改 np 数组不会自动更改 Torch 张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52374062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com