快捷方式

torch.mean

torch.mean(input, *, dtype=None) Tensor

注意

如果 input 张量为空,torch.mean() 返回 nan。此行为与 NumPy 一致,并遵循空集的均值未定义的定义。

返回 input 张量中所有元素的均值。输入必须是浮点类型或复数类型。

参数

input (Tensor) – 输入张量,可以是浮点类型或复数类型

关键字参数

dtype (torch.dtype, optional) – 返回张量所需的 数据类型。如果指定,操作执行前会将输入张量转换为 dtype。这对于防止数据类型溢出很有用。默认值:None。

示例

>>> 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, *, dtype=None, out=None) Tensor

返回给定维度 diminput 张量每行的均值。如果 dim 是维度列表,则对所有维度进行归约。

如果 keepdimTrue,则输出张量的大小与 input 相同,只是在 dim 指定的维度上大小为 1。否则,会压缩 dim 指定的维度(参见 torch.squeeze()),导致输出张量维度减少 1 个(或 len(dim) 个)。

参数
  • input (Tensor) – 输入张量。

  • dim (inttuple of ints) – 待归约的维度或维度列表。

  • keepdim (bool) – 输出张量是否保留 dim 指定的维度。

关键字参数
  • dtype (torch.dtype, optional) – 返回张量所需的 数据类型。如果指定,操作执行前会将输入张量转换为 dtype。这对于防止数据类型溢出很有用。默认值:None。

  • out (Tensor, optional) – 输出张量。

另请参阅

torch.nanmean() 计算非 NaN 元素的均值。

示例

>>> 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]])

文档

访问 PyTorch 全面的开发者文档

查看文档

教程

获取面向初学者和高级开发者的深度教程

查看教程

资源

查找开发资源并获得问题解答

查看资源