一、Tensor和Numpy(array)相互转换
- 我们很容易用
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.]
注:gpu中的Tensor转Numpy
b = a.cpu().detach().numpy()
(二) 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)
- 此外上面我们提到还有一个常用的方法就是直接用
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)
注:Numpy转Tensor后放入gpu中
b = torch.from_numpy(a).cuda()
二、Array和List相互转换
- array转list
import numpy as np
a = np.array(12, np.float32)
list = a.tolist()
- list转array
import numpy as np
a = list()
array = np.array(a)
三、List和Tensor相互转换
- Tensor转list
该转换不能一部完成,通常需要先把tensor转array,再把array转list
list = tensor.numpy().tolist()
- list转Tensor
tensor=torch.Tensor(list)