python中list,ndarray,Tensor间的转换小结

 更新时间:2024年02月02日 11:30:58   作者:tao355667  
数据类型转换是常见的功能,本文主要介绍了python中list,ndarray,Tensor间的转换小结,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧

一、list,ndarray,Tensor间的转化

废话不多说,看表格就行

数据类型所属包
listpython
ndarraynumpy
Tensorpytorch
转化类型对应API注意点
list转换为ndarraynumpy.array()
ndarray转换为listndarray对象.tolist()
list转换为Tensortorch.tensor()list中的int类型数据转换后会变为folat,若需要保持int,则转换时需要加上类型
Tensor转换为listTensor对象.tolist()
ndarray转换为Tensortorch.from_numpy()torch.tensor()
Tensor(CPU)转换为ndarrayTensor对象.numpy()GPU上的Tensor不能直接转换为numpy,需要间接转换
Tensor(GPU)转换为ndarrayTensor对象.cpu().numpy()GPU上的Tensor不能直接转换为numpy,需要间接转换

ndarray --> PILimage

From PIL import Image
y = Image.fromarray(array)

PILimage --> ndarray

From PIL import Image
image = Image.open(“…..”)
img = np.asarray(image)

Tensor --> ndarray

import numpy as np
yy = np.array(tensor) 

ndarray --> Tensor

tensor = torch.from_numpy(ndarray)

tip:返回的张量和ndarray共享同一内存。对张量的修改将反映在ndarray中,反之亦然。

ndarray数据转换数据类型

array.astype(np.uint8)  

将array复制,并将数据类型强制转化为int8

ndarray --> List

import numpy as np
n = np.array([[1,2],[3,4],[5,6]])
m = n.tolist()

List --> Tensor

tensor = torch.tensor(list)

二、例程

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'> 

到此这篇关于python中list,ndarray,Tensor间的转化小结的文章就介绍到这了,更多相关python list,ndarray,Tensor转化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论