torch.nanmean¶
- torch.nanmean(input, dim=None, keepdim=False, *, dtype=None, out=None) Tensor ¶
计算指定维度上所有非 NaN 元素的均值。输入必须是浮点或复数类型。
当
input
张量中没有 NaN 值时,此函数与torch.mean()
完全相同。当存在 NaN 时,torch.mean()
会将 NaN 传播到输出,而torch.nanmean()
会忽略 NaN 值(torch.nanmean(a) 等价于 torch.mean(a[~a.isnan()]))。如果
keepdim
为True
,则输出张量的大小与input
相同,但dim
指定的维度大小为 1。否则,dim
会被压缩(详见torch.squeeze()
),导致输出张量的维度比输入少 1(或len(dim)
)个。- 参数
input (Tensor) – 输入张量,浮点或复数类型
dim (int 或 int 的 tuple,可选) – 要归约的维度或维度。如果为
None
,则归约所有维度。keepdim (bool) – 输出张量是否保留
dim
指定的维度。
- 关键字参数
dtype (
torch.dtype
, 可选) – 返回张量所需的数据类型。如果指定,输入张量在执行操作之前会转换为dtype
类型。这有助于防止数据类型溢出。默认值:None。out (Tensor, 可选) – 输出张量。
另请参阅
torch.mean()
计算平均值,并传播 NaN。示例
>>> x = torch.tensor([[torch.nan, 1, 2], [1, 2, 3]]) >>> x.mean() tensor(nan) >>> x.nanmean() tensor(1.8000) >>> x.mean(dim=0) tensor([ nan, 1.5000, 2.5000]) >>> x.nanmean(dim=0) tensor([1.0000, 1.5000, 2.5000]) # If all elements in the reduced dimensions are NaN then the result is NaN >>> torch.tensor([torch.nan]).nanmean() tensor(nan)