如何将 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'>热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短