PyTorch – Mean()

The PyTorch’s function mean() gives the input tensor’s mean value for all elements. A numpy array is analogous to a PyTorch tensor. The sole distinction is that a tensor uses GPUs to speed up computations involving numbers.

The torch.mean() method is responsible for calculating a tensor’s mean. It provides the input tensor’s mean value for each element. We can also compute the mean row- and column-wise with the right axis or dim. Similarly, torch.std() calculates a tensor’s standard deviation. It yields the tensor’s total elements’ standard deviation. The standard deviation can also be calculated row- or column-wise, just like the mean.

What are the steps necessary to user torch.mean() effectively?

  • Add the necessary library. Torch is the essential Python library used in the following examples. Make certain that it is already installed.
  • Create and output a PyTorch tensor.
  • Utilize torch.mean to calculate the mean (input, axis). The input, in this case, is the tensor whose mean needs to be calculated, and the axis (or dim) is the collection of dimensions.
  • Assign a new variable to the calculated mean.


PyTorch – Mean() Parameters

The mean() function in PyTorch has a single parameter. The latter is called the input tensor and is represented as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>input (Tensor)</pre>
</div>

Keyword Arguments

The preferred data type for the returned tensor is specified by torch.dtype (optional). The input tensor is cast to dtype before the operation is carried out if provided. As a result, data type overflows can be avoided. It is None by default.

The example beneath illustrates how to use the mean()

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>var_a = torch.randn(3, 5)
print(var_a)
torch.mean(var_a)
torch.mean(input, dim, keepdim=False, *, dtype=None, out=None) → Tensor</pre>
</div>

Provides the input tensor’s mean value for each row in the specified dimension dim. Reduce across each dimension in dim if it is a list.

The output tensor has the same size as the input, except for the dim dimension(s), where it is of size one if dim is True. Otherwise, dim is squeezed (see torch.squeeze()), resulting in 1 (or len(dim)) less dimensions in the output tensor (s).

Parameters

Here are the parameters you most likely need to know about this function.

  • input (Tensor) – refers to the sensor’s input.
  • dim (int or tuple of python:ints) – the dim refers to the reducible dimension or dimensions thereof.
  • keepdim (bool) – It represents a boolean value indicating whether the tensor’s output has been retained or not.

In the case where,

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>T.mean(dim=0)</pre>
</div>

It shall provide you with the average along the first dim.

The option to reduce along a single dimension alone is available for many other “reduction” operations in PyTorch (and Numpy). It should be noted (e.g., std, sum, etc.).

Keyword Arguments: What are they?

The preferred data type for the returned tensor is specified by torch.dtype (optional). The input tensor is cast to dtype before the operation is carried out if provided. As a result, data type overflows can be avoided. The latter’s default value is None.

The output tensor is called out (Tensor, optional). As a result, we have the following example to cement this concept.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>var_a = torch.randn(4, 4)
print(var_a)
torch.mean(var_a, 1)
torch.mean(var_a, 1, True)</pre>
</div>

Utilize a CPU

We must create a tensor with a cpu() function to execute an argmax() function on the CPU. It will operate on a computer with a CPU. This time, we can use the cpu() function when building a tensor. The syntax for utilizing a cpu() is as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>torch.tensor(data).cpu()</pre>
</div>

Example 1: cpu() function

In this example, we’ll use the cpu() function to generate a tensor with two dimensions with three rows and five columns, and then we’ll use the mean() function to analyze the rows and columns.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>#import torch module
import torch

#create a tensor with two dimensions (3 * 5)
#with random elements using randn() function
var_data = torch.randn(3,5).cpu()

 
#display
print(var_data)
print()

#get average along columns with mean()

print("Show the resultant mean across the given columns:")
print(torch.mean(var_data, dim=0))

 
print()
#get average along rows with mean()
print("Show the resultant mean across the given rows:")

print(torch.mean(var_data, dim=1))</pre>
</div>

The mean values are displayed across all columns and rows, as can be seen.

Example 2: Using the cpu() function

The cpu() function creates a Tensor with a five-by-five matrix and returns the average over the rows and columns.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>#import torch module
import torch

#create a tensor with two dimensions (5 * 5)
#with random elements using randn() function
var_data = torch.randn(5,5).cpu()

#display
print(var_data)
print()

#find out the resultant average along columns with a mean()
print("the consequential mean across columns:")
print(torch.mean(var_data, dim=0))

