Skip to content

BUG: quantile should error when weights are all zeros #28595

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions doc/release/upcoming_changes/28589.improvement.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Improved error handling in `np.quantile`
----------------------------------------
`np.quantile` now raises errors if:

* All weights are zero
* At least one weight is `np.nan`
* At least one weight is `np.inf`
12 changes: 9 additions & 3 deletions numpy/lib/_function_base_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -4535,9 +4535,11 @@ def quantile(a,
if axis is not None:
axis = _nx.normalize_axis_tuple(axis, a.ndim, argname="axis")
weights = _weights_are_valid(weights=weights, a=a, axis=axis)
if np.any(weights < 0):
raise ValueError("Weights must be non-negative.")

if np.any(weights <= 0):
if np.any(weights < 0):
raise ValueError("Weights must be non-negative.")
elif np.all(weights == 0):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can't you just say else here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't just say else here, as the first if will be true if only one of the weights is 0, which is valid

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can move the == 0 to the sum to simplify this, though.

IMO the checks may be clearer as not all(weights >= 0) to reject NaNs right away, but doesn't matter much so long the == 0 case is handled below.

Also, why not use isfinite?

raise ValueError("At least one weight must be non-zero.")
return _quantile_unchecked(
a, q, axis, out, overwrite_input, method, keepdims, weights)

Expand Down Expand Up @@ -4892,6 +4894,10 @@ def _quantile(
# We use the weights to calculate the empirical cumulative
# distribution function cdf
cdf = weights.cumsum(axis=0, dtype=np.float64)
if np.any(np.isinf(cdf[-1])):
raise ValueError("Weights must be finite.")
elif np.any(np.isnan(cdf[-1])):
raise ValueError("At least one weight is nan.")
cdf /= cdf[-1, ...] # normalization to 1
# Search index i such that
# sum(weights[j], j=0..i-1) < quantile <= sum(weights[j], j=0..i)
Expand Down
25 changes: 25 additions & 0 deletions numpy/lib/tests/test_function_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4142,6 +4142,31 @@ def test_closest_observation(self):
assert_equal(4, np.quantile(arr[0:9], q, method=m))
assert_equal(5, np.quantile(arr, q, method=m))

@pytest.mark.parametrize(["err_msg", "weight"],
[("Weights must be finite.", [1, np.inf, 1, 1]),
("Weights must be non-negative.", [1, -np.inf, 1, 1]),
("Weights must be finite.", [1, np.inf, 1, np.inf]),
("At least one weight must be non-zero.", np.zeros(4))])
@pytest.mark.parametrize("dty", ["f8", "O"])
def test_inf_zeroes_err(self, err_msg, weight, dty):

m = "inverted_cdf"
q = 0.5
arr = [1, 2, 3, 4]
wgts = np.array(weight, dtype=dty)
with pytest.raises(ValueError, match=err_msg):
a = np.quantile(arr, q, weights=wgts, method=m)

@pytest.mark.parametrize("weight", [[1, np.nan, 1, 1], [1, np.nan, np.nan, 1]])
@pytest.mark.parametrize(["err", "dty"], [(ValueError, "f8"), ((RuntimeWarning, ValueError), "O")])
def test_nan_err(self, err, dty, weight):

m = "inverted_cdf"
q = 0.5
arr = [1, 2, 3, 4]
wgts = np.array(weight, dtype=dty)
with pytest.raises(err):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

might as well use match here too

a = np.quantile(arr, q, weights=wgts, method=m)

class TestLerp:
@hypothesis.given(t0=st.floats(allow_nan=False, allow_infinity=False,
Expand Down
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy