fn

nanmedian

Tensor
nanmedian(x: Tensor, dim: int | None = ..., keepdim: bool = ...)
source

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 lucid.median.

Parameters

xTensor
Input tensor of any floating dtype.
dimint | None
Reduction axis. None (default) flattens x first.
keepdimbool
If True, retain the reduced axis as a singleton in the output shape. Ignored when dim is None. Defaults to False.

Returns

Tensor

Median value(s) over the non-NaN entries. Scalar when dim is None; otherwise the input shape with the reduction axis removed (or kept as size 1 if keepdim=True).

Notes

Algorithmic outline:

  1. Replace NaN entries with ++\infty so they sort to the high end and never become the chosen median.
  2. Sort along the reduction axis.
  3. Pick element at index (nnot-nan1)/2\lfloor (n_{\text{not-nan}} - 1) / 2 \rfloor — the lower-median convention for even counts, matching the reference framework's default behaviour.

If all entries along the reduction are NaN the result is NaN (no valid sample to take).

Examples

>>> import lucid
>>> import math
>>> x = lucid.tensor([1.0, math.nan, 3.0, 5.0])
>>> lucid.nanmedian(x)
Tensor(3.)