fn

nanmean

Tensor
nanmean(x: Tensor, dim: int | Sequence[int] | None = ..., keepdim: bool = ...)
source

Mean of the tensor, ignoring NaN entries.

A NaN-safe variant of lucid.mean. Both the numerator (sum) and the denominator (element count) are computed only over the non-NaN entries.

Parameters

xTensor
Input tensor (any floating-point dtype).
dimint | Sequence[int] | None
Axis or axes along which to take the mean. None (default) reduces over the entire tensor.
keepdimbool
If True, retains the reduced dimensions with size 1. Defaults to False.

Returns

Tensor

Reduced tensor.

Notes

With S\mathcal{S} the set of indices being reduced and 1i=11xi is NaN\mathbb{1}_i = 1 - \mathbb{1}_{x_i \text{ is NaN}},

nanmean(x)=iS1ixiiS1i.\text{nanmean}(x) = \frac{\sum_{i \in \mathcal{S}} \mathbb{1}_i \cdot x_i} {\sum_{i \in \mathcal{S}} \mathbb{1}_i}.

A slice that is entirely NaN produces 0 / 0 = NaN; this is the standard convention. The gradient at NaN positions is zero.

Examples

>>> import lucid
>>> import math
>>> x = lucid.tensor([1.0, math.nan, 3.0])
>>> lucid.nanmean(x)
Tensor(2.)