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

วิธีคำนวณฮิสโตแกรมของ Tensor ใน PyTorch

ฮิสโตแกรมของ tensor คำนวณโดยใช้ torch.histc() มันคืนค่าฮิสโตแกรมที่แสดงเป็น tensor มันรับสี่พารามิเตอร์: input, bins, min และ max มันจัดเรียงองค์ประกอบเข้าไปใน bins ความกว้างเท่ากันระหว่าง min และ max มันละเลยองค์ประกอบที่น้อยกว่า min และมากกว่า max

ขั้นตอน

  • นำเข้าไลบรารีที่จำเป็น ในตัวอย่าง Python ทั้งหมดต่อไปนี้ ไลบรารี Python ที่จำเป็นคือ torch และ Matplotlib ตรวจสอบให้แน่ใจว่าคุณติดตั้งแล้ว

  • สร้าง tensor และพิมพ์มัน

  • คำนวณ torch.histc(input, bins=100, min=0, max=100) มันคืนค่า tensor ของค่าฮิสโตแกรม ตั้งค่า bins, min, และ max ให้เหมาะสมตามความต้องการ

  • พิมพ์ฮิสโตแกรมที่คำนวณได้ข้างต้น

  • แสดงฮิสโตแกรมเป็นแผนภูมิแท่ง

ตัวอย่างที่ 1

# โปรแกรม Python คำนวณฮิสโตแกรมของ tensor
# นำเข้าไลบรารีที่จำเป็น
import torch
import matplotlib.pyplot as plt

# สร้าง tensor
T = torch.Tensor([2, 3, 1, 2, 3, 4, 3, 2, 3, 4, 3, 4])
print("Original Tensor T:\n", T)

# คำนวณฮิสโตแกรมของ tensor ที่สร้างข้างต้น
hist = torch.histc(T, bins=5, min=0, max=4)
print("Histogram of T:\n", hist)

ผลลัพธ์

Original Tensor T:
tensor([2., 3., 1., 2., 3., 4., 3., 2., 3., 4., 3., 4.])
Histogram of T:
tensor([0., 1., 3., 5., 3.])

ตัวอย่างที่ 2

# โปรแกรม Python คำนวณฮิสโตแกรมของ tensor
# นำเข้าไลบรารีที่จำเป็น
import torch
import matplotlib.pyplot as plt

# สร้าง tensor
T = torch.Tensor([2, 3, 1, 2, 3, 4, 3, 2, 3, 4, 3, 4])
print("Original Tensor T:\n", T)

# คำนวณฮิสโตแกรมของ tensor ที่สร้างข้างต้น
hist = torch.histc(T, bins=5, min=0, max=4)

# แสดงฮิสโตแกรมที่คำนวณได้ข้างต้นเป็นแผนภูมิแท่ง
bins = 5
x = range(bins)
plt.bar(x, hist, align='center')
plt.xlabel('Bins')
plt.ylabel('Frequency')
plt.show()

ผลลัพธ์

Original Tensor T:
tensor([2., 3., 1., 2., 3., 4., 3., 2., 3., 4., 3., 4.])

วิธีคำนวณฮิสโตแกรมของ Tensor ใน PyTorch