如何將帶有梯度的 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'>

更新於: 2022年1月6日

6K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.