Open In App

How to compute the histogram of a tensor in PyTorch?

Improve
Improve
Like Article
Like
Save
Share
Report

Before understanding how to compute a histogram of a tensor, we should have some basic knowledge. Tensors are simply mathematical objects that can be used to describe physical properties, just like scalars and vectors. And a histogram is a graphical representation that organizes a group of data points into user-specified ranges. 

Syntax: torch.histc(input,bins,min,max)

Parameters:

  • input – This is the tensor that we will be passing as an input,
  • bins – The towers or bars of a histogram are called bins. The height of each bin shows how many values from that data fall into that range.
  • min – This is the minimum value of the bars i.e bin
  • max – This is the maximum value of the bars i.e bin

Steps for computing histogram of a tensor

Step 1: Import the required library. In all the examples, the required Python libraries are  Matplotlib and torch.

If not installed, install them using ‘ pip install matplotlib ‘ and ‘ pip install torch ‘ .

The syntax for importing a library from the python module:

import torch
import matplotlib.pyplot as plt #here plt is a alias

Step 2: Create a tensor with random values and print it.

A Pytorch tensor is the same as a NumPy array it does not know anything about deep learning or computational graphs or gradients its just an n-dimensional array to be used for numeric computation. 

Syntax to create a tensor:

Python3




# torch.tensor(data) creates a 
# torch.Tensor object with the
# given data.
V_data = [1., 2., 3.]
V = torch.tensor(V_data)
print(V)
  
# Creates a tensor of matrix
M_data = [[1., 2., 3.], [4., 5., 6]]
M = torch.tensor(M_data)
print(M)
  
# Create a 3D tensor of size 2x2x2.
T_data = [[[1., 2.], [3., 4.]],
          [[5., 6.], [7., 8.]]]
T = torch.tensor(T_data)
print(T)


Output :

tensor([1., 2., 3.])
tensor([[1., 2., 3.],
        [4., 5., 6.]])
tensor([[[1., 2.],
         [3., 4.]],

        [[5., 6.],
         [7., 8.]]])

Step 3: Compute torch.histc(input, 5, min=0, max=4), set bins, min, and max to appropriate values according to your need.

Syntax :

torch.histc(input, bins=100, min=0, max=0, *, out=None) → Tensor

Computes the histogram of a tensor. The elements are sorted into equal-width bins between min and max. If min and max are both zero, the minimum and maximum values of the data are used. Elements lower than min and higher than max are ignored.

Parameters:

  • input (Tensor) – the input tensor.
  • bins (int) – number of histogram bins
  • min (int) – the lower end of the range (inclusive)
  • max (int) – upper end of the range (inclusive)

Keyword used: out (Tensor, optional) – the output tensor.

Returns: Histogram represented as a tensor

Step 4: Print the histogram that was created by the function torch.histc( ).

Use the simple print function to print the tensor of the histogram.

Python3




# Use Google Colab to run these programs
import torch
  
GFG = torch.Tensor([1, 7, 1, 4, 1, 4, 3, 4, 1, 7, 2, 4])
hist = torch.histc(GFG, bins=5, min=0, max=4, *, out=None)
  
# Printing the histogram of tensor
print("GeeksforGeeks")
print("GFG tensor", hist)


Output :

GeeksforGeeks
GFG tensor tensor([0., 4., 1., 1., 4.])

Step 5: Visualize the histogram as a bar diagram 

For visualizing the histogram we will be using the matplotlib library.

plt.bar(x/y, var_name, align=’center/left/right’, color = [‘anycolor’])

The block of code above is used to plot the histogram as a bar graph.

Parameters:

  • axis x/y: denotes that the bar graph is along the x-axis or y-axis
  • var_name: It is the variable name that was given to the tensor
  • align: center,left,right
  • color: any color

Python3




import torch
import matplotlib.pyplot as plt
  
GFG = torch.Tensor([1, 7, 1, 4, 1, 4, 3, 4, 1, 7, 2, 4])
hist = torch.histc(GFG, bins=5, min=0, max=4, out=None)
  
# Printing the histogram of tensor
print("GeeksforGeeks")
print("GFG tensor", hist)
bins = 5
x = range(bins)
plt.bar(x, hist, align='center', color=['forestgreen'])
plt.xlabel('Bins')
plt.ylabel('Frequency')
plt.show()


Output:

GeeksforGeeks

GFG tensor tensor([0., 4., 1., 1., 4.])

Let’s see a few more examples for better understanding.

Example 1:

Python3




# example 1
import torch
import matplotlib.pyplot as plt
  
# Create a tensor
T = torch.Tensor([1, 5, 1, 4, 2, 4, 3,
                  3, 1, 4, 2, 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)


Output

Original Tensor T:

 tensor([1., 5., 1., 4., 2., 4., 3., 3., 1., 4., 2., 4.])

Histogram of T:

 tensor([0., 3., 2., 2., 4.])

Example 2:

Python3




# example 2
import torch
import matplotlib.pyplot as plt
  
# Create a tensor
T = torch.Tensor([1, 5, 1, 4, 2, 4, 3,
                  3, 1, 4, 2, 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', color=['forestgreen'])
plt.xlabel('Bins')
plt.ylabel('Frequency')
plt.show()


Output

Original Tensor T:

 tensor([1., 5., 1., 4., 2., 4., 3., 3., 1., 4., 2., 4.])



Last Updated : 21 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads