PyTorch conversion between tensor and numpy array: the addition operation

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?

Jat*_*aki 5

这实际上与 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 + 1a不会影响 的值b。另一种就地突变语法是

a[:] = a + 1
print(b)
Run Code Online (Sandbox Code Playgroud)

关于PyTorch,非常简单。from_numpy创建一个别名实际对象(数组)的张量,因此它等效b = a于我的第一个片段中的行。张量将跟踪a调用时命名的数组中的变化,而不是名称a指向的内容的变化。