How to Average a Tensor Along a Dimension in PyTorch with mean()
Averages are everywhere in machine learning: the average loss of a batch, the average of a sentence's token vectors, the average score per row. mean() computes them on a PyTorch tensor, for all its values or along the one dimension you choose. This guide averages a small table of numbers in PyTorch 2.15.0.
Syntax
tensor.mean(dim=None, keepdim=False)
| Part | What it means |
|---|---|
dim | Optional. The dimension to average along. Left out, every value is averaged into one number. For a table, dim=0 averages down each column and dim=1 along each row |
keepdim | Optional. True keeps the averaged dimension, with a length of 1, so the result keeps the table's number of dimensions |
PyTorch's reference says the version with dim "Returns the mean value of each row of the input tensor in the given dimension dim", and that the input "must be floating point or complex": a tensor of decimal numbers. The dimension you give is the one that disappears from the result.
The Example
A table of six decimal numbers in two rows of three. The script prints the average of everything, of each column and of each row, then the row averages again with keepdim=True.
Prerequisites
- A uv project with PyTorch and NumPy.
uv add torch numpyadds both; without NumPy, PyTorch 2.15.0 prints a warning each time it starts. This guide uses PyTorch 2.15.0 and NumPy 2.5.5 on Python 3.15.2, with uv 0.13.10, on an Apple M1 Pro.
Step 1: Write the Script
import torch
scores = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(scores.mean())
print(scores.mean(dim=0))
print(scores.mean(dim=1))
print(scores.mean(dim=1, keepdim=True))

The numbers are written with .0, so PyTorch stores them as decimal numbers (float32), which mean() needs.
Step 2: Run It
uv run python mean.py
tensor(3.5000)
tensor([2.5000, 3.5000, 4.5000])
tensor([2., 5.])
tensor([[2.],
[5.]])
![The terminal after uv run python mean.py: tensor(3.5000), tensor([2.5000, 3.5000, 4.5000]), tensor([2., 5.]) and a two-row column tensor([[2.], [5.]]).](https://strdewiridedevblogsprod.blob.core.windows.net/images/blog/ai/pytorch/2026/pytorch-mean-02-output.webp)
scores.mean()averaged all six values: 21 / 6 =3.5, a tensor with no dimensions left.scores.mean(dim=0)averaged down each column: (1 + 4) / 2 =2.5, then3.5and4.5.scores.mean(dim=1)averaged along each row: (1 + 2 + 3) / 3 =2and (4 + 5 + 6) / 3 =5.- With
keepdim=True, the same row averages came back as a column of two rows, shape[2, 1]instead of[2].
The command works unchanged in PowerShell.
Averaging a Tensor with More Dimensions
The rule stays the same: the dimension you name is averaged away. A batch of sentences, each a list of token vectors, has the shape [sentences, tokens, numbers per token]. mean(dim=1) averages over the tokens and leaves one vector per sentence, [sentences, numbers per token]. That's how a sentence embedding is made from token vectors, as How to Turn a Sentence into an Embedding with a Hugging Face Feature-Extraction Pipeline shows.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Averaging a tensor of whole numbers, such as torch.tensor([[1, 2, 3], [4, 5, 6]]) | NotImplementedError: mean(): could not infer output dtype. Input dtype must be either a floating point or complex dtype. Got: Long: see the fix | Convert first with .float(), or pass dtype=torch.float32 |
Mixing up dim=0 and dim=1 | dim=0 gives one average per column, not per row | Name the dimension that should disappear: the rows are dim=0 |
FAQ
How do I get the average as a Python number?
With item(): scores.mean().item() printed the plain 3.5. How to Get a Python Number from a PyTorch Tensor with item() shows it.
Can I average over two dimensions at once?
Yes. Pass a tuple: scores.mean(dim=(0, 1)) averaged over both and printed tensor(3.5000), the same as scores.mean() for a table.
Conclusion
On a table of two rows of three, scores.mean() gave 3.5, scores.mean(dim=0) the column averages 2.5, 3.5, 4.5, scores.mean(dim=1) the row averages 2, 5, and keepdim=True kept those as a column.
Additional Resources
- torch.mean — PyTorch's reference, with
dim,keepdimanddtype. - Tensor.mean — the method version this guide uses.
