一、list,ndarray,Tensor间的转化
废话不多说,看表格就行
数据类型 | 所属包 |
---|---|
list | python |
ndarray | numpy |
Tensor | pytorch |
转化类型 | 对应API | 注意点 |
---|---|---|
list转换为ndarray | numpy.array() | |
ndarray转换为list | ndarray对象.tolist() | |
list转换为Tensor | torch.tensor() | list中的int类型数据转换后会变为folat,若需要保持int,则转换时需要加上类型 |
Tensor转换为list | Tensor对象.tolist() | |
ndarray转换为Tensor | torch.from_numpy() torch.tensor() | |
Tensor(CPU)转换为ndarray | Tensor对象.numpy() | GPU上的Tensor不能直接转换为numpy,需要间接转换 |
Tensor(GPU)转换为ndarray | Tensor对象.cpu().numpy() | GPU上的Tensor不能直接转换为numpy,需要间接转换 |
二、例程
import numpy as np
import torch
#list转换为ndarray
li=[[1,2,3],[4,5,6],[7,8,9]]
a=np.array(li) #list转换为ndarray
print(a)
print(type(a),'\n')
#ndarray转换为list
b=a.tolist()#ndarray转换为list
print(b)
print(type(b),'\n')
#list转换为Tensor
li=[[1,2,3],[4,5,6],[7,8,9]]
c=torch.tensor(li) #list转换为Tensor
print(c)
print(type(c),'\n')
#Tensor转换为list
d=c.tolist() #Tensor转换为list
print(d)
print(type(d),'\n')
#ndarray转换为Tensor
nd=np.arange(0,12).reshape(3,4)
e=torch.from_numpy(nd) #ndarray转换为Tensor
# e=torch.tensor(nd) #ndarray转换为Tensor
print(e)
print(type(e),'\n')
#Tensor转换为ndarray
f=e.numpy()
print(f)
print(type(f),'\n')
运行结果
[[1 2 3]
[4 5 6]
[7 8 9]]
<class 'numpy.ndarray'>
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
<class 'list'>
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
<class 'torch.Tensor'>
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
<class 'list'>
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]], dtype=torch.int32)
<class 'torch.Tensor'>
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
<class 'numpy.ndarray'>