import torch
import numpy as np
定义一个np的数组
demo_ndndarray = np.random.randint(2,10,[1,5])
demo_ndndarray
Hint:numpy详细笔记和numpy随机数组笔记有兴趣的可以看看噢
array([[3, 7, 3, 6, 3]])
numpy 转为 pytorch格式
demo_tensor = torch.from_numpy(demo_ndndarray)
demo_tensor
tensor([[3, 7, 3, 6, 3]], dtype=torch.int32)
torch 转为numpy
demo1_ndndarray = demo_tensor.numpy()
demo1_ndndarray
array([[3, 7, 3, 6, 3]])
numpy 转为 list格式
demo_list = list(demo_ndndarray.reshape(len(demo_ndndarray[0])))
demo_list
[3, 7, 3, 6, 3]
list 转为 numpy 格式
demo2_ndndarray = np.array(demo_list)
demo2_ndndarray
array([3, 7, 3, 6, 3])