Pytorch中ndarray tensor list互转

1.ndarray->tensor :

b=torch.from_numpy(a)

2.tensor->ndarray:

b=a.numpy()

'''
但这么写会报错……
RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.
'''
# 修改为
b=a.detach().numpy()

'''
gpu上的tensor不能直接转为numpy
'''
b=a.cpu().numpy()

3.ndarray->list

b=a.tolist()

4.list->ndarray

b=numpy.array(a)

转载于:https://www.cnblogs.com/xym4869/p/11417180.html

你可能感兴趣的:(Pytorch中ndarray tensor list互转)