评价此页

torch.mean#

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

注意

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

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

参数

input (Tensor) – 输入张量,浮点数或复数 dtype

关键字参数

dtype (torch.dtype, 可选) – 返回张量的期望数据类型。如果指定,输入张量将在执行操作前被转换为 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

返回 input 张量在给定维度 dim 上的每行平均值。如果 dim 是一个维度列表,则对所有这些维度进行归约。

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

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

  • dim (inttuple of ints, 可选) – 要归约的维度或维度。如果为 None,则归约所有维度。

  • keepdim (bool, 可选) – 输出张量是否保留 dim。默认为 False

关键字参数
  • dtype (torch.dtype, 可选) – 返回张量的期望数据类型。如果指定,输入张量将在执行操作前被转换为 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]])