Skip to content

np.percentile returns different median from np.median when inf is present #12282

Open

Description

@astrofrog

When inf values are present in an array, under certain conditions np.percentile can return NaN as the median, whereas np.median can return a finite value.

Reproducing code example:

>>> import numpy as np
>>> np.percentile([np.inf, 5, 4], [10, 20, 30, 40, 50, 60, 70, 80, 90])
/Users/tom/miniconda3/envs/alldev/lib/python3.7/site-packages/numpy-1.16.0.dev0+45718fd-py3.7-macosx-10.7-x86_64.egg/numpy/lib/function_base.py:3947: RuntimeWarning: invalid value encountered in multiply
  x2 = take(ap, indices_above, axis=axis) * weights_above
array([4.2, 4.4, 4.6, 4.8, nan, inf, inf, inf, inf])
>>> np.median([np.inf, 5, 4])
5.0

In this case, np.median is able to correctly return 5.0 as the median value, whereas np.percentile returns NaN for the 50th percentile.

Numpy/Python version information:

>>> import sys, numpy; print(numpy.__version__, sys.version)
1.16.0.dev0+45718fd 3.7.1 (default, Oct 23 2018, 14:07:42) 
[Clang 4.0.1 (tags/RELEASE_401/final)]

Activity

  1. eric-wieser commented on Oct 28, 2018

    @eric-wieser
    Member

    I think this fails for the same reason that np.interp(0, [0, 1], [0, np.inf]) does - interpolation with one endpoint at infinity results in 0*inf being evaluated.

  2. eric-wieser commented on Oct 28, 2018

    @eric-wieser
    Member

    Interestingly, this hits on the same problem as a previous issue you filed, #8627 - writing a correct lerp is hard

  3. lumbric commented on Dec 27, 2019

    @lumbric
    Contributor

    np.quantile() is affected in the same way (no
    t too surprisingly, since np.percentile() is just a wrapper for np.quantile()).

    I have a draft patch (draft means, not all tests succeed, there are some more corner cases to be tackled in a final version), but I need some guidance and mentoring (it's my first numpy patch).

    Please let me know, if you think I'm on the right path!

    commit 5530a6c88c39c727f8cc312371b551cd40208ef7 (HEAD -> patch_for_12282_try2)
    Author: lumbric <[email protected]>
    Date:   Fri Dec 27 18:00:06 2019 +0100
    
        Fix handling of inf and -inf in quantile()
        
        Kind of fixes #12282, but some tests are still broken. Too much memory
        might be needed, not quite sure yet if more or less than before.
    
    diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py
    index 3ad630a7d..c6b679a6e 100644
    --- a/numpy/lib/function_base.py
    +++ b/numpy/lib/function_base.py
    @@ -3707,7 +3707,7 @@ def quantile(a, q, axis=None, out=None,
                  overwrite_input=False, interpolation='linear', keepdims=False):
         """
         Compute the q-th quantile of the data along the specified axis.
    -    
    +
         .. versionadded:: 1.15.0
     
         Parameters
    @@ -3929,21 +3929,23 @@ def _quantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False,
                 indices_above = indices_above[:-1]
                 n = np.isnan(ap[-1:, ...])
     
    -        x1 = take(ap, indices_below, axis=axis) * weights_below
    -        x2 = take(ap, indices_above, axis=axis) * weights_above
    +        x1 = take(ap, indices_below, axis=axis)
    +        x2 = take(ap, indices_above, axis=axis)
     
    -        # ensure axis with q-th is first
    -        x1 = np.moveaxis(x1, axis, 0)
    -        x2 = np.moveaxis(x2, axis, 0)
    +        if out is None:
    +            out = x1 * weights_below
    +        else:
    +            out[...] = x1 * weights_below
    +
    +        idcs_inf = x2 == np.inf
    +
    +        out += np.where(idcs_inf, 1., x2) * weights_above
    +        out[idcs_inf] += np.inf   # results in NaN or +inf
     
             if zerod:
    -            x1 = x1.squeeze(0)
    -            x2 = x2.squeeze(0)
    +            out = out.squeeze(0)
     
    -        if out is not None:
    -            r = add(x1, x2, out=out)
    -        else:
    -            r = add(x1, x2)
    +        r = out
     
         if np.any(n):
             if zerod:

    I also tried using np.interp(), but this supports only 1d arrays. Another try (skipped here for simplicity) uses nested np.where() calls to calculate x2 (the old meaning of x2, the meaning of x2 changed in the patch above), but I think this creates to many copies of the data in the memory. I tried to avoid the multiplication 0 * inf to get rid of the warning. Do you think filtering the warning would be a better idea? Might make the code simpler or even faster, I'm not entirely sure yet.

  4. Jimut123 commented on Dec 23, 2022

    @Jimut123

    Any update on this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions