
1、torch.Tensor 转 numpy
import torch
#ndarray = tensor.numpy()
#ndarray = tensor.cpu().numpy()
x = torch.randn(10)
arr = x.numpy()
print(x)
print(arr)
#print(arr[0])
for z in arr:
print(z)
tensor([-0.3291, -0.9795, -0.2297, -0.2418, 0.1019, 0.0910, -0.8200, 2.0651,
1.3605, -0.1598])
[-0.32914537 -0.9794707 -0.22972724 -0.24182056 0.1019427 0.09099799
-0.81996155 2.0650983 1.3605494 -0.15978478]
-0.32914537
-0.9794707
-0.22972724
-0.24182056
0.1019427
0.09099799
-0.81996155
2.0650983
1.3605494
-0.15978478
2、numpy 转 torch.Tensor
tensor = torch.from_numpy(ndarray)
import torch import numpy as np #tensor = torch.from_numpy(ndarray) arr = np.array([[0,1,2,3], [4,5,6,7], [8,9,10,11]]) z = torch.from_numpy(arr) print(arr) print(z)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]], dtype=torch.int32)
3、torch.Tensor 转 list
list = tensor.numpy().tolist()
import torch m = torch.randn(10) m_list = m.numpy().tolist() print(m) print(m_list)
tensor([-0.6831, -0.2703, 1.0755, -2.3199, -1.1258, -0.3573, -1.4791, 0.8089,
0.1605, -0.2801])
[-0.6831207871437073, -0.2703227400779724, 1.075508713722229, -2.3199448585510254, -1.125805377960205, -0.3572894036769867, -1.4790899753570557, 0.808900773525238, 0.16054047644138336, -0.2800646126270294]
4、list 转 numpy
ndarray = np.array(list)
import torch z_list = [0, 1, 2, 3, 4, 5] z_arr = np.array(z_list) print(z_list) print(z_arr)
[0, 1, 2, 3, 4, 5] [0 1 2 3 4 5]
5、numpy 转 list
list = ndarray.tolist()
import torch import numpy as np #list = ndarray.tolist() z_arr = np.array([[0,1,2,3], [4,5,6,7], [8,9,10,11]]) z_list = z_arr.tolist() print(z_arr) print(z_list)
[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]