Pytorch中torch.tensor、list、numpy之间的相互转换

1. torch.tensor、list、numpy之间的相互转换

import torch
import numpy as np
# int -> tensor -> int
a = torch.tensor(1)
b = a.item()
 
# list -> tensor(cpu)
l0 = [1, 2, 3]
t = torch.Tensor(l0)
 
# tensor(cpu) -> numpy -> list
a = t.numpy()
l1 = t.numpy().tolist()
 
# list -> numpy
a0 = np.array(l0)
 
# numpy -> tensor(cpu)
t1 = torch.from_numpy(a0)
 
# tensor(cpu) -> tensor(cuda)
tc = t1.cuda()
 
# tensor(cuda) -> list
l2 = tc.cpu().numpy().tolist()
 

2. 链接

  • pytorch中tensor与其他数据结构的转化(int, list, array)
  • python中list、numpy、torch.tensor之间的相互转换

你可能感兴趣的:(Pytorch基础,numpy,pytorch,python,深度学习)