nanmedian(input: Tensor, dim: _int | None = ..., keepdim: _bool = ...)Median of a tensor, ignoring NaN entries.
Computes the median over the requested axis (or the entire tensor
when dim is None), treating NaN entries as missing data
rather than propagating them. This is the NaN-safe counterpart of
median.
Parameters
inputTensordimint | NoneNone (default) flattens input first.keepdimboolTrue, retain the reduced axis as a singleton in the
output shape. Ignored when dim is None. Defaults to
False.Returns
Raises
NotImplementedErrorbool or complex input.IndexErrordim is out of range, or the reduced axis has length 0.Notes
Every slice keeps its own count of non-NaN entries. NaN sorts last, so the median is the entry at sorted position — the lower median for an even count, matching the reference framework. A slice that is all NaN has no number to take and answers NaN, at the position of its first entry. Integer inputs hold no NaN and take the plain lower median.
The gradient of a dim reduction flows to the entry indices
names. The whole-tensor median shares its gradient evenly between
every entry equal to it (every NaN, when the answer is NaN), as the
reference does.
Examples
>>> import lucid
>>> import math
>>> x = lucid.tensor([1.0, math.nan, 3.0, 5.0])
>>> lucid.nanmedian(x)
tensor(3.)
>>> values, indices = lucid.nanmedian(
... lucid.tensor([[1.0, math.nan, math.nan], [1.0, 2.0, 3.0]]), 1
... )
>>> values
tensor([1., 2.])
>>> indices
tensor([0, 1], dtype=lucid.int64)