Skip to content

Commit dfaa3f6

Browse files
authored
MNT refactor name of device function to array_device (scikit-learn#34543)
1 parent 675a5e1 commit dfaa3f6

46 files changed

Lines changed: 330 additions & 356 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

sklearn/_loss/tests/test_loss.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,10 @@
3737
from sklearn.utils import assert_all_finite
3838
from sklearn.utils._array_api import (
3939
_atol_for_type,
40+
array_device,
4041
move_to,
4142
yield_namespace_device_dtype_combinations,
4243
)
43-
from sklearn.utils._array_api import (
44-
device as array_api_device,
45-
)
4644
from sklearn.utils._testing import (
4745
_array_api_for_tests,
4846
create_memmap_backed_data,
@@ -1421,7 +1419,7 @@ def _assert_array_api_result(
14211419
move_to(result_xp, xp=np, device="cpu"), result_np, rtol=rtol, atol=atol
14221420
)
14231421
assert result_xp.dtype == raw_prediction_xp.dtype
1424-
assert array_api_device(result_xp) == array_api_device(raw_prediction_xp)
1422+
assert array_device(result_xp) == array_device(raw_prediction_xp)
14251423

14261424
if method_name == "gradient_proba" and loss_class != HalfMultinomialLoss:
14271425
# `gradient_proba` is only valid for HalfMultinomialLoss

sklearn/calibration.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -410,9 +410,9 @@ def fit(self, X, y, sample_weight=None, **fit_params):
410410
{"splitter": {}, "estimator": {"fit": fit_kwargs}}
411411
)
412412

413-
xp, is_array_api, device_ = get_namespace_and_device(X)
413+
xp, is_array_api, device = get_namespace_and_device(X)
414414
if is_array_api:
415-
y, sample_weight = move_to(y, sample_weight, xp=xp, device=device_)
415+
y, sample_weight = move_to(y, sample_weight, xp=xp, device=device)
416416
# Check that each cross-validation fold can have at least one
417417
# example per class
418418
if isinstance(self.cv, int):
@@ -527,8 +527,8 @@ def predict_proba(self, X):
527527
check_is_fitted(self)
528528
# Compute the arithmetic mean of the predictions of the calibrated
529529
# classifiers
530-
xp, _, device_ = get_namespace_and_device(X)
531-
mean_proba = xp.zeros((_num_samples(X), self.classes_.shape[0]), device=device_)
530+
xp, _, device = get_namespace_and_device(X)
531+
mean_proba = xp.zeros((_num_samples(X), self.classes_.shape[0]), device=device)
532532
for calibrated_classifier in self.calibrated_classifiers_:
533533
proba = calibrated_classifier.predict_proba(X)
534534
mean_proba += proba
@@ -981,7 +981,7 @@ def _convert_to_logits(decision_values, eps=1e-12, xp=None):
981981
-------
982982
logits : ndarray of shape (n_samples, n_classes)
983983
"""
984-
xp, _, device_ = get_namespace_and_device(decision_values, xp=xp)
984+
xp, _, device = get_namespace_and_device(decision_values, xp=xp)
985985
decision_values = check_array(
986986
decision_values, dtype=[xp.float64, xp.float32], ensure_2d=False
987987
)
@@ -993,7 +993,7 @@ def _convert_to_logits(decision_values, eps=1e-12, xp=None):
993993
row_sums_to_one = xp.all(
994994
xpx.isclose(
995995
xp.sum(decision_values, axis=1),
996-
xp.asarray(1.0, device=device_, dtype=decision_values.dtype),
996+
xp.asarray(1.0, device=device, dtype=decision_values.dtype),
997997
)
998998
)
999999

sklearn/covariance/_empirical_covariance.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -272,10 +272,10 @@ def fit(self, X, y=None):
272272
self : object
273273
Returns the instance itself.
274274
"""
275-
xp, _, device_ = get_namespace_and_device(X)
276-
X = validate_data(self, X, dtype=supported_float_dtypes(xp, device_))
275+
xp, _, device = get_namespace_and_device(X)
276+
X = validate_data(self, X, dtype=supported_float_dtypes(xp, device))
277277
if self.assume_centered:
278-
self.location_ = xp.zeros(X.shape[1], dtype=X.dtype, device=device_)
278+
self.location_ = xp.zeros(X.shape[1], dtype=X.dtype, device=device)
279279
else:
280280
self.location_ = xp.mean(X, axis=0)
281281
covariance = empirical_covariance(X, assume_centered=self.assume_centered)
@@ -388,9 +388,9 @@ def mahalanobis(self, X):
388388
dist : ndarray of shape (n_samples,)
389389
Squared Mahalanobis distances of the observations.
390390
"""
391-
xp, _, device_ = get_namespace_and_device(X)
391+
xp, _, device = get_namespace_and_device(X)
392392
X = validate_data(
393-
self, X, reset=False, dtype=supported_float_dtypes(xp, device_)
393+
self, X, reset=False, dtype=supported_float_dtypes(xp, device)
394394
)
395395

396396
precision = self.get_precision()

sklearn/covariance/_shrunk_covariance.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -623,10 +623,10 @@ def fit(self, X, y=None):
623623
"""
624624
# Not calling the parent object to fit, to avoid computing the
625625
# covariance matrix (and potentially the precision)
626-
xp, _, device_ = get_namespace_and_device(X)
627-
X = validate_data(self, X, dtype=supported_float_dtypes(xp, device_))
626+
xp, _, device = get_namespace_and_device(X)
627+
X = validate_data(self, X, dtype=supported_float_dtypes(xp, device))
628628
if self.assume_centered:
629-
self.location_ = xp.zeros(X.shape[1], dtype=X.dtype, device=device_)
629+
self.location_ = xp.zeros(X.shape[1], dtype=X.dtype, device=device)
630630
else:
631631
self.location_ = xp.mean(X, axis=0)
632632
covariance, shrinkage = _ledoit_wolf(

sklearn/decomposition/_base.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
ClassNamePrefixFeaturesOutMixin,
1414
TransformerMixin,
1515
)
16-
from sklearn.utils._array_api import _add_to_diagonal, device, get_namespace
16+
from sklearn.utils._array_api import _add_to_diagonal, array_device, get_namespace
1717
from sklearn.utils.validation import check_array, check_is_fitted, validate_data
1818

1919

@@ -48,7 +48,7 @@ def get_covariance(self):
4848
exp_var_diff = xp.where(
4949
exp_var > self.noise_variance_,
5050
exp_var_diff,
51-
xp.asarray(0.0, device=device(exp_var), dtype=exp_var.dtype),
51+
xp.asarray(0.0, device=array_device(exp_var), dtype=exp_var.dtype),
5252
)
5353
cov = (components_.T * exp_var_diff) @ components_
5454
_add_to_diagonal(cov, self.noise_variance_, xp)
@@ -90,7 +90,7 @@ def get_precision(self):
9090
exp_var_diff = xp.where(
9191
exp_var > self.noise_variance_,
9292
exp_var_diff,
93-
xp.asarray(0.0, device=device(exp_var)),
93+
xp.asarray(0.0, device=array_device(exp_var)),
9494
)
9595
precision = components_ @ components_.T / self.noise_variance_
9696
_add_to_diagonal(precision, 1.0 / exp_var_diff, xp)

sklearn/decomposition/_pca.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from sklearn.decomposition._base import _BasePCA
1616
from sklearn.utils import check_random_state
1717
from sklearn.utils._arpack import _init_arpack_v0
18-
from sklearn.utils._array_api import _cov, device, get_namespace
18+
from sklearn.utils._array_api import _cov, array_device, get_namespace
1919
from sklearn.utils._param_validation import Interval, RealNotInt, StrOptions
2020
from sklearn.utils.extmath import _randomized_svd, fast_logdet, svd_flip
2121
from sklearn.utils.sparsefuncs import _implicit_column_offset, mean_variance_axis
@@ -641,7 +641,7 @@ def _fit_full(self, X, n_components, xp, is_array_api_compliant):
641641
n_components = (
642642
xp.searchsorted(
643643
ratio_cumsum,
644-
xp.asarray(n_components, device=device(ratio_cumsum)),
644+
xp.asarray(n_components, device=array_device(ratio_cumsum)),
645645
side="right",
646646
)
647647
+ 1

sklearn/decomposition/tests/test_pca.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@
1313
from sklearn.decomposition._pca import _assess_dimension, _infer_dimension
1414
from sklearn.utils._array_api import (
1515
_atol_for_type,
16+
array_device,
1617
move_to,
1718
yield_namespace_device_dtype_combinations,
1819
)
19-
from sklearn.utils._array_api import device as array_device
2020
from sklearn.utils._test_common.instance_generator import _get_check_estimator_ids
2121
from sklearn.utils._testing import _array_api_for_tests, assert_allclose
2222
from sklearn.utils.estimator_checks import (

sklearn/discriminant_analysis.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@
2222
from sklearn.preprocessing import StandardScaler
2323
from sklearn.utils._array_api import (
2424
_expit,
25+
array_device,
2526
check_same_namespace,
26-
device,
2727
get_namespace,
2828
size,
2929
)
@@ -113,7 +113,9 @@ def _class_means(X, y):
113113
"""
114114
xp, is_array_api_compliant = get_namespace(X)
115115
classes, y = xp.unique_inverse(y)
116-
means = xp.zeros((classes.shape[0], X.shape[1]), device=device(X), dtype=X.dtype)
116+
means = xp.zeros(
117+
(classes.shape[0], X.shape[1]), device=array_device(X), dtype=X.dtype
118+
)
117119

118120
if is_array_api_compliant:
119121
for i in range(classes.shape[0]):
@@ -602,7 +604,9 @@ def _solve_svd(self, X, y):
602604
std = xp.std(Xc, axis=0)
603605
# avoid division by zero in normalization
604606
std[std == 0] = 1.0
605-
fac = xp.asarray(1.0 / (n_samples - n_classes), dtype=X.dtype, device=device(X))
607+
fac = xp.asarray(
608+
1.0 / (n_samples - n_classes), dtype=X.dtype, device=array_device(X)
609+
)
606610

607611
# 2) Within variance scaling
608612
X = xp.sqrt(fac) * (Xc / std)

sklearn/linear_model/_base.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ def _preprocess_data(
164164
sample_weight_sqrt : ndarray of shape (n_samples, ) or None
165165
`np.sqrt(sample_weight)`
166166
"""
167-
xp, _, device_ = get_namespace_and_device(X, y, sample_weight)
167+
xp, _, device = get_namespace_and_device(X, y, sample_weight)
168168
n_samples, n_features = X.shape
169169
X_is_sparse = sp.issparse(X)
170170

@@ -173,7 +173,7 @@ def _preprocess_data(
173173
X,
174174
copy=copy,
175175
accept_sparse=["csr", "csc"],
176-
dtype=supported_float_dtypes(xp, device=device_),
176+
dtype=supported_float_dtypes(xp, device=device),
177177
)
178178
y = check_array(y, dtype=X.dtype, copy=True, ensure_2d=False)
179179
else:
@@ -198,15 +198,15 @@ def _preprocess_data(
198198
y_offset = _average(y, axis=0, weights=sample_weight, xp=xp)
199199
y -= y_offset
200200
else:
201-
X_offset = xp.zeros(n_features, dtype=X.dtype, device=device_)
201+
X_offset = xp.zeros(n_features, dtype=X.dtype, device=device)
202202
if y.ndim == 1:
203-
y_offset = xp.asarray(0.0, dtype=dtype_, device=device_)
203+
y_offset = xp.asarray(0.0, dtype=dtype_, device=device)
204204
else:
205-
y_offset = xp.zeros(y.shape[1], dtype=dtype_, device=device_)
205+
y_offset = xp.zeros(y.shape[1], dtype=dtype_, device=device)
206206

207207
# X_scale is no longer needed. It is a historic artifact from the
208208
# time where linear model exposed the normalize parameter.
209-
X_scale = xp.ones(n_features, dtype=X.dtype, device=device_)
209+
X_scale = xp.ones(n_features, dtype=X.dtype, device=device)
210210

211211
if sample_weight is not None and rescale_with_sw:
212212
# Sample weight can be implemented via a simple rescaling.
@@ -410,7 +410,7 @@ def predict(self, X):
410410
Vector containing the class labels for each sample.
411411
"""
412412
check_same_namespace(X, self, attribute="coef_", method="predict")
413-
xp, _, device_ = get_namespace_and_device(X)
413+
xp, _, device = get_namespace_and_device(X)
414414
scores = self.decision_function(X)
415415
if len(scores.shape) == 1:
416416
indices = xp.astype(scores > 0, indexing_dtype(xp))
@@ -424,7 +424,7 @@ def predict(self, X):
424424
if isinstance(y_pred[0], str):
425425
return y_pred
426426
else:
427-
return move_to(y_pred, xp=xp, device=device_)
427+
return move_to(y_pred, xp=xp, device=device)
428428

429429
def _predict_proba_lr(self, X):
430430
"""Probability estimation for OvR logistic regression.

sklearn/linear_model/_glm/glm.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ def fit(self, X, y, sample_weight=None):
262262
f"l1_ratio={self.l1_ratio}."
263263
)
264264
raise ValueError(msg)
265-
xp, _, device_ = get_namespace_and_device(X)
265+
xp, _, device = get_namespace_and_device(X)
266266
X, y = validate_data(
267267
self,
268268
X,
@@ -280,10 +280,10 @@ def fit(self, X, y, sample_weight=None):
280280
# losses.
281281
sample_weight = _check_sample_weight(sample_weight, X, dtype=loss_dtype)
282282

283-
y, sample_weight = move_to(y, sample_weight, xp=xp, device=device_)
283+
y, sample_weight = move_to(y, sample_weight, xp=xp, device=device)
284284

285285
n_samples, n_features = X.shape
286-
self._base_loss = self._get_loss(xp=xp, device=device_)
286+
self._base_loss = self._get_loss(xp=xp, device=device)
287287

288288
linear_loss = LinearModelLoss(
289289
base_loss=self._base_loss,
@@ -362,7 +362,7 @@ def fit(self, X, y, sample_weight=None):
362362
coef = xp.asarray(
363363
coef.copy(order="C" if not _is_numpy_namespace(xp) else "K"),
364364
dtype=X.dtype,
365-
device=device_,
365+
device=device,
366366
)
367367
elif self.solver == "newton-cg":
368368
func = linear_loss.loss
@@ -514,8 +514,8 @@ def score(self, X, y, sample_weight=None):
514514
# losses.
515515
sample_weight = _check_sample_weight(sample_weight, X, dtype=y.dtype)
516516

517-
xp, _, device_ = get_namespace_and_device(X)
518-
y, sample_weight = move_to(y, sample_weight, xp=xp, device=device_)
517+
xp, _, device = get_namespace_and_device(X)
518+
y, sample_weight = move_to(y, sample_weight, xp=xp, device=device)
519519

520520
base_loss = self._base_loss
521521

0 commit comments

Comments
 (0)