qfeval_functions.functions.nanamax

nanamax(x, dim=None, keepdim=False)[source]

Compute the maximum of tensor elements along specified dimensions, ignoring NaN values.

This function calculates the maximum of all valid (non-NaN) elements in a tensor along the specified dimension(s). Unlike nanmax(), this function supports multiple dimensions but does not return indices. When no valid elements are found along a dimension, the result is NaN.

The NaN-aware maximum is computed as:

\[\text{nanamax}(X) = \max_{i \text{ valid}} X_i\]

where the maximum is over all valid (non-NaN) values.

Parameters:
  • x (Tensor) – The input tensor containing values.

  • dim (Union[None, int, Tuple[int, ...]]) – The dimension(s) along which to compute the maximum. If None (default), the maximum is computed over all dimensions.

  • keepdim (bool) – Whether the output tensor has dim retained or not. Default is False.

Returns:

The maximum values computed only over valid (non-NaN) values. When no valid values exist along a dimension, the result is NaN. The shape depends on the input dimensions, dim, and keepdim parameters.

Return type:

Tensor

Example

>>> # Simple maximum with NaN values
>>> x = torch.tensor([1.0, 2.0, nan, 4.0, 5.0])
>>> QF.nanamax(x)
tensor(5.)
>>> # All NaN returns NaN
>>> all_nan = torch.tensor([nan, nan, nan])
>>> QF.nanamax(all_nan)
tensor(nan)
>>> # 2D tensor with max along columns
>>> x = torch.tensor([[1.0, nan, 3.0],
...                   [4.0, 5.0, nan]])
>>> QF.nanamax(x, dim=0)
tensor([4., 5., 3.])
>>> # Max along rows
>>> QF.nanamax(x, dim=1)
tensor([3., 5.])
>>> # Multiple dimensions
>>> x = torch.tensor([[[1.0, nan], [3.0, 4.0]],
...                   [[nan, 6.0], [7.0, nan]]])
>>> QF.nanamax(x, dim=(1, 2))
tensor([4., 7.])
>>> # With keepdim
>>> x = torch.tensor([[1.0, nan, 3.0],
...                   [4.0, 5.0, nan]])
>>> QF.nanamax(x, dim=1, keepdim=True)
tensor([[3.],
        [5.]])
>>> # All NaN slice returns NaN
>>> x = torch.tensor([[1.0, 2.0],
...                   [nan, nan]])
>>> QF.nanamax(x, dim=1)
tensor([2., nan])
>>> # With negative infinity
>>> x = torch.tensor([[1.0, -inf, 3.0],
...                   [nan, 2.0, -inf]])
>>> QF.nanamax(x, dim=1)
tensor([3., 2.])

See also

nanmax(): NaN-aware maximum with indices (single dimension only). nanamin(): NaN-aware minimum over multiple dimensions. torch.amax: Standard maximum over multiple dimensions (NaN propagates).