如何将 NumPy ndarray 转换为 PyTorch Tensor,反之亦然?
PyTorch张量就像numpy.ndarray。这两者之间的区别在于张量利用GPU来加速数值计算。我们使用函数将numpy.ndarray转换为PyTorch张量。并且张量被转换为numpy.ndarray使用.方法。torch.from_numpy()numpy()
脚步
导入所需的库。在这里,所需的库是torch和numpy。
创建一个numpy.ndarray或PyTorch张量。
转换numpy.ndarray使用到PyTorch张量函数或PyTorch张量转换为numpy.ndarray使用。方法。torch.from_numpy()numpy()
最后,打印转换后的张量或numpy.ndarray。
示例1
以下Python程序将numpy.ndarray转换为PyTorch张量。
# import the libraries
import torch
import numpy as np
# Create anumpy.ndarray"a"
a = np.array([[1,2,3],[2,1,3],[2,3,5],[5,6,4]])
print("a:\n", a)
print("Type of a :\n", type(a))
# Convert thenumpy.ndarrayto tensor
t = torch.from_numpy(a)
print("t:\n", t)
print("Type after conversion:\n", type(t))输出结果当你运行上面的代码时,它会产生以下输出
a:
[[1 2 3]
[2 1 3]
[2 3 5]
[5 6 4]]
Type of a :
<class 'numpy.ndarray'>
t:
tensor([[1, 2, 3],
[2, 1, 3],
[2, 3, 5],
[5, 6, 4]], dtype=torch.int32)
Type after conversion:
<class 'torch.Tensor'>示例2
以下Python程序将PyTorch张量转换为numpy.ndarray。
# import the libraries
import torch
import numpy
# Create a tensor "t"
t = torch.Tensor([[1,2,3],[2,1,3],[2,3,5],[5,6,4]])
print("t:\n", t)
print("Type of t :\n", type(t))
# Convert the tensor to numpy.ndarray
a = t.numpy()
print("a:\n", a)
print("Type after conversion:\n", type(a))输出结果当你运行上面的代码时,它会产生以下输出
t:
tensor([[1., 2., 3.],
[2., 1., 3.],
[2., 3., 5.],
[5., 6., 4.]])
Type of t :
<class 'torch.Tensor'>
a:
[[1. 2. 3.]
[2. 1. 3.]
[2. 3. 5.]
[5. 6. 4.]]
Type after conversion:
<class 'numpy.ndarray'>