print()
#get the new average figure along rows with mean()
print("The new mean across rows:")
print(torch.mean(var_data, dim=1))</pre>
</div>

We can see that the average values for the rows and columns were given back.

Mean()

The mean value attained from the elements in the input tensor object is returned by the Mean() function in PyTorch.

Syntax:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>torch.mean(tensor,dim)</pre>
</div>

Where:

The input tensor is the tensor.

Dim means to decrease the dimension. Dim=0 designates a comparison that gets the average along a column. On the other hand, Dim=1 designates a comparison that gets the average along a row.

Example: Generating a tensor with two dimensions

In this example, we’ll generate a tensor with two dimensions, three rows, and five columns, and then we’ll use the mean() method to analyze the rows and columns.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>#import torch module

import torch

#create a tensor with two dimensions (3 * 5)

#with random elements using randn() function
data = torch.randn(3,5)

#display
print(var_data)
print()

#get average along columns with mean()

print("The subsequent mean across columns:")
print(torch.mean(var_data, dim=0))

print()
#get the new average value along rows with mean()
print("The new mean across all the rows:")
print(torch.mean(var_data, dim=1))
</pre>
</div>

The mean values are displayed across all columns and rows, as can be seen.

Example: Using a 5*5 matrix to create a tensor

The average over the rows and columns will be returned by creating a Tensor with a 5 * 5 matrix.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>#import torch module
import torch

#create a tensor with two dimensions (5 * 5)
#come up with random elements using randn() function
var_data = torch.randn(5,5)

#display
print(var_data)
print()

#get the resulting average value along columns with a mean()
print("What is the new mean value across columns:")
print(torch.mean(var_data, dim=0))

 

print()
#get the new average value along rows with mean()
print("What is the resulting mean across all the rows:")
print(torch.mean(var_data, dim=1))</pre>
</div>

We can see that the average values for the rows and columns were given back.

Omitting the Dim Parameter

If we omit the dim argument, the average of the entire value is returned.

Example: Create a 2D tensor with a 5*5 matrix and output the average value.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>#import torch module

import torch

#create a tensor with two dimensions (5 * 5)
#with random elements using randn() function

var_data = torch.randn(5,5)
#display

print(var_data)
print()

#find out the new average value with a mean()
print("The new resulting mean  is:")
print(torch.mean(var_data))
</pre>
</div>

Example: Make a 1D tensor with five values and then give back the mean

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>#import torch module
import torch
 
#creation of a new tensor with five numeric values
var_data = torch.tensor([12.6,22.7,32.6,42.4,52.0])

 
#display
print(var_data)
print()

#get the resulting average with a mean()
print("The new mean value is :")
print(torch.mean(var_data))</pre>
</div>

Example: Calculating 2D tensor’s mean

The following Python program demonstrates how to calculate a 2D tensor’s mean in both directions, i.e., row-wise and column-wise.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># import necessary library
import torch

# create a 3x4 2D tensor
new_tensor_t = torch.Tensor([[4,6,9,-4],
[9,31,-60,25],
[4,-4,-75,56]])
print("The new 2 Dimensional tensor is:\n", new_tensor_t)

# compute the mean 
val_mean = torch.mean(new_tensor_t)
print("The resulting mean is :", val_mean)

# Compute column-wise mean 
mean = torch.mean(new_tensor_t, axis = 0)
print("The resulting Column-wise mean is:\n", val_mean)

# Computing the subsequent row-wise mean 
val_mean = torch.mean(new_tensor_t, axis = 1)
print("The resulting Row-wise mean is:\n", val_mean)
</pre>
</div>

Example: Calculating the mean value for a 1D tensor

The mean of a 1D tensor can be determined using the Python method below.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># Python program for computing the resulting mean
# deviation of a 1D tensor
# import the library
import torch

# Create a tensor
new_tensor_t = torch.Tensor([4.453, 6.432, 2.754, -4.554])
print("The new Tensor is:", new_tensor_t)

# Compute the mean and standard deviation
val_mean = torch.mean(new_tensor_t)

# Print the computed mean 
print("The resulting mean value is:", val_mean)</pre>
</div>

How Does PyTorch Find Mean Across Image Channels?

In this section, we’ll look at how to use PyTorch to find the mean across all picture channels. We must calculate the average of an image for the Red, Green, and Blue channels. Using the torch.mean() method, we can determine the average value throughout the image channel.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>function torch.mean()</pre>
</div>

