-
Notifications
You must be signed in to change notification settings - Fork 12
ENH: add quantile
#341
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
Draft
betatim
wants to merge
22
commits into
data-apis:main
Choose a base branch
from
betatim:add-quantile
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+322
−2
Draft
ENH: add quantile
#341
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
f7cac01
Add delegation for `quantile`
betatim 9577f11
Formatting
betatim e8a7d30
Fix scipy version
betatim 10b9ec8
Formatting
betatim 98570f6
Remove superfluous comments
betatim 470f8b4
Remove unsupported method
betatim a2eefa0
More noqa
betatim 37acd5b
yet more noqa
betatim c3501e8
Move quantile implementation to new file
betatim 7a7934c
Remove duplicated code
betatim 3095889
docstring keepdims
lucascolley bd55318
lint
lucascolley 1ef7d5e
improve style
lucascolley 440106f
fix list
lucascolley 0f28550
Merge branch 'main' into add-quantile
lucascolley 3ef6727
Raise exception for invalid q values
betatim 13a5507
Merge remote-tracking branch 'origin/add-quantile' into add-quantile
betatim 007a61f
Tweak
betatim 1ccdac4
noqa
betatim ebcec0e
More lint pleasure
betatim 5c974a4
Delegate to dask directly
betatim 477c916
Fix
betatim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,6 +19,7 @@ | |
nunique | ||
one_hot | ||
pad | ||
quantile | ||
setdiff1d | ||
sinc | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
"""Quantile implementation.""" | ||
|
||
from types import ModuleType | ||
from typing import cast | ||
|
||
from ._at import at | ||
from ._utils import _compat | ||
from ._utils._compat import array_namespace | ||
from ._utils._typing import Array | ||
|
||
|
||
def quantile( | ||
x: Array, | ||
q: Array | float, | ||
/, | ||
*, | ||
axis: int | None = None, | ||
keepdims: bool | None = None, | ||
method: str = "linear", | ||
xp: ModuleType | None = None, | ||
) -> Array: # numpydoc ignore=PR01,RT01 | ||
"""See docstring in `array_api_extra._delegation.py`.""" | ||
if xp is None: | ||
xp = array_namespace(x, q) | ||
|
||
q_is_scalar = isinstance(q, int | float) | ||
if q_is_scalar: | ||
q = xp.asarray(q, dtype=xp.float64, device=_compat.device(x)) | ||
q_arr = cast(Array, q) | ||
|
||
if not xp.isdtype(x.dtype, ("integral", "real floating")): | ||
msg = "`x` must have real dtype." | ||
raise ValueError(msg) | ||
if not xp.isdtype(q_arr.dtype, "real floating"): | ||
msg = "`q` must have real floating dtype." | ||
raise ValueError(msg) | ||
|
||
# Promote to common dtype | ||
x = xp.astype(x, xp.float64) | ||
q_arr = xp.asarray(q_arr, dtype=xp.float64, device=_compat.device(x)) | ||
|
||
dtype = x.dtype | ||
axis_none = axis is None | ||
ndim = max(x.ndim, q_arr.ndim) | ||
|
||
if axis_none: | ||
x = xp.reshape(x, (-1,)) | ||
q_arr = xp.reshape(q_arr, (-1,)) | ||
axis = 0 | ||
elif not isinstance(axis, int): # pyright: ignore[reportUnnecessaryIsInstance] | ||
msg = "`axis` must be an integer or None." | ||
raise ValueError(msg) | ||
elif axis >= ndim or axis < -ndim: | ||
msg = "`axis` is not compatible with the shapes of the inputs." | ||
raise ValueError(msg) | ||
else: | ||
axis = int(axis) | ||
|
||
if keepdims not in {None, True, False}: | ||
msg = "If specified, `keepdims` must be True or False." | ||
raise ValueError(msg) | ||
|
||
if x.shape[axis] == 0: | ||
shape = list(x.shape) | ||
shape[axis] = 1 | ||
x = xp.full(shape, xp.nan, dtype=dtype, device=_compat.device(x)) | ||
|
||
y = xp.sort(x, axis=axis) | ||
|
||
# Move axis to the end for easier processing | ||
y = xp.moveaxis(y, axis, -1) | ||
if not (q_is_scalar or q_arr.ndim == 0): | ||
q_arr = xp.moveaxis(q_arr, axis, -1) | ||
|
||
n = xp.asarray(y.shape[-1], dtype=dtype, device=_compat.device(y)) | ||
|
||
# Validate that q values are in the range [0, 1] | ||
if xp.any((q_arr < 0) | (q_arr > 1)): | ||
msg = "`q` must contain values between 0 and 1 inclusive." | ||
raise ValueError(msg) | ||
|
||
res = _quantile_hf(y, q_arr, n, method, xp) | ||
|
||
# Reshape per axis/keepdims | ||
if axis_none and keepdims: | ||
shape = (1,) * (ndim - 1) + res.shape | ||
res = xp.reshape(res, shape) | ||
axis = -1 | ||
|
||
# Move axis back to original position | ||
res = xp.moveaxis(res, -1, axis) | ||
|
||
if not keepdims and res.shape[axis] == 1: | ||
res = xp.squeeze(res, axis=axis) | ||
|
||
if res.ndim == 0: | ||
return res[()] | ||
return res | ||
|
||
|
||
def _quantile_hf( | ||
y: Array, p: Array, n: Array, method: str, xp: ModuleType | ||
) -> Array: # numpydoc ignore=PR01,RT01 | ||
"""Helper function for Hyndman-Fan quantile method.""" | ||
ms: dict[str, Array | int | float] = { | ||
"inverted_cdf": 0, | ||
"averaged_inverted_cdf": 0, | ||
"closest_observation": -0.5, | ||
"interpolated_inverted_cdf": 0, | ||
"hazen": 0.5, | ||
"weibull": p, | ||
"linear": 1 - p, | ||
"median_unbiased": p / 3 + 1 / 3, | ||
"normal_unbiased": p / 4 + 3 / 8, | ||
} | ||
m = ms[method] | ||
|
||
jg = p * n + m - 1 | ||
# Convert both to integers, the type of j and n must be the same | ||
# for us to be able to `xp.clip` them. | ||
j = xp.astype(jg // 1, xp.int64) | ||
n = xp.astype(n, xp.int64) | ||
g = jg % 1 | ||
|
||
if method == "inverted_cdf": | ||
g = xp.astype((g > 0), jg.dtype) | ||
elif method == "averaged_inverted_cdf": | ||
g = (1 + xp.astype((g > 0), jg.dtype)) / 2 | ||
elif method == "closest_observation": | ||
g = 1 - xp.astype((g == 0) & (j % 2 == 1), jg.dtype) | ||
if method in {"inverted_cdf", "averaged_inverted_cdf", "closest_observation"}: | ||
g = xp.asarray(g) | ||
g = at(g, jg < 0).set(0) | ||
g = at(g, j < 0).set(0) | ||
j = xp.clip(j, 0, n - 1) | ||
jp1 = xp.clip(j + 1, 0, n - 1) | ||
|
||
# Broadcast indices to match y shape except for the last axis | ||
if y.ndim > 1: | ||
# Create broadcast shape for indices | ||
broadcast_shape = [*y.shape[:-1], 1] | ||
j = xp.broadcast_to(j, broadcast_shape) | ||
jp1 = xp.broadcast_to(jp1, broadcast_shape) | ||
g = xp.broadcast_to(g, broadcast_shape) | ||
|
||
res = (1 - g) * xp.take_along_axis(y, j, axis=-1) + g * xp.take_along_axis( | ||
y, jp1, axis=-1 | ||
) | ||
return res # noqa: RET504 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
scikit-learn/scikit-learn#31671 (comment) suggests that delegation to some existing array libraries may be desirable here