Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเข้าถึงข้อมูลเมตาของทิลเซอร์ (Tensor Metadata) ใน PyTorch

ข้อมูลเมตาของทิลเซอร์ประกอบด้วย ขนาด (size) หรือรูปร่าง (shape) และ จำนวนองค์ประกอบทั้งหมด เราใช้ .size() เพื่อเข้าถึงขนาด และ .shape สำหรับรูปร่าง ทั้งสองให้ผลลัพธ์เหมือนกัน สำหรับจำนวนองค์ประกอบ ใช้ฟังก์ชัน torch.numel()

ขั้นตอนการทำงาน

  • นำเข้าไลบรารี torch

  • กำหนดทิลเซอร์ PyTorch

  • หาข้อมูลเมตา: ใช้ .size() และ .shape สำหรับขนาด/รูปร่าง ใช้ torch.numel() สำหรับจำนวนองค์ประกอบ

  • พิมพ์ทิลเซอร์และข้อมูลเมตาเพื่อความเข้าใจ

ตัวอย่างที่ 1: ทิลเซอร์ 2D ขนาด 4x3

import torch

# สร้างทิลเซอร์ขนาด 4x3
T = torch.Tensor([[1, 2, 3], [2, 1, 3], [2, 3, 5], [5, 6, 4]])
print("T:\n", T)

# หาข้อมูลเมตา
size_T = T.size()
print("size of tensor T:\n", size_T)

# วิธีอื่น ใช้ .shape
print("Shape of tensor:\n", T.shape)

# หาจำนวนองค์ประกอบ
num_T = torch.numel(T)
print("Number of elements in tensor T:\n", num_T)

ผลลัพธ์

T: tensor([[1., 2., 3.], [2., 1., 3.], [2., 3., 5.], [5., 6., 4.]])
size of tensor T: torch.Size([4, 3])
Shape of tensor: torch.Size([4, 3])
Number of elements in tensor T: 12

ตัวอย่างที่ 2: ทิลเซอร์ 3D ขนาด 4x3x2 (สุ่ม)

import torch

# สร้างทิลเซอร์ 3D จากตัวเลขสุ่ม
T = torch.randn(4, 3, 2)
print("T:\n", T)

# หาข้อมูลเมตา
size_T = T.size()
print("size of tensor T:\n", size_T)
print("Shape of tensor:\n", T.shape)

num_T = torch.numel(T)
print("Number of elements in tensor T:\n", num_T)

ผลลัพธ์

T: tensor([[[-1.1806, 0.5569], [2.2237, 0.9709], [0.4775, -0.2491]], [[-0.9703, 1.9916], [0.1998, -0.6501], [-0.7489, -1.3013]], [[1.3191, 2.0049], [-0.1195, 0.1860], [-0.6061, -1.2451]], [[-0.6044, 0.6153], [-2.2473, -0.1531], [0.5341, 1.3697]]])
size of tensor T: torch.Size([4, 3, 2])
Shape of tensor: torch.Size([4, 3, 2])
Number of elements in tensor T: 24