เทนเซอร์ PyTorch เป็นเหมือน numpy.ndarray . ความแตกต่างระหว่างสองสิ่งนี้คือเทนเซอร์ใช้ GPU เพื่อเร่งการคำนวณตัวเลข เราแปลง numpy.ndarray กับเทนเซอร์ PyTorch โดยใช้ฟังก์ชัน torch.from_numpy() . และเทนเซอร์จะถูกแปลงเป็น numpy.ndarray โดยใช้ .numpy() วิธีการ
ขั้นตอน
-
นำเข้าไลบรารีที่จำเป็น ที่นี่ ห้องสมุดที่จำเป็นคือไฟและ จำนวน .
-
สร้าง numpy.ndarray หรือเทนเซอร์ PyTorch
-
แปลง numpy.ndarray ไปยังเมตริกซ์ PyTorch โดยใช้ torch.from_numpy() ทำงานหรือแปลงเทนเซอร์ PyTorch เป็น numpy.ndarray โดยใช้ .numpy() วิธีการ
-
สุดท้าย พิมพ์เทนเซอร์ที่แปลงแล้วหรือ 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'>