1、Tensor 转Numpy
import torch as t
import numpy as np
a = t.ones(5)
a
Out[23]: tensor([1., 1., 1., 1., 1.])
b = a.numpy()# Tensor -> Numpy
b
Out[25]: array([1., 1., 1., 1., 1.], dtype=float32)
2、Numpy 转Tensor
import torch as t
import numpy as np
a = np.ones(5)
b = t.from_numpy(a) # Numpy->Tensor
a
Out[29]: array([1., 1., 1., 1., 1.])
b
Out[30]: tensor([1., 1., 1., 1., 1.], dtype=torch.float64)