如何将带有梯度的 PyTorch 张量转换为 NumPy 数组?
要将具有梯度的 Torch 张量转换为 NumPy 数组,首先我们必须将该张量从当前计算图中分离出来。为此,我们使用 Tensor.detach() 操作。此操作将张量从当前计算图中分离出来。现在,我们无法计算相对于此张量的梯度。在 detach() 操作之后,我们使用 .numpy() 方法将其转换为 NumPy 数组。
如果在 GPU 上定义了具有 **requires_grad=True** 的张量,则要将此张量转换为 NumPy 数组,我们必须执行一个额外的步骤。首先,我们必须将张量移动到 CPU,然后执行 **Tensor.detach()** 操作,最后使用 **.numpy()** 方法将其转换为 NumPy 数组。
步骤
导入所需的库。所需的库是 **torch**。
在 CPU 上创建具有梯度的张量。如果在 GPU 上已经定义了具有梯度的张量,则必须将其移动到 CPU。
将张量从当前计算图中分离。您可以使用 **.detach()** 执行此操作。在 **detach()** 操作之后,张量将没有梯度。
接下来,将没有梯度的张量转换为 NumPy 数组。您可以使用 **.numpy()** 将其转换为 NumPy 数组。
打印 NumPy 数组。
示例 1
# import torch library
import torch
# define a tensor with requires gradient true
x = torch.tensor([1.,2.], requires_grad = True)
print("x:", x)
# x.numpy()--> error
x = x.detach().numpy()
print("x:", x)
print("type of x:", type(x))输出
x: tensor([1., 2.], requires_grad=True) x: [1. 2.] type of x: <class 'numpy.ndarray'>
示例 2
import torch
# define device
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# define tensors with gradients on gpu
x = torch.tensor([1.,2.], requires_grad = True, device = device)
y = torch.tensor([1.,2., 3.], requires_grad = True, device = device)
print("x:", x)
print("y:", y)
# first move the tensor from gpu to cpu
x = x.to('cpu') # or x = x.cpu()
# then detach the requires_grad
x = x.detach()
# and then convert to numpy
x = x.numpy()
print("x:",x)
print("type of x:", type(x))
y = y.cpu().detach().numpy()
print("y:", y)
print("type of y:", type(y))输出 1 - 如果 GPU 不可用
x: tensor([1., 2.], requires_grad=True) y: tensor([1., 2., 3.], requires_grad=True) x: [1. 2.] type of x: <class 'numpy.ndarray'> y: [1. 2. 3.] type of y: <class 'numpy.ndarray'>
输出 2 - 如果 GPU 可用
x: tensor([1., 2.], device='cuda:0', requires_grad=True) y: tensor([1., 2., 3.], device='cuda:0', requires_grad=True) x: [1. 2.] type of x: <class 'numpy.ndarray'> y: [1. 2. 3.] type of y: <class 'numpy.ndarray'>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP