list转tensor
tensor=torch.Tensor(list)
list转numpy
ndarray = np.array(list)
numpy转list
list = ndarray.tolist()
numpy转tensor
tensor = torch.from_numpy(ndarray)
tensor转list
# 先转numpy,后转list
list = tensor.numpy().tolist()
tensor转numpy
ndarray = tensor.numpy()
# *gpu上的tensor不能直接转为numpy,应先放回cpu中
ndarray = tensor.cpu().numpy()
CPU tensor和GPU tensor之间的转换
CPU ---> GPU: data.cuda()
GPU ---> CPU: data.cpu()
如果tensor是标量的话,可以直接使用 item() 函数(只能是标量)将值取出来:
print(data.item())