PyTorch tensor เป็น homogeneous หมายถึงองค์ประกอบทั้งหมดของ tensor มีชนิดข้อมูลเดียวกัน เราสามารถเข้าถึงชนิดข้อมูลของ tensor ได้โดยใช้แอตทริบิวต์ ".dtype" ของ tensor มันคืนค่าชนิดข้อมูลของ tensor
ขั้นตอน
นำเข้าไลบรารีที่จำเป็น ในตัวอย่าง Python ทั้งหมดต่อไปนี้ ไลบรารี Python ที่จำเป็นคือ torch ตรวจสอบให้แน่ใจว่าคุณติดตั้งแล้ว
สร้าง tensor และพิมพ์มัน
คำนวณ T.dtype ที่นี่ T คือ tensor ที่เราต้องการรับชนิดข้อมูล
พิมพ์ชนิดข้อมูลของ tensor
ตัวอย่างที่ 1
โปรแกรม Python ต่อไปนี้แสดงวิธีรับชนิดข้อมูลของ tensor
# นำเข้าไลบรารี
import torch
# สร้าง tensor ของตัวเลขสุ่มขนาด 3x4
T = torch.randn(3, 4)
print("Original Tensor T:\n", T)
# รับชนิดข้อมูลของ tensor ข้างต้น
data_type = T.dtype
# พิมพ์ชนิดข้อมูลของ tensor
print("Data type of tensor T:\n", data_type)
ผลลัพธ์
Original Tensor T:
tensor([[ 2.1768, -0.1328, 0.8155, -0.7967],
[ 0.1194, 1.0465, 0.0779, 0.9103],
[-0.1809, 1.8085, 0.8393, -0.2463]])
Data type of tensor T:
torch.float32
ตัวอย่างที่ 2
# โปรแกรม Python รับชนิดข้อมูลของ tensor
# นำเข้าไลบรารี
import torch
# สร้าง tensor ของตัวเลขสุ่มขนาด 3x4
T = torch.Tensor([1, 2, 3, 4])
print("Original Tensor T:\n", T)
# รับชนิดข้อมูลของ tensor ข้างต้น
data_type = T.dtype
# พิมพ์ชนิดข้อมูลของ tensor
print("Data type of tensor T:\n", data_type)
ผลลัพธ์
Original Tensor T: tensor([1., 2., 3., 4.]) Data type of tensor T: torch.float32