如何計算 PyTorch 中張量的直方圖?
使用 torch.histc() 計算張量的直方圖。它返回一個表示為張量的直方圖。它使用四個引數:input、bins、min 和 max。它將元素排序到 min 和 max 之間的相等寬度箱中。它忽略小於 min 和大於 max 的元素。
步驟
匯入所需的庫。在所有以下 Python 示例中,所需的 Python 庫都是 torch 和 Matplotlib。確保已經安裝了它們。
建立一個張量並列印它。
計算 torch.histc(input, bins=100, min=0, max=100)。它將返回一個直方圖值張量。根據需要將 bins、min 和 max 設定為適當的值。
列印上面計算的直方圖。
將直方圖作為條形圖進行視覺化。
示例 1
# Python program to calculate histogram of a tensor
# import necessary libraries
import torch
import matplotlib.pyplot as plt
# Create a tensor
T = torch.Tensor([2,3,1,2,3,4,3,2,3,4,3,4])
print("Original Tensor T:\n",T)
# Calculate the histogram of the above created 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 program to calculate histogram of a tensor
# import necessary libraries
import torch
import matplotlib.pyplot as plt
# Create a tensor
T = torch.Tensor([2,3,1,2,3,4,3,2,3,4,3,4])
print("Original Tensor T:\n",T)
# Calculate the histogram of the above created tensor
hist = torch.histc(T, bins = 5, min = 0, max = 4)
# Visualize above calculated histogram as bar diagram
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.])

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP