torch中Tensor和numpy相互转化

Numpy转为Tensor

使用torch.from_numpy()

import torch
B = torch.from_numpy(A)

Tensor转为Numpy

使用data.numpy()

import torch
C = B.numpy()

可能会出现报错如下
TypeError: can’t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor
只要改为

C = B.cpu().numpy()

你可能感兴趣的:(python)