Python教程

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

本文主要是介绍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.]

这篇关于Python中的list、numpy、torch.tensor相互转换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!