如何将NumPy ndarray转换为PyTorch张量,反之亦然?
PyTorch 张量类似于numpy.ndarray。两者之间的区别在于,张量利用GPU来加速数值计算。我们可以使用函数torch.from_numpy()将numpy.ndarray转换为PyTorch张量。而张量可以使用.numpy()方法转换为numpy.ndarray。
步骤
导入所需的库。这里,所需的库是torch和numpy。
创建一个numpy.ndarray或PyTorch张量。
使用torch.from_numpy()函数将numpy.ndarray转换为PyTorch张量,或使用.numpy()方法将PyTorch张量转换为numpy.ndarray。
最后,打印转换后的张量或numpy.ndarray。
示例1
下面的Python程序将numpy.ndarray转换为PyTorch张量。
# import the libraries
import torch
import numpy as np
# Create a numpy.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 the numpy.ndarray to 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'>
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP