Tensor、Numpy、List之间的互相转化

174 阅读1分钟

numpy 与 tensor 相互转化

# 将 Tensor 转化为 numpy
img = img.numpy()   # torch.Tensor 转化为 numpy.ndarray


# 将 numpy 转化为 Tensor
img = torch.from_numpy(img)  # numpy.ndarray 转化为 torch.Tensor.float64


list 与 tensor 相互转化

# 将 list 转化为 Tensor
img = torch.tensor(img)  



# 将 Tensor 转化为 list
img  = img .tolist() 


list 与 numpy 相互转化

# 将 list 转化为 numpy
img = np.array(img)

# 将 numpy 转化为 list
img = img.tolist()


pytorch中将CDDA.tensor数据转换为numpy数据

predicte = predicte.data.cpu().numpy()


pytorch中,读取tensor变量中的每一个值:

t.item()