深度学习pytorch- tensor和numpy相互转换torch.from_numpy()

  1. 处理批量数据时, 经常需要tensor和numpy的相互转化
  2. torch.from_numpy(x), 将x 转换为torch类型
  3. y.numpy(), 将y由tensor转化为numpy
import numpy as np
x = np.array([[1, 2], [3, 4.]])
x

array([[1., 2.],
[3., 4.]])

# Convert the numpy array to a torch tensor.
y = torch.from_numpy(x)
y

tensor([[1., 2.],
[3., 4.]], dtype=torch.float64)

x.dtype, y.dtype

(dtype(‘float64’), torch.float64)

# Convert a torch tensor to a numpy array
z = y.numpy()
z

array([[1., 2.],
[3., 4.]])

你可能感兴趣的:(deep,learning,深度学习,numpy,python)