PyTorch torch.nanmedian Function


Pytorch torch 参考手册PyTorch torch Reference Manual

torch.nanmedianIt is a function in PyTorch used to return the median of non-NaN values in a tensor. Unlike median, it ignores all NaN values.

Function Definition

torch.nanmedian(input, dim, keepdim=False)

Usage Example

Example

import torch

x = torch.tensor([1.0, float('nan'), 3.0, 2.0, 5.0])

# Return the median of non-NaN values
print("Non-NaN median:", torch.nanmedian(x))

# Non-NaN median along dim=0
y = torch.tensor([[1.0, float('nan'), 2.0], [4.0, 1.0, 3.0]])
print("dim=0 non-NaN median:", torch.nanmedian(y, dim=0))

The output result is:

非NaN中位数: tensor(2.)
dim=0 非NaN中位数: torch.return_types.nanmedian(values=tensor([1., 1., 2.]), indices=tensor([0, 1, 0]))

Pytorch torch 参考手册PyTorch torch Reference Manual

Other Extensions