ทิลเซอร์ PyTorch คล้ายกับ numpy.ndarray ความแตกต่างคือทิลเซอร์ใช้ GPU เพื่อเร่งการคำนวณตัวเลข เราแปลง numpy.ndarray เป็นทิลเซอร์ด้วย torch.from_numpy() และแปลงทิลเซอร์เป็น numpy.ndarray ด้วยเมธอด .numpy()
ขั้นตอนการทำงาน
นำเข้าไลบรารี torch และ numpy
สร้าง numpy.ndarray หรือทิลเซอร์ PyTorch
แปลง numpy.ndarray เป็นทิลเซอร์ด้วย torch.from_numpy() หรือแปลงทิลเซอร์เป็น numpy.ndarray ด้วย .numpy()
พิมพ์ทิลเซอร์หรือ numpy.ndarray ที่แปลงแล้ว
ตัวอย่างที่ 1: แปลง NumPy ndarray เป็น PyTorch Tensor
import torch
import numpy as np
# สร้าง numpy.ndarray
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))
# แปลงเป็นทิลเซอร์
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:t: tensor([[1, 2, 3], [2, 1, 3], [2, 3, 5], [5, 6, 4]], dtype=torch.int32) Type after conversion:
ตัวอย่างที่ 2: แปลง PyTorch Tensor เป็น NumPy ndarray
import torch
import numpy
# สร้างทิลเซอร์
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))
# แปลงเป็น 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:a: [[1. 2. 3.] [2. 1. 3.] [2. 3. 5.] [5. 6. 4.]] Type after conversion:
หมายเหตุ: ทิลเซอร์และ ndarray ที่แปลงกันจะ แบ่งปันหน่วยความจำเดียวกัน การเปลี่ยนแปลงค่าที่หนึ่งจะส่งผลต่ออีกตัวหนึ่งด้วย