How to compute the histogram of a tensor in PyTorch?

The histogram of a tensor is computed using torch.histc(). It returns a histogram represented as a tensor. It takes four parameters: input, bins, min and max. It sorts the elements into equal width bins between min and max. It ignores the elements smaller than the min and greater than the max.

Syntax

torch.histc(input, bins=100, min=0, max=0)

Parameters

  • input ? Input tensor
  • bins ? Number of histogram bins (default: 100)
  • min ? Lower range of bins (default: 0)
  • max ? Upper range of bins (default: 0)

Basic Example

Let's create a simple tensor and compute its histogram ?

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:")
print(T)

# Calculate the histogram of the above created tensor
hist = torch.histc(T, bins=5, min=0, max=4)
print("\nHistogram of T:")
print(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.])

The histogram shows frequency counts: 0 elements in bin 0 (0-0.8), 1 element in bin 1 (0.8-1.6), 3 elements in bin 2 (1.6-2.4), 5 elements in bin 3 (2.4-3.2), and 3 elements in bin 4 (3.2-4.0).

Visualizing the Histogram

We can visualize the histogram using matplotlib to create a bar chart ?

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:")
print(T)

# Calculate the histogram of the above created tensor
hist = torch.histc(T, bins=5, min=0, max=4)

# Visualize histogram as bar diagram
bins = 5
x = range(bins)
plt.figure(figsize=(8, 5))
plt.bar(x, hist, align='center')
plt.xlabel('Bins')
plt.ylabel('Frequency')
plt.title('Tensor Histogram')
plt.show()
Original Tensor T:
tensor([2., 3., 1., 2., 3., 4., 3., 2., 3., 4., 3., 4.])
0 1 2 3 4 0 1 2 3 4 5 Bins Frequency

Working with Random Data

Here's an example using normally distributed random data ?

import torch

# Create random tensor with normal distribution
torch.manual_seed(42)  # For reproducible results
data = torch.randn(1000) * 2 + 5  # Mean=5, Std=2

# Compute histogram with 10 bins
hist = torch.histc(data, bins=10, min=0, max=10)
print("Random data histogram:")
print(hist)
print(f"\nTotal elements: {hist.sum()}")
Random data histogram:
tensor([  6.,  19.,  71., 147., 207., 241., 188., 102.,  18.,   1.])

Total elements: 1000

Key Points

  • Elements outside the [min, max] range are ignored
  • Bins are of equal width: (max - min) / bins
  • Returns a 1D tensor with histogram counts
  • Useful for data analysis and visualization

Conclusion

Use torch.histc() to compute tensor histograms with customizable bins and ranges. It's essential for data analysis and understanding value distributions in PyTorch tensors.

Updated on: 2026-03-26T18:43:55+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements