syl*_*ong 4 python numpy pytorch
I am following the 60-minute blitz on PyTorch but have a question about conversion of a numpy array to a tensor. Tutorial example here.
This piece of code:
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)
Run Code Online (Sandbox Code Playgroud)
yields
[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
However
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
a = a + 1 #the diff is here
print(a)
print(b)
Run Code Online (Sandbox Code Playgroud)
yields
[2. 2. 2. 2. 2.]
tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
Why are the outputs different?
这实际上与 PyTorch 关系不大。相比
import numpy as np
a = np.ones(5)
b = a
Run Code Online (Sandbox Code Playgroud)
其次是
np.add(a, 1, out=a)
print(b)
Run Code Online (Sandbox Code Playgroud)
或者
a = a + 1
print(b)
Run Code Online (Sandbox Code Playgroud)
np.add(a, 1, out=a)
和之间有区别a = a + 1
。在前者中,您保留a
具有不同值(2
而不是1
)的相同对象(数组);在后者中,您将获得一个新数组,该数组绑定到相同的变量名称a
并且值为2
. 但是,“原始”a
被丢弃,除非有其他 ( b
) 指向它,否则将被释放。换句话说,第一个操作是就地操作,而后一个操作是异地操作。由于b
保留了最初在 处找到的数组a
,重新分配a + 1
到a
不会影响 的值b
。另一种就地突变语法是
a[:] = a + 1
print(b)
Run Code Online (Sandbox Code Playgroud)
关于PyTorch,非常简单。from_numpy
创建一个别名实际对象(数组)的张量,因此它等效b = a
于我的第一个片段中的行。张量将跟踪a
调用时命名的数组中的变化,而不是名称a
指向的内容的变化。
归档时间: |
|
查看次数: |
2481 次 |
最近记录: |