Since the torch.mean() method only accepts input as a tensor. We must first convert our image to a PyTorch tensor to determine the mean of all the elements in the input tensor. We utilize this PyTorch tensor as the input tensor after conversion. We will use the examples below to drive our point home to determine the average overall picture channels.

Example: Finding mean across entire image’s channels

In the example below, we first use PIL to read photos from the computer before using PyTorch to find the mean across all image channels.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># import required libraries
import torch
from PIL import Image
import torchvision.transforms as transforms

# Reading the input image
val_img = Image.open('code_img.png')

# create a transform
val_transform = transforms.ToTensor()

# conversion of the given image to PyTorch Tensor
val_img_tensor = transform(val_img)

# Computation of the image's mean across the channels RGB
r_val, g_val, b_val = torch.mean(val_img_tensor, dim=[1, 2])

# Display the resulting outcome
print("The follow-on Mean for the specified Red channel is: ", r_val)
print("The new mean for the provided Green channel is: ", g_val)
print("The resulting mean for the given Blue channel is: ", b_val)</pre>
</div>

Example: Use OpenCV to read & find mean on image channels

In the example below, we use OpenCV to read photos from the computer before using PyTorch to get the mean overall image channels.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre># start by importing the required libraries
import torch
import cv2
import torchvision.transforms as transforms

# Reading the image input by utilizing the OpenCV
val_img = cv2.imread('new_img.png')
val_img = cv2.cvtColor(val_img, cv2.COLOR_BGR2RGB)

# create a transform
val_transform = transforms.ToTensor()

# conversion of the specified image to PyTorch Tensor
val_img_tensor = transform(val_img)

# Computing the image mean across the given channels RGB
r_val, g_val, b_val = torch.mean(val_img_tensor, dim=[1, 2])

# Showing the resulting outcome 
print("\n\nThe follow-on mean for the specified red channel is: ", r_val)
print("The new mean for the provided green channel is: ", g_val)
print("The resulting mean value for the blue channel is: ", b_val)</pre>
</div>

MEAN-AVERAGE-PRECISION (MAP)

Predicts item detection and calculates the Mean-Average-Precision (mAP) and Mean-Average-Recall (mAR). The mAP and mAR values can optionally be computed per class.

Targets and predicted boxes must be in Pascal VOC format (xmin-top left, ymin-top left, xmax-bottom right, ymax-bottom right). For more details on the input format for this metric, refer to the update() method. Check out the torchmetrics examples to illustrate how to use this statistic.

This metric adheres to pycocotools’ mAP implementation, a common application of the mAP metric for object detection.

You must have installed torchvision version 0.8.0 or later to use this statistic (with corresponding version 1.7.0 of torch or newer). When iou type is segm, this metric requires pycocotools to be installed. Please install using pip install torchmetrics[detection] or pip install torchvision.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import torch
from torchmetrics.detection.mean_ap import MeanAveragePrecision
val_preds = [
   val_dict(
     new_boxes=torch.tensor([[298.0, 81.0, 646.0, 325.0]]),
     new_scores=torch.tensor([0.536]),
     new_labels=torch.tensor([0]),
   )
 ]
val_target = [
  val_dict(
    new_boxes=torch.tensor([[254.0, 81.0, 602.0, 325.0]]),
    new_labels=torch.tensor([0]),
  )
]
rs_metric = MeanAveragePrecision()
rs_metric.update(val_preds, val_target)
from pprint import pprint
print(rs_metric.compute())</pre>
</div>

What exceptions could be raised?

If torchvision does not exist as part of the installed applications or the version installed is less than 0.8.0, a module not found error will occur. If iou_type is equal to seqm and pycocotools is not installed, a ModuleNotFoundError will occur. Additionally, if class_metrics is not a boolean, ValueError will occur.

Creates the internal Module state that is shared by ScriptModule and nn.Module.

Calculate the mean average precision and mean average recall scores (mAP and mAR)

The @[IoU=self.iou_thresholds | area=all | max_dets=max_detection_thresholds] function is used to determine the map score.

For your attention, the dictionary keys for mAR may alter if the initialization parameters are altered. The absence of the default properties will result in an AttributeError, which is likewise reachable via fields.

Conclusion

In this PyTorch tutorial, we have demonstrated how to use mean() to return the average values from a tensor. Recall that PyTorch is an open-source framework offered together with the Python programming language. The data is kept in a multidimensional array called a tensor. As a result, we must import the torch module to use a tensor. The procedure used to produce a tensor is called tensor().

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *