Skip to content

MNT Updates _isotonic.pyx to use memoryviews instead of cnp.ndarray #26068

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

Merged
merged 10 commits into from
Apr 6, 2023
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ def check_package_status(package, min_version):
{"sources": ["_check_build.pyx"]},
],
"": [
{"sources": ["_isotonic.pyx"], "include_np": True},
{"sources": ["_isotonic.pyx"]},
],
"_loss": [
{"sources": ["_loss.pyx.tp"]},
Expand Down
28 changes: 17 additions & 11 deletions sklearn/_isotonic.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@
# pool at each step.

import numpy as np
cimport numpy as cnp
from cython cimport floating

cnp.import_array()


def _inplace_contiguous_isotonic_regression(floating[::1] y, floating[::1] w):
Expand Down Expand Up @@ -62,9 +60,9 @@ def _inplace_contiguous_isotonic_regression(floating[::1] y, floating[::1] w):
i = k


def _make_unique(cnp.ndarray[dtype=floating] X,
cnp.ndarray[dtype=floating] y,
cnp.ndarray[dtype=floating] sample_weights):
def _make_unique(const floating[::1] X,
const floating[::1] y,
const floating[::1] sample_weights):
"""Average targets for duplicate X, drop duplicates.

Aggregates duplicate X values into a single X value where
Expand All @@ -75,10 +73,14 @@ def _make_unique(cnp.ndarray[dtype=floating] X,
"""
unique_values = len(np.unique(X))

cdef cnp.ndarray[dtype=floating] y_out = np.empty(unique_values,
dtype=X.dtype)
cdef cnp.ndarray[dtype=floating] x_out = np.empty_like(y_out)
cdef cnp.ndarray[dtype=floating] weights_out = np.empty_like(y_out)
if floating is float:
dtype = np.float32
else:
dtype = np.float64

cdef floating[::1] y_out = np.empty(unique_values, dtype=dtype)
cdef floating[::1] x_out = np.empty_like(y_out)
cdef floating[::1] weights_out = np.empty_like(y_out)

cdef floating current_x = X[0]
cdef floating current_y = 0
Expand All @@ -88,7 +90,7 @@ def _make_unique(cnp.ndarray[dtype=floating] X,
cdef int j
cdef floating x
cdef int n_samples = len(X)
cdef floating eps = np.finfo(X.dtype).resolution
cdef floating eps = np.finfo(dtype).resolution

for j in range(n_samples):
x = X[j]
Expand All @@ -108,4 +110,8 @@ def _make_unique(cnp.ndarray[dtype=floating] X,
x_out[i] = current_x
weights_out[i] = current_weight
y_out[i] = current_y / current_weight
return x_out[:i+1], y_out[:i+1], weights_out[:i+1]
return(
np.asarray(x_out[:i+1]),
np.asarray(y_out[:i+1]),
np.asarray(weights_out[:i+1]),
)