.mean()
Anonymous contributor
Published Nov 28, 2024
Contribute to Docs
The .mean() method in PyTorch computes the arithmetic mean (average) of tensor elements. It can calculate the mean for all elements in the tensor or along a specified dimension. This method is widely used in data preprocessing and analysis for summarizing data.
Syntax
tensor.mean(dim=None, keepdim=False)
dim
(optional): The dimension along which the mean is computed. If not specified, the mean of all elements is calculated.keepdim
(optional): IfTrue
, retains the reduced dimension with size1
. Defaults toFalse
.
The function returns a tensor containing the mean value(s).
Example
This example demonstrates calculating the mean of all elements in a tensor and along a specific dimension:
import torch# Create a tensortensor = torch.tensor([[1.0, 2.0], [3.0, 4.0]])# Calculate the mean of all elementsmean_all = tensor.mean()# Calculate the mean along dimension 0 (columns)mean_dim0 = tensor.mean(dim=0)print("Mean of all elements:", mean_all)print("Mean along dimension 0:", mean_dim0)
This example results in the following output:
Mean of all elements: tensor(2.5000)Mean along dimension 0: tensor([2.0000, 3.0000])
In this example:
mean_all
computes the mean of all elements in the tensor.mean_dim0
computes the mean along each column (dimension 0), reducing the rows. This makes.mean()
a versatile tool for data analysis.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly90 hours - Free course
Intro to PyTorch and Neural Networks
Learn how to use PyTorch to build, train, and test artificial neural networks in this course.Intermediate3 hours