Global reduction
Compute a single aggregate statistic from a tensor.
PyTorch · Function
Computes the mean of all tensor elements or reduces selected dimensions. It supports optional dtype conversion and dimension retention.
torch.mean computes the arithmetic mean of every element or reduces selected dimensions. The optional dtype casts the input before reduction, while keepdim preserves reduced dimensions as size 1.
torch.mean(*input*, ***, *dtype=None*) → Tensor
torch.mean(*input*, *dim*, *keepdim=False*, ***, *dtype=None*, *out=None*) → Tensor| Name | Type | Description |
|---|---|---|
input | Tensor | The input tensor, with floating-point or complex dtype. |
dtype | torch.dtype, optional | Optional desired data type; the input is cast to it before reduction. |
dim | int or tuple of ints, optional | Dimension or dimensions over which to reduce. |
keepdim | bool, optional | Whether to retain reduced dimensions as size 1. |
out | Tensor, optional | Optional output tensor. |
A Tensor containing the mean of all input elements or the means after reduction over the selected dimension(s).
import torch
x = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(torch.mean(x))
print(torch.mean(x, dim=0, keepdim=True))Computes the overall mean, then the column means while retaining the reduced dimension.
Compute a single aggregate statistic from a tensor.
Average features, batches, or spatial axes independently.
Maintain broadcast-compatible shapes after reducing dimensions.
With only input, torch.mean returns one scalar containing the mean of all elements. With dim, it reduces the specified dimension or dimensions instead.
Follow-up: What happens when dim is a list? It reduces across every dimension in that list.
keepdim=True leaves each reduced axis in the result with length one. With the default False, those axes are squeezed from the output shape.
Follow-up: Why use keepdim=True? It keeps shapes suitable for broadcasting against the unreduced tensor.
dtype specifies the desired output data type. When provided, the input is cast to that dtype before the mean is calculated.
Follow-up: What input types does the documented function accept? Floating-point and complex tensors.
torch.nanmeantorch.squeezetorch.Tensor.mean