如何將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'>

更新於:2023年9月12日

32K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.