一、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.]