Python中的list、numpy、torch.tensor相互转换

一、list、numpy互转

a = np.array(a)   【将list转换成numpy】

a = a.tolist()        【将numpy转换成list】

import numpy as np
a = [1, 2, 3]
print(type(a))
print(a)
a = np.array(a)
print(type(a))
print(a)
# <class 'list'>
# [1, 2, 3]
# <class 'numpy.ndarray'>
# array([1, 2, 3])

b = np.array([1, 2, 3])
print(type(b))
print(b)
b = b.tolist()
print(type(b))
print(b)
# <class 'numpy.ndarray'>
# array([1, 2, 3])
# <class 'list'>
# [1, 2, 3]

二、list、torch.Tensor互转

a = torch.Tensor(a)        【将list转换成torch.Tensor】

a = tensor.numpy().tolist()        【将torch.Tensor转换成list】

常用的不同数据类型的Tensor

32位的浮点型 torch.FloatTensor

64位的浮点型 torch.DoubleTensor

16位的整形 torch.ShortTensor

32位的整形 torch.IntTensor

64位的整形 torch.LongTensor

import torch
import numpy as np

a = [1, 2, 3]
print(type(a))
print(a)
tensor = torch.Tensor(a)
print(type(tensor))
print(tensor)
tensor = torch.IntTensor(a)
print(type(tensor))
print(tensor)

# <class 'list'>
# [1, 2, 3]
# <class 'torch.Tensor'>
# tensor([1., 2., 3.])
# <class 'torch.Tensor'>
# tensor([1, 2, 3], dtype=torch.int32)

a = torch.Tensor([1, 2, 3])
print(type(a))
print(a)
a = a.numpy().tolist()
print(type(a))
print(a)

# <class 'torch.Tensor'>
# tensor([1., 2., 3.])
# <class 'list'>
# [1.0, 2.0, 3.0]

三、numpy、torch.Tensor互转

a = tensor.numpy()        【将torch.Tensor转换成numpy】

a = tensor.cpu().numpy()        【GPU上的tensor不能直接转换成numpy, 转换到CPU上再转换】

a = torch.from_numpy(a)        【将numpy转换成torch.Tensor】

import numpy as np
import torch

a = np.array([1, 2, 3])
print(type(a))
print(a)
a = torch.from_numpy(a)
print(type(a))
print(a)
# <class 'numpy.ndarray'>
# [1 2 3]
# <class 'torch.Tensor'>
# tensor([1, 2, 3], dtype=torch.int32)

a = torch.Tensor([1, 2, 3])
print(type(a))
print(a)
a = a.numpy()
print(type(a))
print(a)
# <class 'torch.Tensor'>
# tensor([1., 2., 3.])
# <class 'numpy.ndarray'>
# [1. 2. 3.]

a = torch.Tensor([1, 2, 3]).cuda()
a.to(device)
print(type(a))
print(a)
a = a.cpu().numpy()
print(type(a))
print(a)
# <class 'torch.Tensor'>
# tensor([1., 2., 3.], device='cuda:0')
# <class 'numpy.ndarray'>
# [1. 2. 3.]

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值