我们很容易用 numpy() 和 from_numpy() 将 Tensor 和NumPy中的数组相互转换。

但是需要注意的点是: 这两个函数所产⽣生的的 Tensor 和NumPy中的数组共享相同的内存(所以他们之间的转换很快),改变其中⼀个时另⼀个也会改变!!!

还有一个常用的将NumPy中的array转换成 Tensor 的方法就是 torch.tensor() , 需要注意的
是,此方法总是会进行数据拷贝(就会消耗更多的时间和空间),所以返回的 Tensor 和原来的数据不再共享内存。

Tensor转NumPy

使用numpy()将 Tensor 转换成NumPy数组:

a = torch.ones(5)
b = a.numpy()
print(a, b)
a += 1
print(a, b)
b += 1
print(a, b)

输出为:

tensor([1., 1., 1., 1., 1.]) [1. 1. 1. 1. 1.]
tensor([2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2.]
tensor([3., 3., 3., 3., 3.]) [3. 3. 3. 3. 3.]

NumPy数组转 Tensor

通过使用 from_numpy() 将NumPy数组转换成 Tensor :

import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
print(a, b)
a += 1
print(a, b)
b += 1
print(a, b)

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

所有在CPU上的 Tensor (除了 CharTensor )都支持与NumPy数组相互转换。

此外上面我们提到还有一个常用的方法就是直接用 torch.tensor() 将NumPy数组转换成 Tensor ,需要
注意的是该方法总是会进行数据拷贝,返回的 Tensor 和原来的数据不再共享内存。

c = torch.tensor(a)
a += 1
print(a, c)

输出为:

[4. 4. 4. 4. 4.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)