python中list,ndarray,Tensor间的转化

1 篇文章 0 订阅
1 篇文章 0 订阅

一、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,需要间接转换

二、例程

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'> 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值