mean

Documentation

treetensor.torch.mean(input, *args, reduce=None, **kwargs)[source]

Returns the mean value of all elements in the input tensor.

Examples:

>>> import torch
>>> import treetensor.torch as ttorch
>>> t = torch.randn((2, 3)) * 30
>>> t
tensor([[ 26.6598,  27.8008, -59.4753],
        [-79.1833,   3.3349,  20.1665]])
>>> ttorch.mean(t)
tensor(-10.1161)

>>> tt = ttorch.randn({
...     'a': (2, 3),
...     'b': {'x': (3, 4)},
... }) * 30
>>> tt
<Tensor 0x7f2f5b9f6cf8>
├── a --> tensor([[ 25.2702,  37.4206, -37.1401],
│                 [ -7.7245, -91.3234, -27.9402]])
└── b --> <Tensor 0x7f2f5b9f6c18>
    └── x --> tensor([[  3.2028, -14.0720,  18.1739,   8.5944],
                      [ 41.7761,  36.9908, -20.5495,   5.6480],
                      [ -9.3438,  -0.7416,  47.2113,   6.9325]])
>>> ttorch.mean(tt)
tensor(1.2436)
>>> ttorch.mean(tt, reduce=False)
<Tensor 0x7f1321caf080>
├── a --> tensor(-16.9062)
└── b --> <Tensor 0x7f1321caf048>
    └── x --> tensor(10.3186)
>>> ttorch.mean(tt, dim=1)
<Tensor 0x7f63dbbc9828>
├── a --> tensor([  8.5169, -42.3294])
└── b --> <Tensor 0x7f63dbbc9780>
    └── x --> tensor([ 3.9748, 15.9663, 11.0146])

Torch Version Related

This documentation is based on torch.mean in torch v2.0.1+cu117. Its arguments’ arrangements depend on the version of pytorch you installed.

If some arguments listed here are not working properly, please check your pytorch’s version with the following command and find its documentation.

1
python -c 'import torch;print(torch.__version__)'

The arguments and keyword arguments supported in torch v2.0.1+cu117 is listed below.

Description From Torch v2.0.1+cu117

torch.mean(input)Tensor

Returns the mean value of all elements in the input tensor.

Args:

input (Tensor): the input tensor.

Example:

>>> a = torch.randn(1, 3)
>>> a
tensor([[ 0.2294, -0.5481,  1.3288]])
>>> torch.mean(a)
tensor(0.3367)
torch.mean(input, dim, keepdim=False, *, out=None)Tensor

Returns the mean value of each row of the input tensor in the given dimension dim. If dim is a list of dimensions, reduce over all of them.

If keepdim is True, the output tensor is of the same size as input except in the dimension(s) dim where it is of size 1. Otherwise, dim is squeezed (see torch.squeeze()), resulting in the output tensor having 1 (or len(dim)) fewer dimension(s).

Args:

input (Tensor): the input tensor. dim (int or tuple of ints): the dimension or dimensions to reduce. keepdim (bool): whether the output tensor has dim retained or not.

Keyword args:

out (Tensor, optional): the output tensor.

Example:

>>> a = torch.randn(4, 4)
>>> a
tensor([[-0.3841,  0.6320,  0.4254, -0.7384],
        [-0.9644,  1.0131, -0.6549, -1.4279],
        [-0.2951, -1.3350, -0.7694,  0.5600],
        [ 1.0842, -0.9580,  0.3623,  0.2343]])
>>> torch.mean(a, 1)
tensor([-0.0163, -0.5085, -0.4599,  0.1807])
>>> torch.mean(a, 1, True)
tensor([[-0.0163],
        [-0.5085],
        [-0.4599],
        [ 0.1807]])