diff --git a/ckpts/universal/global_step40/zero/10.mlp.dense_4h_to_h.weight/fp32.pt b/ckpts/universal/global_step40/zero/10.mlp.dense_4h_to_h.weight/fp32.pt new file mode 100644 index 0000000000000000000000000000000000000000..c64fb9384b47c703ff9e59eb4ecdd23208524afb --- /dev/null +++ b/ckpts/universal/global_step40/zero/10.mlp.dense_4h_to_h.weight/fp32.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bae3355ac505dba276fbc9ef1a8d8a4a431a137ebb360756af8d63420c8d51f2 +size 33555533 diff --git a/ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/exp_avg.pt b/ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/exp_avg.pt new file mode 100644 index 0000000000000000000000000000000000000000..90e78262784b09ce31630469c12e810c92af6425 --- /dev/null +++ b/ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/exp_avg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cadac90d4f41233545e34e5aa5b51138130b7cd0ade41055f9eb78dfffab118d +size 33555612 diff --git a/ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/exp_avg_sq.pt b/ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..101377e8abd359d132579d45ac787ef504d1a6bf --- /dev/null +++ b/ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e379e326b77e978f944bd8a16ac6eabfab08f8e5c84039959e2281e0f6f331f +size 33555627 diff --git a/ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/fp32.pt b/ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/fp32.pt new file mode 100644 index 0000000000000000000000000000000000000000..61a69e12d169ef3f409f2c6142682bc353a16570 --- /dev/null +++ b/ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/fp32.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10f2fae360748617999505b629e700527fd4f54adec3a0a0d65e18d641104e1c +size 33555533 diff --git a/ckpts/universal/global_step40/zero/21.attention.query_key_value.weight/exp_avg.pt b/ckpts/universal/global_step40/zero/21.attention.query_key_value.weight/exp_avg.pt new file mode 100644 index 0000000000000000000000000000000000000000..252f6152d1e81738b9553447e228dde5ce3e8d83 --- /dev/null +++ b/ckpts/universal/global_step40/zero/21.attention.query_key_value.weight/exp_avg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33d6a07534b7dcdeb437b1000f825147b2ad45d03b9447841dad2ec134b17d00 +size 50332828 diff --git a/ckpts/universal/global_step40/zero/21.attention.query_key_value.weight/exp_avg_sq.pt b/ckpts/universal/global_step40/zero/21.attention.query_key_value.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..dc77a6686d7d2e3d34545acc19690b9e934747e0 --- /dev/null +++ b/ckpts/universal/global_step40/zero/21.attention.query_key_value.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2062d08884b7b2cbf5001d295a8965e9df7e168728992285576d6a82f2934cb +size 50332843 diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_bunch.py b/venv/lib/python3.10/site-packages/sklearn/utils/_bunch.py new file mode 100644 index 0000000000000000000000000000000000000000..d90aeb7d93c74d483254901d51da9d82d39cfe6a --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_bunch.py @@ -0,0 +1,67 @@ +import warnings + + +class Bunch(dict): + """Container object exposing keys as attributes. + + Bunch objects are sometimes used as an output for functions and methods. + They extend dictionaries by enabling values to be accessed by key, + `bunch["value_key"]`, or by an attribute, `bunch.value_key`. + + Examples + -------- + >>> from sklearn.utils import Bunch + >>> b = Bunch(a=1, b=2) + >>> b['b'] + 2 + >>> b.b + 2 + >>> b.a = 3 + >>> b['a'] + 3 + >>> b.c = 6 + >>> b['c'] + 6 + """ + + def __init__(self, **kwargs): + super().__init__(kwargs) + + # Map from deprecated key to warning message + self.__dict__["_deprecated_key_to_warnings"] = {} + + def __getitem__(self, key): + if key in self.__dict__.get("_deprecated_key_to_warnings", {}): + warnings.warn( + self._deprecated_key_to_warnings[key], + FutureWarning, + ) + return super().__getitem__(key) + + def _set_deprecated(self, value, *, new_key, deprecated_key, warning_message): + """Set key in dictionary to be deprecated with its warning message.""" + self.__dict__["_deprecated_key_to_warnings"][deprecated_key] = warning_message + self[new_key] = self[deprecated_key] = value + + def __setattr__(self, key, value): + self[key] = value + + def __dir__(self): + return self.keys() + + def __getattr__(self, key): + try: + return self[key] + except KeyError: + raise AttributeError(key) + + def __setstate__(self, state): + # Bunch pickles generated with scikit-learn 0.16.* have an non + # empty __dict__. This causes a surprising behaviour when + # loading these pickles scikit-learn 0.17: reading bunch.key + # uses __dict__ but assigning to bunch.key use __setattr__ and + # only changes bunch['key']. More details can be found at: + # https://github.com/scikit-learn/scikit-learn/issues/6196. + # Overriding __setstate__ to be a noop has the effect of + # ignoring the pickled __dict__ + pass diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_cython_blas.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/sklearn/utils/_cython_blas.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..aaf9a874f9b2557df52260c47ed062cd48472978 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/_cython_blas.cpython-310-x86_64-linux-gnu.so differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_cython_blas.pxd b/venv/lib/python3.10/site-packages/sklearn/utils/_cython_blas.pxd new file mode 100644 index 0000000000000000000000000000000000000000..1187eb49d25d4248cda1cc7d06f62583b1761f49 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_cython_blas.pxd @@ -0,0 +1,41 @@ +from cython cimport floating + + +cpdef enum BLAS_Order: + RowMajor # C contiguous + ColMajor # Fortran contiguous + + +cpdef enum BLAS_Trans: + NoTrans = 110 # correspond to 'n' + Trans = 116 # correspond to 't' + + +# BLAS Level 1 ################################################################ +cdef floating _dot(int, const floating*, int, const floating*, int) noexcept nogil + +cdef floating _asum(int, const floating*, int) noexcept nogil + +cdef void _axpy(int, floating, const floating*, int, floating*, int) noexcept nogil + +cdef floating _nrm2(int, const floating*, int) noexcept nogil + +cdef void _copy(int, const floating*, int, const floating*, int) noexcept nogil + +cdef void _scal(int, floating, const floating*, int) noexcept nogil + +cdef void _rotg(floating*, floating*, floating*, floating*) noexcept nogil + +cdef void _rot(int, floating*, int, floating*, int, floating, floating) noexcept nogil + +# BLAS Level 2 ################################################################ +cdef void _gemv(BLAS_Order, BLAS_Trans, int, int, floating, const floating*, int, + const floating*, int, floating, floating*, int) noexcept nogil + +cdef void _ger(BLAS_Order, int, int, floating, const floating*, int, const floating*, + int, floating*, int) noexcept nogil + +# BLASLevel 3 ################################################################ +cdef void _gemm(BLAS_Order, BLAS_Trans, BLAS_Trans, int, int, int, floating, + const floating*, int, const floating*, int, floating, floating*, + int) noexcept nogil diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_fast_dict.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/sklearn/utils/_fast_dict.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..bde968659e9e7f1346513e73fe97764271e72ea6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/_fast_dict.cpython-310-x86_64-linux-gnu.so differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_heap.pxd b/venv/lib/python3.10/site-packages/sklearn/utils/_heap.pxd new file mode 100644 index 0000000000000000000000000000000000000000..39de4dc02d315f8decd1fa06f430759eaa57e68e --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_heap.pxd @@ -0,0 +1,14 @@ +# Heap routines, used in various Cython implementations. + +from cython cimport floating + +from ._typedefs cimport intp_t + + +cdef int heap_push( + floating* values, + intp_t* indices, + intp_t size, + floating val, + intp_t val_idx, +) noexcept nogil diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_mask.py b/venv/lib/python3.10/site-packages/sklearn/utils/_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..07332bf1edbd4a21b14c974937ba80ff3cbad13f --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_mask.py @@ -0,0 +1,63 @@ +from contextlib import suppress + +import numpy as np +from scipy import sparse as sp + +from . import is_scalar_nan +from .fixes import _object_dtype_isnan + + +def _get_dense_mask(X, value_to_mask): + with suppress(ImportError, AttributeError): + # We also suppress `AttributeError` because older versions of pandas do + # not have `NA`. + import pandas + + if value_to_mask is pandas.NA: + return pandas.isna(X) + + if is_scalar_nan(value_to_mask): + if X.dtype.kind == "f": + Xt = np.isnan(X) + elif X.dtype.kind in ("i", "u"): + # can't have NaNs in integer array. + Xt = np.zeros(X.shape, dtype=bool) + else: + # np.isnan does not work on object dtypes. + Xt = _object_dtype_isnan(X) + else: + Xt = X == value_to_mask + + return Xt + + +def _get_mask(X, value_to_mask): + """Compute the boolean mask X == value_to_mask. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + Input data, where ``n_samples`` is the number of samples and + ``n_features`` is the number of features. + + value_to_mask : {int, float} + The value which is to be masked in X. + + Returns + ------- + X_mask : {ndarray, sparse matrix} of shape (n_samples, n_features) + Missing mask. + """ + if not sp.issparse(X): + # For all cases apart of a sparse input where we need to reconstruct + # a sparse output + return _get_dense_mask(X, value_to_mask) + + Xt = _get_dense_mask(X.data, value_to_mask) + + sparse_constructor = sp.csr_matrix if X.format == "csr" else sp.csc_matrix + Xt_sparse = sparse_constructor( + (Xt, X.indices.copy(), X.indptr.copy()), shape=X.shape, dtype=bool + ) + + return Xt_sparse diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_mocking.py b/venv/lib/python3.10/site-packages/sklearn/utils/_mocking.py new file mode 100644 index 0000000000000000000000000000000000000000..16acabf03755bb31509cfb2d9fc46d94f3261fcb --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_mocking.py @@ -0,0 +1,400 @@ +import numpy as np + +from ..base import BaseEstimator, ClassifierMixin +from ..utils._metadata_requests import RequestMethod +from .metaestimators import available_if +from .validation import _check_sample_weight, _num_samples, check_array, check_is_fitted + + +class ArraySlicingWrapper: + """ + Parameters + ---------- + array + """ + + def __init__(self, array): + self.array = array + + def __getitem__(self, aslice): + return MockDataFrame(self.array[aslice]) + + +class MockDataFrame: + """ + Parameters + ---------- + array + """ + + # have shape and length but don't support indexing. + + def __init__(self, array): + self.array = array + self.values = array + self.shape = array.shape + self.ndim = array.ndim + # ugly hack to make iloc work. + self.iloc = ArraySlicingWrapper(array) + + def __len__(self): + return len(self.array) + + def __array__(self, dtype=None): + # Pandas data frames also are array-like: we want to make sure that + # input validation in cross-validation does not try to call that + # method. + return self.array + + def __eq__(self, other): + return MockDataFrame(self.array == other.array) + + def __ne__(self, other): + return not self == other + + def take(self, indices, axis=0): + return MockDataFrame(self.array.take(indices, axis=axis)) + + +class CheckingClassifier(ClassifierMixin, BaseEstimator): + """Dummy classifier to test pipelining and meta-estimators. + + Checks some property of `X` and `y`in fit / predict. + This allows testing whether pipelines / cross-validation or metaestimators + changed the input. + + Can also be used to check if `fit_params` are passed correctly, and + to force a certain score to be returned. + + Parameters + ---------- + check_y, check_X : callable, default=None + The callable used to validate `X` and `y`. These callable should return + a bool where `False` will trigger an `AssertionError`. If `None`, the + data is not validated. Default is `None`. + + check_y_params, check_X_params : dict, default=None + The optional parameters to pass to `check_X` and `check_y`. If `None`, + then no parameters are passed in. + + methods_to_check : "all" or list of str, default="all" + The methods in which the checks should be applied. By default, + all checks will be done on all methods (`fit`, `predict`, + `predict_proba`, `decision_function` and `score`). + + foo_param : int, default=0 + A `foo` param. When `foo > 1`, the output of :meth:`score` will be 1 + otherwise it is 0. + + expected_sample_weight : bool, default=False + Whether to check if a valid `sample_weight` was passed to `fit`. + + expected_fit_params : list of str, default=None + A list of the expected parameters given when calling `fit`. + + Attributes + ---------- + classes_ : int + The classes seen during `fit`. + + n_features_in_ : int + The number of features seen during `fit`. + + Examples + -------- + >>> from sklearn.utils._mocking import CheckingClassifier + + This helper allow to assert to specificities regarding `X` or `y`. In this + case we expect `check_X` or `check_y` to return a boolean. + + >>> from sklearn.datasets import load_iris + >>> X, y = load_iris(return_X_y=True) + >>> clf = CheckingClassifier(check_X=lambda x: x.shape == (150, 4)) + >>> clf.fit(X, y) + CheckingClassifier(...) + + We can also provide a check which might raise an error. In this case, we + expect `check_X` to return `X` and `check_y` to return `y`. + + >>> from sklearn.utils import check_array + >>> clf = CheckingClassifier(check_X=check_array) + >>> clf.fit(X, y) + CheckingClassifier(...) + """ + + def __init__( + self, + *, + check_y=None, + check_y_params=None, + check_X=None, + check_X_params=None, + methods_to_check="all", + foo_param=0, + expected_sample_weight=None, + expected_fit_params=None, + ): + self.check_y = check_y + self.check_y_params = check_y_params + self.check_X = check_X + self.check_X_params = check_X_params + self.methods_to_check = methods_to_check + self.foo_param = foo_param + self.expected_sample_weight = expected_sample_weight + self.expected_fit_params = expected_fit_params + + def _check_X_y(self, X, y=None, should_be_fitted=True): + """Validate X and y and make extra check. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data set. + `X` is checked only if `check_X` is not `None` (default is None). + y : array-like of shape (n_samples), default=None + The corresponding target, by default `None`. + `y` is checked only if `check_y` is not `None` (default is None). + should_be_fitted : bool, default=True + Whether or not the classifier should be already fitted. + By default True. + + Returns + ------- + X, y + """ + if should_be_fitted: + check_is_fitted(self) + if self.check_X is not None: + params = {} if self.check_X_params is None else self.check_X_params + checked_X = self.check_X(X, **params) + if isinstance(checked_X, (bool, np.bool_)): + assert checked_X + else: + X = checked_X + if y is not None and self.check_y is not None: + params = {} if self.check_y_params is None else self.check_y_params + checked_y = self.check_y(y, **params) + if isinstance(checked_y, (bool, np.bool_)): + assert checked_y + else: + y = checked_y + return X, y + + def fit(self, X, y, sample_weight=None, **fit_params): + """Fit classifier. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : array-like of shape (n_samples, n_outputs) or (n_samples,), \ + default=None + Target relative to X for classification or regression; + None for unsupervised learning. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. If None, then samples are equally weighted. + + **fit_params : dict of string -> object + Parameters passed to the ``fit`` method of the estimator + + Returns + ------- + self + """ + assert _num_samples(X) == _num_samples(y) + if self.methods_to_check == "all" or "fit" in self.methods_to_check: + X, y = self._check_X_y(X, y, should_be_fitted=False) + self.n_features_in_ = np.shape(X)[1] + self.classes_ = np.unique(check_array(y, ensure_2d=False, allow_nd=True)) + if self.expected_fit_params: + missing = set(self.expected_fit_params) - set(fit_params) + if missing: + raise AssertionError( + f"Expected fit parameter(s) {list(missing)} not seen." + ) + for key, value in fit_params.items(): + if _num_samples(value) != _num_samples(X): + raise AssertionError( + f"Fit parameter {key} has length {_num_samples(value)}" + f"; expected {_num_samples(X)}." + ) + if self.expected_sample_weight: + if sample_weight is None: + raise AssertionError("Expected sample_weight to be passed") + _check_sample_weight(sample_weight, X) + + return self + + def predict(self, X): + """Predict the first class seen in `classes_`. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The input data. + + Returns + ------- + preds : ndarray of shape (n_samples,) + Predictions of the first class seens in `classes_`. + """ + if self.methods_to_check == "all" or "predict" in self.methods_to_check: + X, y = self._check_X_y(X) + return self.classes_[np.zeros(_num_samples(X), dtype=int)] + + def predict_proba(self, X): + """Predict probabilities for each class. + + Here, the dummy classifier will provide a probability of 1 for the + first class of `classes_` and 0 otherwise. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The input data. + + Returns + ------- + proba : ndarray of shape (n_samples, n_classes) + The probabilities for each sample and class. + """ + if self.methods_to_check == "all" or "predict_proba" in self.methods_to_check: + X, y = self._check_X_y(X) + proba = np.zeros((_num_samples(X), len(self.classes_))) + proba[:, 0] = 1 + return proba + + def decision_function(self, X): + """Confidence score. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The input data. + + Returns + ------- + decision : ndarray of shape (n_samples,) if n_classes == 2\ + else (n_samples, n_classes) + Confidence score. + """ + if ( + self.methods_to_check == "all" + or "decision_function" in self.methods_to_check + ): + X, y = self._check_X_y(X) + if len(self.classes_) == 2: + # for binary classifier, the confidence score is related to + # classes_[1] and therefore should be null. + return np.zeros(_num_samples(X)) + else: + decision = np.zeros((_num_samples(X), len(self.classes_))) + decision[:, 0] = 1 + return decision + + def score(self, X=None, Y=None): + """Fake score. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Input data, where `n_samples` is the number of samples and + `n_features` is the number of features. + + Y : array-like of shape (n_samples, n_output) or (n_samples,) + Target relative to X for classification or regression; + None for unsupervised learning. + + Returns + ------- + score : float + Either 0 or 1 depending of `foo_param` (i.e. `foo_param > 1 => + score=1` otherwise `score=0`). + """ + if self.methods_to_check == "all" or "score" in self.methods_to_check: + self._check_X_y(X, Y) + if self.foo_param > 1: + score = 1.0 + else: + score = 0.0 + return score + + def _more_tags(self): + return {"_skip_test": True, "X_types": ["1dlabel"]} + + +# Deactivate key validation for CheckingClassifier because we want to be able to +# call fit with arbitrary fit_params and record them. Without this change, we +# would get an error because those arbitrary params are not expected. +CheckingClassifier.set_fit_request = RequestMethod( # type: ignore + name="fit", keys=[], validate_keys=False +) + + +class NoSampleWeightWrapper(BaseEstimator): + """Wrap estimator which will not expose `sample_weight`. + + Parameters + ---------- + est : estimator, default=None + The estimator to wrap. + """ + + def __init__(self, est=None): + self.est = est + + def fit(self, X, y): + return self.est.fit(X, y) + + def predict(self, X): + return self.est.predict(X) + + def predict_proba(self, X): + return self.est.predict_proba(X) + + def _more_tags(self): + return {"_skip_test": True} + + +def _check_response(method): + def check(self): + return self.response_methods is not None and method in self.response_methods + + return check + + +class _MockEstimatorOnOffPrediction(BaseEstimator): + """Estimator for which we can turn on/off the prediction methods. + + Parameters + ---------- + response_methods: list of \ + {"predict", "predict_proba", "decision_function"}, default=None + List containing the response implemented by the estimator. When, the + response is in the list, it will return the name of the response method + when called. Otherwise, an `AttributeError` is raised. It allows to + use `getattr` as any conventional estimator. By default, no response + methods are mocked. + """ + + def __init__(self, response_methods=None): + self.response_methods = response_methods + + def fit(self, X, y): + self.classes_ = np.unique(y) + return self + + @available_if(_check_response("predict")) + def predict(self, X): + return "predict" + + @available_if(_check_response("predict_proba")) + def predict_proba(self, X): + return "predict_proba" + + @available_if(_check_response("decision_function")) + def decision_function(self, X): + return "decision_function" diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ca49165d6512da35769bc0e3d331453a5462cc8e Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.cpython-310-x86_64-linux-gnu.so differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_plotting.py b/venv/lib/python3.10/site-packages/sklearn/utils/_plotting.py new file mode 100644 index 0000000000000000000000000000000000000000..84eaacc152884f3ba6bba1105b457100887af001 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_plotting.py @@ -0,0 +1,98 @@ +import numpy as np + +from . import check_consistent_length, check_matplotlib_support +from ._response import _get_response_values_binary +from .multiclass import type_of_target +from .validation import _check_pos_label_consistency + + +class _BinaryClassifierCurveDisplayMixin: + """Mixin class to be used in Displays requiring a binary classifier. + + The aim of this class is to centralize some validations regarding the estimator and + the target and gather the response of the estimator. + """ + + def _validate_plot_params(self, *, ax=None, name=None): + check_matplotlib_support(f"{self.__class__.__name__}.plot") + import matplotlib.pyplot as plt + + if ax is None: + _, ax = plt.subplots() + + name = self.estimator_name if name is None else name + return ax, ax.figure, name + + @classmethod + def _validate_and_get_response_values( + cls, estimator, X, y, *, response_method="auto", pos_label=None, name=None + ): + check_matplotlib_support(f"{cls.__name__}.from_estimator") + + name = estimator.__class__.__name__ if name is None else name + + y_pred, pos_label = _get_response_values_binary( + estimator, + X, + response_method=response_method, + pos_label=pos_label, + ) + + return y_pred, pos_label, name + + @classmethod + def _validate_from_predictions_params( + cls, y_true, y_pred, *, sample_weight=None, pos_label=None, name=None + ): + check_matplotlib_support(f"{cls.__name__}.from_predictions") + + if type_of_target(y_true) != "binary": + raise ValueError( + f"The target y is not binary. Got {type_of_target(y_true)} type of" + " target." + ) + + check_consistent_length(y_true, y_pred, sample_weight) + pos_label = _check_pos_label_consistency(pos_label, y_true) + + name = name if name is not None else "Classifier" + + return pos_label, name + + +def _validate_score_name(score_name, scoring, negate_score): + """Validate the `score_name` parameter. + + If `score_name` is provided, we just return it as-is. + If `score_name` is `None`, we use `Score` if `negate_score` is `False` and + `Negative score` otherwise. + If `score_name` is a string or a callable, we infer the name. We replace `_` by + spaces and capitalize the first letter. We remove `neg_` and replace it by + `"Negative"` if `negate_score` is `False` or just remove it otherwise. + """ + if score_name is not None: + return score_name + elif scoring is None: + return "Negative score" if negate_score else "Score" + else: + score_name = scoring.__name__ if callable(scoring) else scoring + if negate_score: + if score_name.startswith("neg_"): + score_name = score_name[4:] + else: + score_name = f"Negative {score_name}" + elif score_name.startswith("neg_"): + score_name = f"Negative {score_name[4:]}" + score_name = score_name.replace("_", " ") + return score_name.capitalize() + + +def _interval_max_min_ratio(data): + """Compute the ratio between the largest and smallest inter-point distances. + + A value larger than 5 typically indicates that the parameter range would + better be displayed with a log scale while a linear scale would be more + suitable otherwise. + """ + diff = np.diff(np.sort(data)) + return diff.max() / diff.min() diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_random.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/sklearn/utils/_random.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..820e77e469fbbaa3d752abf33f7051c688fc021c Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/_random.cpython-310-x86_64-linux-gnu.so differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_response.py b/venv/lib/python3.10/site-packages/sklearn/utils/_response.py new file mode 100644 index 0000000000000000000000000000000000000000..e647ba3a4f0094402709eeca4b3f709528cb0746 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_response.py @@ -0,0 +1,298 @@ +"""Utilities to get the response values of a classifier or a regressor. + +It allows to make uniform checks and validation. +""" +import numpy as np + +from ..base import is_classifier +from .multiclass import type_of_target +from .validation import _check_response_method, check_is_fitted + + +def _process_predict_proba(*, y_pred, target_type, classes, pos_label): + """Get the response values when the response method is `predict_proba`. + + This function process the `y_pred` array in the binary and multi-label cases. + In the binary case, it selects the column corresponding to the positive + class. In the multi-label case, it stacks the predictions if they are not + in the "compressed" format `(n_samples, n_outputs)`. + + Parameters + ---------- + y_pred : ndarray + Output of `estimator.predict_proba`. The shape depends on the target type: + + - for binary classification, it is a 2d array of shape `(n_samples, 2)`; + - for multiclass classification, it is a 2d array of shape + `(n_samples, n_classes)`; + - for multilabel classification, it is either a list of 2d arrays of shape + `(n_samples, 2)` (e.g. `RandomForestClassifier` or `KNeighborsClassifier`) or + an array of shape `(n_samples, n_outputs)` (e.g. `MLPClassifier` or + `RidgeClassifier`). + + target_type : {"binary", "multiclass", "multilabel-indicator"} + Type of the target. + + classes : ndarray of shape (n_classes,) or list of such arrays + Class labels as reported by `estimator.classes_`. + + pos_label : int, float, bool or str + Only used with binary and multiclass targets. + + Returns + ------- + y_pred : ndarray of shape (n_samples,), (n_samples, n_classes) or \ + (n_samples, n_output) + Compressed predictions format as requested by the metrics. + """ + if target_type == "binary" and y_pred.shape[1] < 2: + # We don't handle classifiers trained on a single class. + raise ValueError( + f"Got predict_proba of shape {y_pred.shape}, but need " + "classifier with two classes." + ) + + if target_type == "binary": + col_idx = np.flatnonzero(classes == pos_label)[0] + return y_pred[:, col_idx] + elif target_type == "multilabel-indicator": + # Use a compress format of shape `(n_samples, n_output)`. + # Only `MLPClassifier` and `RidgeClassifier` return an array of shape + # `(n_samples, n_outputs)`. + if isinstance(y_pred, list): + # list of arrays of shape `(n_samples, 2)` + return np.vstack([p[:, -1] for p in y_pred]).T + else: + # array of shape `(n_samples, n_outputs)` + return y_pred + + return y_pred + + +def _process_decision_function(*, y_pred, target_type, classes, pos_label): + """Get the response values when the response method is `decision_function`. + + This function process the `y_pred` array in the binary and multi-label cases. + In the binary case, it inverts the sign of the score if the positive label + is not `classes[1]`. In the multi-label case, it stacks the predictions if + they are not in the "compressed" format `(n_samples, n_outputs)`. + + Parameters + ---------- + y_pred : ndarray + Output of `estimator.predict_proba`. The shape depends on the target type: + + - for binary classification, it is a 1d array of shape `(n_samples,)` where the + sign is assuming that `classes[1]` is the positive class; + - for multiclass classification, it is a 2d array of shape + `(n_samples, n_classes)`; + - for multilabel classification, it is a 2d array of shape `(n_samples, + n_outputs)`. + + target_type : {"binary", "multiclass", "multilabel-indicator"} + Type of the target. + + classes : ndarray of shape (n_classes,) or list of such arrays + Class labels as reported by `estimator.classes_`. + + pos_label : int, float, bool or str + Only used with binary and multiclass targets. + + Returns + ------- + y_pred : ndarray of shape (n_samples,), (n_samples, n_classes) or \ + (n_samples, n_output) + Compressed predictions format as requested by the metrics. + """ + if target_type == "binary" and pos_label == classes[0]: + return -1 * y_pred + return y_pred + + +def _get_response_values( + estimator, + X, + response_method, + pos_label=None, + return_response_method_used=False, +): + """Compute the response values of a classifier, an outlier detector, or a regressor. + + The response values are predictions such that it follows the following shape: + + - for binary classification, it is a 1d array of shape `(n_samples,)`; + - for multiclass classification, it is a 2d array of shape `(n_samples, n_classes)`; + - for multilabel classification, it is a 2d array of shape `(n_samples, n_outputs)`; + - for outlier detection, it is a 1d array of shape `(n_samples,)`; + - for regression, it is a 1d array of shape `(n_samples,)`. + + If `estimator` is a binary classifier, also return the label for the + effective positive class. + + This utility is used primarily in the displays and the scikit-learn scorers. + + .. versionadded:: 1.3 + + Parameters + ---------- + estimator : estimator instance + Fitted classifier, outlier detector, or regressor or a + fitted :class:`~sklearn.pipeline.Pipeline` in which the last estimator is a + classifier, an outlier detector, or a regressor. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + response_method : {"predict_proba", "predict_log_proba", "decision_function", \ + "predict"} or list of such str + Specifies the response method to use get prediction from an estimator + (i.e. :term:`predict_proba`, :term:`predict_log_proba`, + :term:`decision_function` or :term:`predict`). Possible choices are: + + - if `str`, it corresponds to the name to the method to return; + - if a list of `str`, it provides the method names in order of + preference. The method returned corresponds to the first method in + the list and which is implemented by `estimator`. + + pos_label : int, float, bool or str, default=None + The class considered as the positive class when computing + the metrics. If `None` and target is 'binary', `estimators.classes_[1]` is + considered as the positive class. + + return_response_method_used : bool, default=False + Whether to return the response method used to compute the response + values. + + .. versionadded:: 1.4 + + Returns + ------- + y_pred : ndarray of shape (n_samples,), (n_samples, n_classes) or \ + (n_samples, n_outputs) + Target scores calculated from the provided `response_method` + and `pos_label`. + + pos_label : int, float, bool, str or None + The class considered as the positive class when computing + the metrics. Returns `None` if `estimator` is a regressor or an outlier + detector. + + response_method_used : str + The response method used to compute the response values. Only returned + if `return_response_method_used` is `True`. + + .. versionadded:: 1.4 + + Raises + ------ + ValueError + If `pos_label` is not a valid label. + If the shape of `y_pred` is not consistent for binary classifier. + If the response method can be applied to a classifier only and + `estimator` is a regressor. + """ + from sklearn.base import is_classifier, is_outlier_detector # noqa + + if is_classifier(estimator): + prediction_method = _check_response_method(estimator, response_method) + classes = estimator.classes_ + target_type = type_of_target(classes) + + if target_type in ("binary", "multiclass"): + if pos_label is not None and pos_label not in classes.tolist(): + raise ValueError( + f"pos_label={pos_label} is not a valid label: It should be " + f"one of {classes}" + ) + elif pos_label is None and target_type == "binary": + pos_label = classes[-1] + + y_pred = prediction_method(X) + + if prediction_method.__name__ in ("predict_proba", "predict_log_proba"): + y_pred = _process_predict_proba( + y_pred=y_pred, + target_type=target_type, + classes=classes, + pos_label=pos_label, + ) + elif prediction_method.__name__ == "decision_function": + y_pred = _process_decision_function( + y_pred=y_pred, + target_type=target_type, + classes=classes, + pos_label=pos_label, + ) + elif is_outlier_detector(estimator): + prediction_method = _check_response_method(estimator, response_method) + y_pred, pos_label = prediction_method(X), None + else: # estimator is a regressor + if response_method != "predict": + raise ValueError( + f"{estimator.__class__.__name__} should either be a classifier to be " + f"used with response_method={response_method} or the response_method " + "should be 'predict'. Got a regressor with response_method=" + f"{response_method} instead." + ) + prediction_method = estimator.predict + y_pred, pos_label = prediction_method(X), None + + if return_response_method_used: + return y_pred, pos_label, prediction_method.__name__ + return y_pred, pos_label + + +def _get_response_values_binary(estimator, X, response_method, pos_label=None): + """Compute the response values of a binary classifier. + + Parameters + ---------- + estimator : estimator instance + Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a binary classifier. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + response_method : {'auto', 'predict_proba', 'decision_function'} + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the target response. If set to 'auto', + :term:`predict_proba` is tried first and if it does not exist + :term:`decision_function` is tried next. + + pos_label : int, float, bool or str, default=None + The class considered as the positive class when computing + the metrics. By default, `estimators.classes_[1]` is + considered as the positive class. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Target scores calculated from the provided response_method + and pos_label. + + pos_label : int, float, bool or str + The class considered as the positive class when computing + the metrics. + """ + classification_error = "Expected 'estimator' to be a binary classifier." + + check_is_fitted(estimator) + if not is_classifier(estimator): + raise ValueError( + classification_error + f" Got {estimator.__class__.__name__} instead." + ) + elif len(estimator.classes_) != 2: + raise ValueError( + classification_error + f" Got {len(estimator.classes_)} classes instead." + ) + + if response_method == "auto": + response_method = ["predict_proba", "decision_function"] + + return _get_response_values( + estimator, + X, + response_method, + pos_label=pos_label, + ) diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.pxd b/venv/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2bd630fa4db6791823a3bb7769a4aefc438ed09e --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.pxd @@ -0,0 +1,104 @@ +# WARNING: Do not edit this file directly. +# It is automatically generated from 'sklearn/utils/_seq_dataset.pxd.tp'. +# Changes must be made there. + +"""Dataset abstractions for sequential data access.""" + +cimport numpy as cnp + +# SequentialDataset and its two concrete subclasses are (optionally randomized) +# iterators over the rows of a matrix X and corresponding target values y. + +#------------------------------------------------------------------------------ + +cdef class SequentialDataset64: + cdef int current_index + cdef int[::1] index + cdef int *index_data_ptr + cdef Py_ssize_t n_samples + cdef cnp.uint32_t seed + + cdef void shuffle(self, cnp.uint32_t seed) noexcept nogil + cdef int _get_next_index(self) noexcept nogil + cdef int _get_random_index(self) noexcept nogil + + cdef void _sample(self, double **x_data_ptr, int **x_ind_ptr, + int *nnz, double *y, double *sample_weight, + int current_index) noexcept nogil + cdef void next(self, double **x_data_ptr, int **x_ind_ptr, + int *nnz, double *y, double *sample_weight) noexcept nogil + cdef int random(self, double **x_data_ptr, int **x_ind_ptr, + int *nnz, double *y, double *sample_weight) noexcept nogil + + +cdef class ArrayDataset64(SequentialDataset64): + cdef const double[:, ::1] X + cdef const double[::1] Y + cdef const double[::1] sample_weights + cdef Py_ssize_t n_features + cdef cnp.npy_intp X_stride + cdef double *X_data_ptr + cdef double *Y_data_ptr + cdef const int[::1] feature_indices + cdef int *feature_indices_ptr + cdef double *sample_weight_data + + +cdef class CSRDataset64(SequentialDataset64): + cdef const double[::1] X_data + cdef const int[::1] X_indptr + cdef const int[::1] X_indices + cdef const double[::1] Y + cdef const double[::1] sample_weights + cdef double *X_data_ptr + cdef int *X_indptr_ptr + cdef int *X_indices_ptr + cdef double *Y_data_ptr + cdef double *sample_weight_data + +#------------------------------------------------------------------------------ + +cdef class SequentialDataset32: + cdef int current_index + cdef int[::1] index + cdef int *index_data_ptr + cdef Py_ssize_t n_samples + cdef cnp.uint32_t seed + + cdef void shuffle(self, cnp.uint32_t seed) noexcept nogil + cdef int _get_next_index(self) noexcept nogil + cdef int _get_random_index(self) noexcept nogil + + cdef void _sample(self, float **x_data_ptr, int **x_ind_ptr, + int *nnz, float *y, float *sample_weight, + int current_index) noexcept nogil + cdef void next(self, float **x_data_ptr, int **x_ind_ptr, + int *nnz, float *y, float *sample_weight) noexcept nogil + cdef int random(self, float **x_data_ptr, int **x_ind_ptr, + int *nnz, float *y, float *sample_weight) noexcept nogil + + +cdef class ArrayDataset32(SequentialDataset32): + cdef const float[:, ::1] X + cdef const float[::1] Y + cdef const float[::1] sample_weights + cdef Py_ssize_t n_features + cdef cnp.npy_intp X_stride + cdef float *X_data_ptr + cdef float *Y_data_ptr + cdef const int[::1] feature_indices + cdef int *feature_indices_ptr + cdef float *sample_weight_data + + +cdef class CSRDataset32(SequentialDataset32): + cdef const float[::1] X_data + cdef const int[::1] X_indptr + cdef const int[::1] X_indices + cdef const float[::1] Y + cdef const float[::1] sample_weights + cdef float *X_data_ptr + cdef int *X_indptr_ptr + cdef int *X_indices_ptr + cdef float *Y_data_ptr + cdef float *sample_weight_data diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_set_output.py b/venv/lib/python3.10/site-packages/sklearn/utils/_set_output.py new file mode 100644 index 0000000000000000000000000000000000000000..cf7364e11732056c1cb1987d9da2633ad80870e7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_set_output.py @@ -0,0 +1,441 @@ +import importlib +from functools import wraps +from typing import Protocol, runtime_checkable + +import numpy as np +from scipy.sparse import issparse + +from .._config import get_config +from ._available_if import available_if + + +def check_library_installed(library): + """Check library is installed.""" + try: + return importlib.import_module(library) + except ImportError as exc: + raise ImportError( + f"Setting output container to '{library}' requires {library} to be" + " installed" + ) from exc + + +def get_columns(columns): + if callable(columns): + try: + return columns() + except Exception: + return None + return columns + + +@runtime_checkable +class ContainerAdapterProtocol(Protocol): + container_lib: str + + def create_container(self, X_output, X_original, columns, inplace=False): + """Create container from `X_output` with additional metadata. + + Parameters + ---------- + X_output : {ndarray, dataframe} + Data to wrap. + + X_original : {ndarray, dataframe} + Original input dataframe. This is used to extract the metadata that should + be passed to `X_output`, e.g. pandas row index. + + columns : callable, ndarray, or None + The column names or a callable that returns the column names. The + callable is useful if the column names require some computation. If `None`, + then no columns are passed to the container's constructor. + + inplace : bool, default=False + Whether or not we intend to modify `X_output` in-place. However, it does + not guarantee that we return the same object if the in-place operation + is not possible. + + Returns + ------- + wrapped_output : container_type + `X_output` wrapped into the container type. + """ + + def is_supported_container(self, X): + """Return True if X is a supported container. + + Parameters + ---------- + Xs: container + Containers to be checked. + + Returns + ------- + is_supported_container : bool + True if X is a supported container. + """ + + def rename_columns(self, X, columns): + """Rename columns in `X`. + + Parameters + ---------- + X : container + Container which columns is updated. + + columns : ndarray of str + Columns to update the `X`'s columns with. + + Returns + ------- + updated_container : container + Container with new names. + """ + + def hstack(self, Xs): + """Stack containers horizontally (column-wise). + + Parameters + ---------- + Xs : list of containers + List of containers to stack. + + Returns + ------- + stacked_Xs : container + Stacked containers. + """ + + +class PandasAdapter: + container_lib = "pandas" + + def create_container(self, X_output, X_original, columns, inplace=True): + pd = check_library_installed("pandas") + columns = get_columns(columns) + + if not inplace or not isinstance(X_output, pd.DataFrame): + # In all these cases, we need to create a new DataFrame + + # Unfortunately, we cannot use `getattr(container, "index")` + # because `list` exposes an `index` attribute. + if isinstance(X_output, pd.DataFrame): + index = X_output.index + elif isinstance(X_original, pd.DataFrame): + index = X_original.index + else: + index = None + + # We don't pass columns here because it would intend columns selection + # instead of renaming. + X_output = pd.DataFrame(X_output, index=index, copy=not inplace) + + if columns is not None: + return self.rename_columns(X_output, columns) + return X_output + + def is_supported_container(self, X): + pd = check_library_installed("pandas") + return isinstance(X, pd.DataFrame) + + def rename_columns(self, X, columns): + # we cannot use `rename` since it takes a dictionary and at this stage we have + # potentially duplicate column names in `X` + X.columns = columns + return X + + def hstack(self, Xs): + pd = check_library_installed("pandas") + return pd.concat(Xs, axis=1) + + +class PolarsAdapter: + container_lib = "polars" + + def create_container(self, X_output, X_original, columns, inplace=True): + pl = check_library_installed("polars") + columns = get_columns(columns) + columns = columns.tolist() if isinstance(columns, np.ndarray) else columns + + if not inplace or not isinstance(X_output, pl.DataFrame): + # In all these cases, we need to create a new DataFrame + return pl.DataFrame(X_output, schema=columns, orient="row") + + if columns is not None: + return self.rename_columns(X_output, columns) + return X_output + + def is_supported_container(self, X): + pl = check_library_installed("polars") + return isinstance(X, pl.DataFrame) + + def rename_columns(self, X, columns): + # we cannot use `rename` since it takes a dictionary and at this stage we have + # potentially duplicate column names in `X` + X.columns = columns + return X + + def hstack(self, Xs): + pl = check_library_installed("polars") + return pl.concat(Xs, how="horizontal") + + +class ContainerAdaptersManager: + def __init__(self): + self.adapters = {} + + @property + def supported_outputs(self): + return {"default"} | set(self.adapters) + + def register(self, adapter): + self.adapters[adapter.container_lib] = adapter + + +ADAPTERS_MANAGER = ContainerAdaptersManager() +ADAPTERS_MANAGER.register(PandasAdapter()) +ADAPTERS_MANAGER.register(PolarsAdapter()) + + +def _get_container_adapter(method, estimator=None): + """Get container adapter.""" + dense_config = _get_output_config(method, estimator)["dense"] + try: + return ADAPTERS_MANAGER.adapters[dense_config] + except KeyError: + return None + + +def _get_output_config(method, estimator=None): + """Get output config based on estimator and global configuration. + + Parameters + ---------- + method : {"transform"} + Estimator's method for which the output container is looked up. + + estimator : estimator instance or None + Estimator to get the output configuration from. If `None`, check global + configuration is used. + + Returns + ------- + config : dict + Dictionary with keys: + + - "dense": specifies the dense container for `method`. This can be + `"default"` or `"pandas"`. + """ + est_sklearn_output_config = getattr(estimator, "_sklearn_output_config", {}) + if method in est_sklearn_output_config: + dense_config = est_sklearn_output_config[method] + else: + dense_config = get_config()[f"{method}_output"] + + supported_outputs = ADAPTERS_MANAGER.supported_outputs + if dense_config not in supported_outputs: + raise ValueError( + f"output config must be in {sorted(supported_outputs)}, got {dense_config}" + ) + + return {"dense": dense_config} + + +def _wrap_data_with_container(method, data_to_wrap, original_input, estimator): + """Wrap output with container based on an estimator's or global config. + + Parameters + ---------- + method : {"transform"} + Estimator's method to get container output for. + + data_to_wrap : {ndarray, dataframe} + Data to wrap with container. + + original_input : {ndarray, dataframe} + Original input of function. + + estimator : estimator instance + Estimator with to get the output configuration from. + + Returns + ------- + output : {ndarray, dataframe} + If the output config is "default" or the estimator is not configured + for wrapping return `data_to_wrap` unchanged. + If the output config is "pandas", return `data_to_wrap` as a pandas + DataFrame. + """ + output_config = _get_output_config(method, estimator) + + if output_config["dense"] == "default" or not _auto_wrap_is_configured(estimator): + return data_to_wrap + + dense_config = output_config["dense"] + if issparse(data_to_wrap): + raise ValueError( + "The transformer outputs a scipy sparse matrix. " + "Try to set the transformer output to a dense array or disable " + f"{dense_config.capitalize()} output with set_output(transform='default')." + ) + + adapter = ADAPTERS_MANAGER.adapters[dense_config] + return adapter.create_container( + data_to_wrap, + original_input, + columns=estimator.get_feature_names_out, + ) + + +def _wrap_method_output(f, method): + """Wrapper used by `_SetOutputMixin` to automatically wrap methods.""" + + @wraps(f) + def wrapped(self, X, *args, **kwargs): + data_to_wrap = f(self, X, *args, **kwargs) + if isinstance(data_to_wrap, tuple): + # only wrap the first output for cross decomposition + return_tuple = ( + _wrap_data_with_container(method, data_to_wrap[0], X, self), + *data_to_wrap[1:], + ) + # Support for namedtuples `_make` is a documented API for namedtuples: + # https://docs.python.org/3/library/collections.html#collections.somenamedtuple._make + if hasattr(type(data_to_wrap), "_make"): + return type(data_to_wrap)._make(return_tuple) + return return_tuple + + return _wrap_data_with_container(method, data_to_wrap, X, self) + + return wrapped + + +def _auto_wrap_is_configured(estimator): + """Return True if estimator is configured for auto-wrapping the transform method. + + `_SetOutputMixin` sets `_sklearn_auto_wrap_output_keys` to `set()` if auto wrapping + is manually disabled. + """ + auto_wrap_output_keys = getattr(estimator, "_sklearn_auto_wrap_output_keys", set()) + return ( + hasattr(estimator, "get_feature_names_out") + and "transform" in auto_wrap_output_keys + ) + + +class _SetOutputMixin: + """Mixin that dynamically wraps methods to return container based on config. + + Currently `_SetOutputMixin` wraps `transform` and `fit_transform` and configures + it based on `set_output` of the global configuration. + + `set_output` is only defined if `get_feature_names_out` is defined and + `auto_wrap_output_keys` is the default value. + """ + + def __init_subclass__(cls, auto_wrap_output_keys=("transform",), **kwargs): + super().__init_subclass__(**kwargs) + + # Dynamically wraps `transform` and `fit_transform` and configure it's + # output based on `set_output`. + if not ( + isinstance(auto_wrap_output_keys, tuple) or auto_wrap_output_keys is None + ): + raise ValueError("auto_wrap_output_keys must be None or a tuple of keys.") + + if auto_wrap_output_keys is None: + cls._sklearn_auto_wrap_output_keys = set() + return + + # Mapping from method to key in configurations + method_to_key = { + "transform": "transform", + "fit_transform": "transform", + } + cls._sklearn_auto_wrap_output_keys = set() + + for method, key in method_to_key.items(): + if not hasattr(cls, method) or key not in auto_wrap_output_keys: + continue + cls._sklearn_auto_wrap_output_keys.add(key) + + # Only wrap methods defined by cls itself + if method not in cls.__dict__: + continue + wrapped_method = _wrap_method_output(getattr(cls, method), key) + setattr(cls, method, wrapped_method) + + @available_if(_auto_wrap_is_configured) + def set_output(self, *, transform=None): + """Set output container. + + See :ref:`sphx_glr_auto_examples_miscellaneous_plot_set_output.py` + for an example on how to use the API. + + Parameters + ---------- + transform : {"default", "pandas"}, default=None + Configure output of `transform` and `fit_transform`. + + - `"default"`: Default output format of a transformer + - `"pandas"`: DataFrame output + - `"polars"`: Polars output + - `None`: Transform configuration is unchanged + + .. versionadded:: 1.4 + `"polars"` option was added. + + Returns + ------- + self : estimator instance + Estimator instance. + """ + if transform is None: + return self + + if not hasattr(self, "_sklearn_output_config"): + self._sklearn_output_config = {} + + self._sklearn_output_config["transform"] = transform + return self + + +def _safe_set_output(estimator, *, transform=None): + """Safely call estimator.set_output and error if it not available. + + This is used by meta-estimators to set the output for child estimators. + + Parameters + ---------- + estimator : estimator instance + Estimator instance. + + transform : {"default", "pandas"}, default=None + Configure output of the following estimator's methods: + + - `"transform"` + - `"fit_transform"` + + If `None`, this operation is a no-op. + + Returns + ------- + estimator : estimator instance + Estimator instance. + """ + set_output_for_transform = ( + hasattr(estimator, "transform") + or hasattr(estimator, "fit_transform") + and transform is not None + ) + if not set_output_for_transform: + # If estimator can not transform, then `set_output` does not need to be + # called. + return + + if not hasattr(estimator, "set_output"): + raise ValueError( + f"Unable to configure output for {estimator} because `set_output` " + "is not available." + ) + return estimator.set_output(transform=transform) diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_sorting.pxd b/venv/lib/python3.10/site-packages/sklearn/utils/_sorting.pxd new file mode 100644 index 0000000000000000000000000000000000000000..51f21afd4d3e401bfe4021ff308cd2d5c36e5c4b --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_sorting.pxd @@ -0,0 +1,9 @@ +from ._typedefs cimport intp_t + +from cython cimport floating + +cdef int simultaneous_sort( + floating *dist, + intp_t *idx, + intp_t size, +) noexcept nogil diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_tags.py b/venv/lib/python3.10/site-packages/sklearn/utils/_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..c8f6ffb651a0de206ae078c8628b0bf03c82392a --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_tags.py @@ -0,0 +1,68 @@ +import numpy as np + +_DEFAULT_TAGS = { + "array_api_support": False, + "non_deterministic": False, + "requires_positive_X": False, + "requires_positive_y": False, + "X_types": ["2darray"], + "poor_score": False, + "no_validation": False, + "multioutput": False, + "allow_nan": False, + "stateless": False, + "multilabel": False, + "_skip_test": False, + "_xfail_checks": False, + "multioutput_only": False, + "binary_only": False, + "requires_fit": True, + "preserves_dtype": [np.float64], + "requires_y": False, + "pairwise": False, +} + + +def _safe_tags(estimator, key=None): + """Safely get estimator tags. + + :class:`~sklearn.BaseEstimator` provides the estimator tags machinery. + However, if an estimator does not inherit from this base class, we should + fall-back to the default tags. + + For scikit-learn built-in estimators, we should still rely on + `self._get_tags()`. `_safe_tags(est)` should be used when we are not sure + where `est` comes from: typically `_safe_tags(self.base_estimator)` where + `self` is a meta-estimator, or in the common checks. + + Parameters + ---------- + estimator : estimator object + The estimator from which to get the tag. + + key : str, default=None + Tag name to get. By default (`None`), all tags are returned. + + Returns + ------- + tags : dict or tag value + The estimator tags. A single value is returned if `key` is not None. + """ + if hasattr(estimator, "_get_tags"): + tags_provider = "_get_tags()" + tags = estimator._get_tags() + elif hasattr(estimator, "_more_tags"): + tags_provider = "_more_tags()" + tags = {**_DEFAULT_TAGS, **estimator._more_tags()} + else: + tags_provider = "_DEFAULT_TAGS" + tags = _DEFAULT_TAGS + + if key is not None: + if key not in tags: + raise ValueError( + f"The key {key} is not defined in {tags_provider} for the " + f"class {estimator.__class__.__name__}." + ) + return tags[key] + return tags diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_testing.py b/venv/lib/python3.10/site-packages/sklearn/utils/_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..42011e3f719168de01b15275dbd6b91c15c1d14e --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_testing.py @@ -0,0 +1,1169 @@ +"""Testing utilities.""" + +# Copyright (c) 2011, 2012 +# Authors: Pietro Berkes, +# Andreas Muller +# Mathieu Blondel +# Olivier Grisel +# Arnaud Joly +# Denis Engemann +# Giorgio Patrini +# Thierry Guillemot +# License: BSD 3 clause +import atexit +import contextlib +import functools +import importlib +import inspect +import os +import os.path as op +import re +import shutil +import sys +import tempfile +import unittest +import warnings +from collections.abc import Iterable +from dataclasses import dataclass +from functools import wraps +from inspect import signature +from subprocess import STDOUT, CalledProcessError, TimeoutExpired, check_output +from unittest import TestCase + +import joblib +import numpy as np +import scipy as sp +from numpy.testing import assert_allclose as np_assert_allclose +from numpy.testing import ( + assert_almost_equal, + assert_approx_equal, + assert_array_almost_equal, + assert_array_equal, + assert_array_less, + assert_no_warnings, +) + +import sklearn +from sklearn.utils import ( + _IS_32BIT, + IS_PYPY, + _in_unstable_openblas_configuration, +) +from sklearn.utils._array_api import _check_array_api_dispatch +from sklearn.utils.fixes import VisibleDeprecationWarning, parse_version, sp_version +from sklearn.utils.multiclass import check_classification_targets +from sklearn.utils.validation import ( + check_array, + check_is_fitted, + check_X_y, +) + +__all__ = [ + "assert_raises", + "assert_raises_regexp", + "assert_array_equal", + "assert_almost_equal", + "assert_array_almost_equal", + "assert_array_less", + "assert_approx_equal", + "assert_allclose", + "assert_run_python_script_without_output", + "assert_no_warnings", + "SkipTest", +] + +_dummy = TestCase("__init__") +assert_raises = _dummy.assertRaises +SkipTest = unittest.case.SkipTest +assert_dict_equal = _dummy.assertDictEqual + +assert_raises_regex = _dummy.assertRaisesRegex +# assert_raises_regexp is deprecated in Python 3.4 in favor of +# assert_raises_regex but lets keep the backward compat in scikit-learn with +# the old name for now +assert_raises_regexp = assert_raises_regex + + +def ignore_warnings(obj=None, category=Warning): + """Context manager and decorator to ignore warnings. + + Note: Using this (in both variants) will clear all warnings + from all python modules loaded. In case you need to test + cross-module-warning-logging, this is not your tool of choice. + + Parameters + ---------- + obj : callable, default=None + callable where you want to ignore the warnings. + category : warning class, default=Warning + The category to filter. If Warning, all categories will be muted. + + Examples + -------- + >>> import warnings + >>> from sklearn.utils._testing import ignore_warnings + >>> with ignore_warnings(): + ... warnings.warn('buhuhuhu') + + >>> def nasty_warn(): + ... warnings.warn('buhuhuhu') + ... print(42) + + >>> ignore_warnings(nasty_warn)() + 42 + """ + if isinstance(obj, type) and issubclass(obj, Warning): + # Avoid common pitfall of passing category as the first positional + # argument which result in the test not being run + warning_name = obj.__name__ + raise ValueError( + "'obj' should be a callable where you want to ignore warnings. " + "You passed a warning class instead: 'obj={warning_name}'. " + "If you want to pass a warning class to ignore_warnings, " + "you should use 'category={warning_name}'".format(warning_name=warning_name) + ) + elif callable(obj): + return _IgnoreWarnings(category=category)(obj) + else: + return _IgnoreWarnings(category=category) + + +class _IgnoreWarnings: + """Improved and simplified Python warnings context manager and decorator. + + This class allows the user to ignore the warnings raised by a function. + Copied from Python 2.7.5 and modified as required. + + Parameters + ---------- + category : tuple of warning class, default=Warning + The category to filter. By default, all the categories will be muted. + + """ + + def __init__(self, category): + self._record = True + self._module = sys.modules["warnings"] + self._entered = False + self.log = [] + self.category = category + + def __call__(self, fn): + """Decorator to catch and hide warnings without visual nesting.""" + + @wraps(fn) + def wrapper(*args, **kwargs): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", self.category) + return fn(*args, **kwargs) + + return wrapper + + def __repr__(self): + args = [] + if self._record: + args.append("record=True") + if self._module is not sys.modules["warnings"]: + args.append("module=%r" % self._module) + name = type(self).__name__ + return "%s(%s)" % (name, ", ".join(args)) + + def __enter__(self): + if self._entered: + raise RuntimeError("Cannot enter %r twice" % self) + self._entered = True + self._filters = self._module.filters + self._module.filters = self._filters[:] + self._showwarning = self._module.showwarning + warnings.simplefilter("ignore", self.category) + + def __exit__(self, *exc_info): + if not self._entered: + raise RuntimeError("Cannot exit %r without entering first" % self) + self._module.filters = self._filters + self._module.showwarning = self._showwarning + self.log[:] = [] + + +def assert_raise_message(exceptions, message, function, *args, **kwargs): + """Helper function to test the message raised in an exception. + + Given an exception, a callable to raise the exception, and + a message string, tests that the correct exception is raised and + that the message is a substring of the error thrown. Used to test + that the specific message thrown during an exception is correct. + + Parameters + ---------- + exceptions : exception or tuple of exception + An Exception object. + + message : str + The error message or a substring of the error message. + + function : callable + Callable object to raise error. + + *args : the positional arguments to `function`. + + **kwargs : the keyword arguments to `function`. + """ + try: + function(*args, **kwargs) + except exceptions as e: + error_message = str(e) + if message not in error_message: + raise AssertionError( + "Error message does not include the expected" + " string: %r. Observed error message: %r" % (message, error_message) + ) + else: + # concatenate exception names + if isinstance(exceptions, tuple): + names = " or ".join(e.__name__ for e in exceptions) + else: + names = exceptions.__name__ + + raise AssertionError("%s not raised by %s" % (names, function.__name__)) + + +def assert_allclose( + actual, desired, rtol=None, atol=0.0, equal_nan=True, err_msg="", verbose=True +): + """dtype-aware variant of numpy.testing.assert_allclose + + This variant introspects the least precise floating point dtype + in the input argument and automatically sets the relative tolerance + parameter to 1e-4 float32 and use 1e-7 otherwise (typically float64 + in scikit-learn). + + `atol` is always left to 0. by default. It should be adjusted manually + to an assertion-specific value in case there are null values expected + in `desired`. + + The aggregate tolerance is `atol + rtol * abs(desired)`. + + Parameters + ---------- + actual : array_like + Array obtained. + desired : array_like + Array desired. + rtol : float, optional, default=None + Relative tolerance. + If None, it is set based on the provided arrays' dtypes. + atol : float, optional, default=0. + Absolute tolerance. + equal_nan : bool, optional, default=True + If True, NaNs will compare equal. + err_msg : str, optional, default='' + The error message to be printed in case of failure. + verbose : bool, optional, default=True + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired are not equal up to specified precision. + + See Also + -------- + numpy.testing.assert_allclose + + Examples + -------- + >>> import numpy as np + >>> from sklearn.utils._testing import assert_allclose + >>> x = [1e-5, 1e-3, 1e-1] + >>> y = np.arccos(np.cos(x)) + >>> assert_allclose(x, y, rtol=1e-5, atol=0) + >>> a = np.full(shape=10, fill_value=1e-5, dtype=np.float32) + >>> assert_allclose(a, 1e-5) + """ + dtypes = [] + + actual, desired = np.asanyarray(actual), np.asanyarray(desired) + dtypes = [actual.dtype, desired.dtype] + + if rtol is None: + rtols = [1e-4 if dtype == np.float32 else 1e-7 for dtype in dtypes] + rtol = max(rtols) + + np_assert_allclose( + actual, + desired, + rtol=rtol, + atol=atol, + equal_nan=equal_nan, + err_msg=err_msg, + verbose=verbose, + ) + + +def assert_allclose_dense_sparse(x, y, rtol=1e-07, atol=1e-9, err_msg=""): + """Assert allclose for sparse and dense data. + + Both x and y need to be either sparse or dense, they + can't be mixed. + + Parameters + ---------- + x : {array-like, sparse matrix} + First array to compare. + + y : {array-like, sparse matrix} + Second array to compare. + + rtol : float, default=1e-07 + relative tolerance; see numpy.allclose. + + atol : float, default=1e-9 + absolute tolerance; see numpy.allclose. Note that the default here is + more tolerant than the default for numpy.testing.assert_allclose, where + atol=0. + + err_msg : str, default='' + Error message to raise. + """ + if sp.sparse.issparse(x) and sp.sparse.issparse(y): + x = x.tocsr() + y = y.tocsr() + x.sum_duplicates() + y.sum_duplicates() + assert_array_equal(x.indices, y.indices, err_msg=err_msg) + assert_array_equal(x.indptr, y.indptr, err_msg=err_msg) + assert_allclose(x.data, y.data, rtol=rtol, atol=atol, err_msg=err_msg) + elif not sp.sparse.issparse(x) and not sp.sparse.issparse(y): + # both dense + assert_allclose(x, y, rtol=rtol, atol=atol, err_msg=err_msg) + else: + raise ValueError( + "Can only compare two sparse matrices, not a sparse matrix and an array." + ) + + +def set_random_state(estimator, random_state=0): + """Set random state of an estimator if it has the `random_state` param. + + Parameters + ---------- + estimator : object + The estimator. + random_state : int, RandomState instance or None, default=0 + Pseudo random number generator state. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + """ + if "random_state" in estimator.get_params(): + estimator.set_params(random_state=random_state) + + +try: + _check_array_api_dispatch(True) + ARRAY_API_COMPAT_FUNCTIONAL = True +except ImportError: + ARRAY_API_COMPAT_FUNCTIONAL = False + +try: + import pytest + + skip_if_32bit = pytest.mark.skipif(_IS_32BIT, reason="skipped on 32bit platforms") + fails_if_pypy = pytest.mark.xfail(IS_PYPY, reason="not compatible with PyPy") + fails_if_unstable_openblas = pytest.mark.xfail( + _in_unstable_openblas_configuration(), + reason="OpenBLAS is unstable for this configuration", + ) + skip_if_no_parallel = pytest.mark.skipif( + not joblib.parallel.mp, reason="joblib is in serial mode" + ) + skip_if_array_api_compat_not_configured = pytest.mark.skipif( + not ARRAY_API_COMPAT_FUNCTIONAL, + reason="requires array_api_compat installed and a new enough version of NumPy", + ) + + # Decorator for tests involving both BLAS calls and multiprocessing. + # + # Under POSIX (e.g. Linux or OSX), using multiprocessing in conjunction + # with some implementation of BLAS (or other libraries that manage an + # internal posix thread pool) can cause a crash or a freeze of the Python + # process. + # + # In practice all known packaged distributions (from Linux distros or + # Anaconda) of BLAS under Linux seems to be safe. So we this problem seems + # to only impact OSX users. + # + # This wrapper makes it possible to skip tests that can possibly cause + # this crash under OS X with. + # + # Under Python 3.4+ it is possible to use the `forkserver` start method + # for multiprocessing to avoid this issue. However it can cause pickling + # errors on interactively defined functions. It therefore not enabled by + # default. + + if_safe_multiprocessing_with_blas = pytest.mark.skipif( + sys.platform == "darwin", reason="Possible multi-process bug with some BLAS" + ) +except ImportError: + pass + + +def check_skip_network(): + if int(os.environ.get("SKLEARN_SKIP_NETWORK_TESTS", 0)): + raise SkipTest("Text tutorial requires large dataset download") + + +def _delete_folder(folder_path, warn=False): + """Utility function to cleanup a temporary folder if still existing. + + Copy from joblib.pool (for independence). + """ + try: + if os.path.exists(folder_path): + # This can fail under windows, + # but will succeed when called by atexit + shutil.rmtree(folder_path) + except OSError: + if warn: + warnings.warn("Could not delete temporary folder %s" % folder_path) + + +class TempMemmap: + """ + Parameters + ---------- + data + mmap_mode : str, default='r' + """ + + def __init__(self, data, mmap_mode="r"): + self.mmap_mode = mmap_mode + self.data = data + + def __enter__(self): + data_read_only, self.temp_folder = create_memmap_backed_data( + self.data, mmap_mode=self.mmap_mode, return_folder=True + ) + return data_read_only + + def __exit__(self, exc_type, exc_val, exc_tb): + _delete_folder(self.temp_folder) + + +def create_memmap_backed_data(data, mmap_mode="r", return_folder=False): + """ + Parameters + ---------- + data + mmap_mode : str, default='r' + return_folder : bool, default=False + """ + temp_folder = tempfile.mkdtemp(prefix="sklearn_testing_") + atexit.register(functools.partial(_delete_folder, temp_folder, warn=True)) + filename = op.join(temp_folder, "data.pkl") + joblib.dump(data, filename) + memmap_backed_data = joblib.load(filename, mmap_mode=mmap_mode) + result = ( + memmap_backed_data if not return_folder else (memmap_backed_data, temp_folder) + ) + return result + + +# Utils to test docstrings + + +def _get_args(function, varargs=False): + """Helper to get function arguments.""" + + try: + params = signature(function).parameters + except ValueError: + # Error on builtin C function + return [] + args = [ + key + for key, param in params.items() + if param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD) + ] + if varargs: + varargs = [ + param.name + for param in params.values() + if param.kind == param.VAR_POSITIONAL + ] + if len(varargs) == 0: + varargs = None + return args, varargs + else: + return args + + +def _get_func_name(func): + """Get function full name. + + Parameters + ---------- + func : callable + The function object. + + Returns + ------- + name : str + The function name. + """ + parts = [] + module = inspect.getmodule(func) + if module: + parts.append(module.__name__) + + qualname = func.__qualname__ + if qualname != func.__name__: + parts.append(qualname[: qualname.find(".")]) + + parts.append(func.__name__) + return ".".join(parts) + + +def check_docstring_parameters(func, doc=None, ignore=None): + """Helper to check docstring. + + Parameters + ---------- + func : callable + The function object to test. + doc : str, default=None + Docstring if it is passed manually to the test. + ignore : list, default=None + Parameters to ignore. + + Returns + ------- + incorrect : list + A list of string describing the incorrect results. + """ + from numpydoc import docscrape + + incorrect = [] + ignore = [] if ignore is None else ignore + + func_name = _get_func_name(func) + if not func_name.startswith("sklearn.") or func_name.startswith( + "sklearn.externals" + ): + return incorrect + # Don't check docstring for property-functions + if inspect.isdatadescriptor(func): + return incorrect + # Don't check docstring for setup / teardown pytest functions + if func_name.split(".")[-1] in ("setup_module", "teardown_module"): + return incorrect + # Dont check estimator_checks module + if func_name.split(".")[2] == "estimator_checks": + return incorrect + # Get the arguments from the function signature + param_signature = list(filter(lambda x: x not in ignore, _get_args(func))) + # drop self + if len(param_signature) > 0 and param_signature[0] == "self": + param_signature.remove("self") + + # Analyze function's docstring + if doc is None: + records = [] + with warnings.catch_warnings(record=True): + warnings.simplefilter("error", UserWarning) + try: + doc = docscrape.FunctionDoc(func) + except UserWarning as exp: + if "potentially wrong underline length" in str(exp): + # Catch warning raised as of numpydoc 1.2 when + # the underline length for a section of a docstring + # is not consistent. + message = str(exp).split("\n")[:3] + incorrect += [f"In function: {func_name}"] + message + return incorrect + records.append(str(exp)) + except Exception as exp: + incorrect += [func_name + " parsing error: " + str(exp)] + return incorrect + if len(records): + raise RuntimeError("Error for %s:\n%s" % (func_name, records[0])) + + param_docs = [] + for name, type_definition, param_doc in doc["Parameters"]: + # Type hints are empty only if parameter name ended with : + if not type_definition.strip(): + if ":" in name and name[: name.index(":")][-1:].strip(): + incorrect += [ + func_name + + " There was no space between the param name and colon (%r)" % name + ] + elif name.rstrip().endswith(":"): + incorrect += [ + func_name + + " Parameter %r has an empty type spec. Remove the colon" + % (name.lstrip()) + ] + + # Create a list of parameters to compare with the parameters gotten + # from the func signature + if "*" not in name: + param_docs.append(name.split(":")[0].strip("` ")) + + # If one of the docstring's parameters had an error then return that + # incorrect message + if len(incorrect) > 0: + return incorrect + + # Remove the parameters that should be ignored from list + param_docs = list(filter(lambda x: x not in ignore, param_docs)) + + # The following is derived from pytest, Copyright (c) 2004-2017 Holger + # Krekel and others, Licensed under MIT License. See + # https://github.com/pytest-dev/pytest + + message = [] + for i in range(min(len(param_docs), len(param_signature))): + if param_signature[i] != param_docs[i]: + message += [ + "There's a parameter name mismatch in function" + " docstring w.r.t. function signature, at index %s" + " diff: %r != %r" % (i, param_signature[i], param_docs[i]) + ] + break + if len(param_signature) > len(param_docs): + message += [ + "Parameters in function docstring have less items w.r.t." + " function signature, first missing item: %s" + % param_signature[len(param_docs)] + ] + + elif len(param_signature) < len(param_docs): + message += [ + "Parameters in function docstring have more items w.r.t." + " function signature, first extra item: %s" + % param_docs[len(param_signature)] + ] + + # If there wasn't any difference in the parameters themselves between + # docstring and signature including having the same length then return + # empty list + if len(message) == 0: + return [] + + import difflib + import pprint + + param_docs_formatted = pprint.pformat(param_docs).splitlines() + param_signature_formatted = pprint.pformat(param_signature).splitlines() + + message += ["Full diff:"] + + message.extend( + line.strip() + for line in difflib.ndiff(param_signature_formatted, param_docs_formatted) + ) + + incorrect.extend(message) + + # Prepend function name + incorrect = ["In function: " + func_name] + incorrect + + return incorrect + + +def assert_run_python_script_without_output(source_code, pattern=".+", timeout=60): + """Utility to check assertions in an independent Python subprocess. + + The script provided in the source code should return 0 and the stdtout + + stderr should not match the pattern `pattern`. + + This is a port from cloudpickle https://github.com/cloudpipe/cloudpickle + + Parameters + ---------- + source_code : str + The Python source code to execute. + pattern : str + Pattern that the stdout + stderr should not match. By default, unless + stdout + stderr are both empty, an error will be raised. + timeout : int, default=60 + Time in seconds before timeout. + """ + fd, source_file = tempfile.mkstemp(suffix="_src_test_sklearn.py") + os.close(fd) + try: + with open(source_file, "wb") as f: + f.write(source_code.encode("utf-8")) + cmd = [sys.executable, source_file] + cwd = op.normpath(op.join(op.dirname(sklearn.__file__), "..")) + env = os.environ.copy() + try: + env["PYTHONPATH"] = os.pathsep.join([cwd, env["PYTHONPATH"]]) + except KeyError: + env["PYTHONPATH"] = cwd + kwargs = {"cwd": cwd, "stderr": STDOUT, "env": env} + # If coverage is running, pass the config file to the subprocess + coverage_rc = os.environ.get("COVERAGE_PROCESS_START") + if coverage_rc: + kwargs["env"]["COVERAGE_PROCESS_START"] = coverage_rc + + kwargs["timeout"] = timeout + try: + try: + out = check_output(cmd, **kwargs) + except CalledProcessError as e: + raise RuntimeError( + "script errored with output:\n%s" % e.output.decode("utf-8") + ) + + out = out.decode("utf-8") + if re.search(pattern, out): + if pattern == ".+": + expectation = "Expected no output" + else: + expectation = f"The output was not supposed to match {pattern!r}" + + message = f"{expectation}, got the following output instead: {out!r}" + raise AssertionError(message) + except TimeoutExpired as e: + raise RuntimeError( + "script timeout, output so far:\n%s" % e.output.decode("utf-8") + ) + finally: + os.unlink(source_file) + + +def _convert_container( + container, + constructor_name, + columns_name=None, + dtype=None, + minversion=None, + categorical_feature_names=None, +): + """Convert a given container to a specific array-like with a dtype. + + Parameters + ---------- + container : array-like + The container to convert. + constructor_name : {"list", "tuple", "array", "sparse", "dataframe", \ + "series", "index", "slice", "sparse_csr", "sparse_csc"} + The type of the returned container. + columns_name : index or array-like, default=None + For pandas container supporting `columns_names`, it will affect + specific names. + dtype : dtype, default=None + Force the dtype of the container. Does not apply to `"slice"` + container. + minversion : str, default=None + Minimum version for package to install. + categorical_feature_names : list of str, default=None + List of column names to cast to categorical dtype. + + Returns + ------- + converted_container + """ + if constructor_name == "list": + if dtype is None: + return list(container) + else: + return np.asarray(container, dtype=dtype).tolist() + elif constructor_name == "tuple": + if dtype is None: + return tuple(container) + else: + return tuple(np.asarray(container, dtype=dtype).tolist()) + elif constructor_name == "array": + return np.asarray(container, dtype=dtype) + elif constructor_name in ("pandas", "dataframe"): + pd = pytest.importorskip("pandas", minversion=minversion) + result = pd.DataFrame(container, columns=columns_name, dtype=dtype, copy=False) + if categorical_feature_names is not None: + for col_name in categorical_feature_names: + result[col_name] = result[col_name].astype("category") + return result + elif constructor_name == "pyarrow": + pa = pytest.importorskip("pyarrow", minversion=minversion) + array = np.asarray(container) + if columns_name is None: + columns_name = [f"col{i}" for i in range(array.shape[1])] + data = {name: array[:, i] for i, name in enumerate(columns_name)} + result = pa.Table.from_pydict(data) + if categorical_feature_names is not None: + for col_idx, col_name in enumerate(result.column_names): + if col_name in categorical_feature_names: + result = result.set_column( + col_idx, col_name, result.column(col_name).dictionary_encode() + ) + return result + elif constructor_name == "polars": + pl = pytest.importorskip("polars", minversion=minversion) + result = pl.DataFrame(container, schema=columns_name, orient="row") + if categorical_feature_names is not None: + for col_name in categorical_feature_names: + result = result.with_columns(pl.col(col_name).cast(pl.Categorical)) + return result + elif constructor_name == "series": + pd = pytest.importorskip("pandas", minversion=minversion) + return pd.Series(container, dtype=dtype) + elif constructor_name == "index": + pd = pytest.importorskip("pandas", minversion=minversion) + return pd.Index(container, dtype=dtype) + elif constructor_name == "slice": + return slice(container[0], container[1]) + elif "sparse" in constructor_name: + if not sp.sparse.issparse(container): + # For scipy >= 1.13, sparse array constructed from 1d array may be + # 1d or raise an exception. To avoid this, we make sure that the + # input container is 2d. For more details, see + # https://github.com/scipy/scipy/pull/18530#issuecomment-1878005149 + container = np.atleast_2d(container) + + if "array" in constructor_name and sp_version < parse_version("1.8"): + raise ValueError( + f"{constructor_name} is only available with scipy>=1.8.0, got " + f"{sp_version}" + ) + if constructor_name in ("sparse", "sparse_csr"): + # sparse and sparse_csr are equivalent for legacy reasons + return sp.sparse.csr_matrix(container, dtype=dtype) + elif constructor_name == "sparse_csr_array": + return sp.sparse.csr_array(container, dtype=dtype) + elif constructor_name == "sparse_csc": + return sp.sparse.csc_matrix(container, dtype=dtype) + elif constructor_name == "sparse_csc_array": + return sp.sparse.csc_array(container, dtype=dtype) + + +def raises(expected_exc_type, match=None, may_pass=False, err_msg=None): + """Context manager to ensure exceptions are raised within a code block. + + This is similar to and inspired from pytest.raises, but supports a few + other cases. + + This is only intended to be used in estimator_checks.py where we don't + want to use pytest. In the rest of the code base, just use pytest.raises + instead. + + Parameters + ---------- + excepted_exc_type : Exception or list of Exception + The exception that should be raised by the block. If a list, the block + should raise one of the exceptions. + match : str or list of str, default=None + A regex that the exception message should match. If a list, one of + the entries must match. If None, match isn't enforced. + may_pass : bool, default=False + If True, the block is allowed to not raise an exception. Useful in + cases where some estimators may support a feature but others must + fail with an appropriate error message. By default, the context + manager will raise an exception if the block does not raise an + exception. + err_msg : str, default=None + If the context manager fails (e.g. the block fails to raise the + proper exception, or fails to match), then an AssertionError is + raised with this message. By default, an AssertionError is raised + with a default error message (depends on the kind of failure). Use + this to indicate how users should fix their estimators to pass the + checks. + + Attributes + ---------- + raised_and_matched : bool + True if an exception was raised and a match was found, False otherwise. + """ + return _Raises(expected_exc_type, match, may_pass, err_msg) + + +class _Raises(contextlib.AbstractContextManager): + # see raises() for parameters + def __init__(self, expected_exc_type, match, may_pass, err_msg): + self.expected_exc_types = ( + expected_exc_type + if isinstance(expected_exc_type, Iterable) + else [expected_exc_type] + ) + self.matches = [match] if isinstance(match, str) else match + self.may_pass = may_pass + self.err_msg = err_msg + self.raised_and_matched = False + + def __exit__(self, exc_type, exc_value, _): + # see + # https://docs.python.org/2.5/whatsnew/pep-343.html#SECTION000910000000000000000 + + if exc_type is None: # No exception was raised in the block + if self.may_pass: + return True # CM is happy + else: + err_msg = self.err_msg or f"Did not raise: {self.expected_exc_types}" + raise AssertionError(err_msg) + + if not any( + issubclass(exc_type, expected_type) + for expected_type in self.expected_exc_types + ): + if self.err_msg is not None: + raise AssertionError(self.err_msg) from exc_value + else: + return False # will re-raise the original exception + + if self.matches is not None: + err_msg = self.err_msg or ( + "The error message should contain one of the following " + "patterns:\n{}\nGot {}".format("\n".join(self.matches), str(exc_value)) + ) + if not any(re.search(match, str(exc_value)) for match in self.matches): + raise AssertionError(err_msg) from exc_value + self.raised_and_matched = True + + return True + + +class MinimalClassifier: + """Minimal classifier implementation with inheriting from BaseEstimator. + + This estimator should be tested with: + + * `check_estimator` in `test_estimator_checks.py`; + * within a `Pipeline` in `test_pipeline.py`; + * within a `SearchCV` in `test_search.py`. + """ + + _estimator_type = "classifier" + + def __init__(self, param=None): + self.param = param + + def get_params(self, deep=True): + return {"param": self.param} + + def set_params(self, **params): + for key, value in params.items(): + setattr(self, key, value) + return self + + def fit(self, X, y): + X, y = check_X_y(X, y) + check_classification_targets(y) + self.classes_, counts = np.unique(y, return_counts=True) + self._most_frequent_class_idx = counts.argmax() + return self + + def predict_proba(self, X): + check_is_fitted(self) + X = check_array(X) + proba_shape = (X.shape[0], self.classes_.size) + y_proba = np.zeros(shape=proba_shape, dtype=np.float64) + y_proba[:, self._most_frequent_class_idx] = 1.0 + return y_proba + + def predict(self, X): + y_proba = self.predict_proba(X) + y_pred = y_proba.argmax(axis=1) + return self.classes_[y_pred] + + def score(self, X, y): + from sklearn.metrics import accuracy_score + + return accuracy_score(y, self.predict(X)) + + +class MinimalRegressor: + """Minimal regressor implementation with inheriting from BaseEstimator. + + This estimator should be tested with: + + * `check_estimator` in `test_estimator_checks.py`; + * within a `Pipeline` in `test_pipeline.py`; + * within a `SearchCV` in `test_search.py`. + """ + + _estimator_type = "regressor" + + def __init__(self, param=None): + self.param = param + + def get_params(self, deep=True): + return {"param": self.param} + + def set_params(self, **params): + for key, value in params.items(): + setattr(self, key, value) + return self + + def fit(self, X, y): + X, y = check_X_y(X, y) + self.is_fitted_ = True + self._mean = np.mean(y) + return self + + def predict(self, X): + check_is_fitted(self) + X = check_array(X) + return np.ones(shape=(X.shape[0],)) * self._mean + + def score(self, X, y): + from sklearn.metrics import r2_score + + return r2_score(y, self.predict(X)) + + +class MinimalTransformer: + """Minimal transformer implementation with inheriting from + BaseEstimator. + + This estimator should be tested with: + + * `check_estimator` in `test_estimator_checks.py`; + * within a `Pipeline` in `test_pipeline.py`; + * within a `SearchCV` in `test_search.py`. + """ + + def __init__(self, param=None): + self.param = param + + def get_params(self, deep=True): + return {"param": self.param} + + def set_params(self, **params): + for key, value in params.items(): + setattr(self, key, value) + return self + + def fit(self, X, y=None): + check_array(X) + self.is_fitted_ = True + return self + + def transform(self, X, y=None): + check_is_fitted(self) + X = check_array(X) + return X + + def fit_transform(self, X, y=None): + return self.fit(X, y).transform(X, y) + + +def _array_api_for_tests(array_namespace, device): + try: + if array_namespace == "numpy.array_api": + # FIXME: once it is not experimental anymore + with ignore_warnings(category=UserWarning): + # UserWarning: numpy.array_api submodule is still experimental. + array_mod = importlib.import_module(array_namespace) + else: + array_mod = importlib.import_module(array_namespace) + except ModuleNotFoundError: + raise SkipTest( + f"{array_namespace} is not installed: not checking array_api input" + ) + try: + import array_api_compat # noqa + except ImportError: + raise SkipTest( + "array_api_compat is not installed: not checking array_api input" + ) + + # First create an array using the chosen array module and then get the + # corresponding (compatibility wrapped) array namespace based on it. + # This is because `cupy` is not the same as the compatibility wrapped + # namespace of a CuPy array. + xp = array_api_compat.get_namespace(array_mod.asarray(1)) + if ( + array_namespace == "torch" + and device == "cuda" + and not xp.backends.cuda.is_built() + ): + raise SkipTest("PyTorch test requires cuda, which is not available") + elif array_namespace == "torch" and device == "mps": + if os.getenv("PYTORCH_ENABLE_MPS_FALLBACK") != "1": + # For now we need PYTORCH_ENABLE_MPS_FALLBACK=1 for all estimators to work + # when using the MPS device. + raise SkipTest( + "Skipping MPS device test because PYTORCH_ENABLE_MPS_FALLBACK is not " + "set." + ) + if not xp.backends.mps.is_built(): + raise SkipTest( + "MPS is not available because the current PyTorch install was not " + "built with MPS enabled." + ) + elif array_namespace in {"cupy", "cupy.array_api"}: # pragma: nocover + import cupy + + if cupy.cuda.runtime.getDeviceCount() == 0: + raise SkipTest("CuPy test requires cuda, which is not available") + return xp + + +def _get_warnings_filters_info_list(): + @dataclass + class WarningInfo: + action: "warnings._ActionKind" + message: str = "" + category: type[Warning] = Warning + + def to_filterwarning_str(self): + if self.category.__module__ == "builtins": + category = self.category.__name__ + else: + category = f"{self.category.__module__}.{self.category.__name__}" + + return f"{self.action}:{self.message}:{category}" + + return [ + WarningInfo("error", category=DeprecationWarning), + WarningInfo("error", category=FutureWarning), + WarningInfo("error", category=VisibleDeprecationWarning), + # TODO: remove when pyamg > 5.0.1 + # Avoid a deprecation warning due pkg_resources usage in pyamg. + WarningInfo( + "ignore", + message="pkg_resources is deprecated as an API", + category=DeprecationWarning, + ), + WarningInfo( + "ignore", + message="Deprecated call to `pkg_resources", + category=DeprecationWarning, + ), + # pytest-cov issue https://github.com/pytest-dev/pytest-cov/issues/557 not + # fixed although it has been closed. https://github.com/pytest-dev/pytest-cov/pull/623 + # would probably fix it. + WarningInfo( + "ignore", + message=( + "The --rsyncdir command line argument and rsyncdirs config variable are" + " deprecated" + ), + category=DeprecationWarning, + ), + # XXX: Easiest way to ignore pandas Pyarrow DeprecationWarning in the + # short-term. See https://github.com/pandas-dev/pandas/issues/54466 for + # more details. + WarningInfo( + "ignore", + message=r"\s*Pyarrow will become a required dependency", + category=DeprecationWarning, + ), + ] + + +def get_pytest_filterwarning_lines(): + warning_filters_info_list = _get_warnings_filters_info_list() + return [ + warning_info.to_filterwarning_str() + for warning_info in warning_filters_info_list + ] + + +def turn_warnings_into_errors(): + warnings_filters_info_list = _get_warnings_filters_info_list() + for warning_info in warnings_filters_info_list: + warnings.filterwarnings( + warning_info.action, + message=warning_info.message, + category=warning_info.category, + ) diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_typedefs.pxd b/venv/lib/python3.10/site-packages/sklearn/utils/_typedefs.pxd new file mode 100644 index 0000000000000000000000000000000000000000..3ffe5b3b41098f75be516ff96b84d9d0ea621824 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_typedefs.pxd @@ -0,0 +1,29 @@ +# Commonly used types +# These are redefinitions of the ones defined by numpy in +# https://github.com/numpy/numpy/blob/main/numpy/__init__.pxd +# and exposed by cython in +# https://github.com/cython/cython/blob/master/Cython/Includes/numpy/__init__.pxd. +# It will eventually avoid having to always include the numpy headers even when we +# would only use it for the types. +# +# When used to declare variables that will receive values from numpy arrays, it +# should match the dtype of the array. For example, to declare a variable that will +# receive values from a numpy array of dtype np.float64, the type float64_t must be +# used. +# +# TODO: Stop defining custom types locally or globally like DTYPE_t and friends and +# use these consistently throughout the codebase. +# NOTE: Extend this list as needed when converting more cython extensions. +ctypedef unsigned char uint8_t +ctypedef unsigned int uint32_t +ctypedef unsigned long long uint64_t +ctypedef Py_ssize_t intp_t +ctypedef float float32_t +ctypedef double float64_t +# Sparse matrices indices and indices' pointers arrays must use int32_t over +# intp_t because intp_t is platform dependent. +# When large sparse matrices are supported, indexing must use int64_t. +# See https://github.com/scikit-learn/scikit-learn/issues/23653 which tracks the +# ongoing work to support large sparse matrices. +ctypedef signed int int32_t +ctypedef signed long long int64_t diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..45922b85d73f0625701a20fd5986d3fd890333c7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_weight_vector.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/sklearn/utils/_weight_vector.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a3346298925be5b3aea88e6a3bed670925bb90d7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/_weight_vector.cpython-310-x86_64-linux-gnu.so differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/_weight_vector.pxd b/venv/lib/python3.10/site-packages/sklearn/utils/_weight_vector.pxd new file mode 100644 index 0000000000000000000000000000000000000000..a8ef0ab53d04848fbfe4b68f493146badb09d734 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/_weight_vector.pxd @@ -0,0 +1,48 @@ +# WARNING: Do not edit this file directly. +# It is automatically generated from 'sklearn/utils/_weight_vector.pxd.tp'. +# Changes must be made there. + + +cdef class WeightVector64(object): + cdef readonly double[::1] w + cdef readonly double[::1] aw + cdef double *w_data_ptr + cdef double *aw_data_ptr + + cdef double wscale + cdef double average_a + cdef double average_b + cdef int n_features + cdef double sq_norm + + cdef void add(self, double *x_data_ptr, int *x_ind_ptr, + int xnnz, double c) noexcept nogil + cdef void add_average(self, double *x_data_ptr, int *x_ind_ptr, + int xnnz, double c, double num_iter) noexcept nogil + cdef double dot(self, double *x_data_ptr, int *x_ind_ptr, + int xnnz) noexcept nogil + cdef void scale(self, double c) noexcept nogil + cdef void reset_wscale(self) noexcept nogil + cdef double norm(self) noexcept nogil + +cdef class WeightVector32(object): + cdef readonly float[::1] w + cdef readonly float[::1] aw + cdef float *w_data_ptr + cdef float *aw_data_ptr + + cdef double wscale + cdef double average_a + cdef double average_b + cdef int n_features + cdef double sq_norm + + cdef void add(self, float *x_data_ptr, int *x_ind_ptr, + int xnnz, float c) noexcept nogil + cdef void add_average(self, float *x_data_ptr, int *x_ind_ptr, + int xnnz, float c, float num_iter) noexcept nogil + cdef float dot(self, float *x_data_ptr, int *x_ind_ptr, + int xnnz) noexcept nogil + cdef void scale(self, float c) noexcept nogil + cdef void reset_wscale(self) noexcept nogil + cdef float norm(self) noexcept nogil diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/class_weight.py b/venv/lib/python3.10/site-packages/sklearn/utils/class_weight.py new file mode 100644 index 0000000000000000000000000000000000000000..55802f780ed4194c66cbd8d3a98c8edb669720b2 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/class_weight.py @@ -0,0 +1,224 @@ +""" +The :mod:`sklearn.utils.class_weight` module includes utilities for handling +weights based on class labels. +""" + +# Authors: Andreas Mueller +# Manoj Kumar +# License: BSD 3 clause + +import numpy as np +from scipy import sparse + +from ._param_validation import StrOptions, validate_params + + +@validate_params( + { + "class_weight": [dict, StrOptions({"balanced"}), None], + "classes": [np.ndarray], + "y": ["array-like"], + }, + prefer_skip_nested_validation=True, +) +def compute_class_weight(class_weight, *, classes, y): + """Estimate class weights for unbalanced datasets. + + Parameters + ---------- + class_weight : dict, "balanced" or None + If "balanced", class weights will be given by + `n_samples / (n_classes * np.bincount(y))`. + If a dictionary is given, keys are classes and values are corresponding class + weights. + If `None` is given, the class weights will be uniform. + + classes : ndarray + Array of the classes occurring in the data, as given by + `np.unique(y_org)` with `y_org` the original class labels. + + y : array-like of shape (n_samples,) + Array of original class labels per sample. + + Returns + ------- + class_weight_vect : ndarray of shape (n_classes,) + Array with `class_weight_vect[i]` the weight for i-th class. + + References + ---------- + The "balanced" heuristic is inspired by + Logistic Regression in Rare Events Data, King, Zen, 2001. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.utils.class_weight import compute_class_weight + >>> y = [1, 1, 1, 1, 0, 0] + >>> compute_class_weight(class_weight="balanced", classes=np.unique(y), y=y) + array([1.5 , 0.75]) + """ + # Import error caused by circular imports. + from ..preprocessing import LabelEncoder + + if set(y) - set(classes): + raise ValueError("classes should include all valid labels that can be in y") + if class_weight is None or len(class_weight) == 0: + # uniform class weights + weight = np.ones(classes.shape[0], dtype=np.float64, order="C") + elif class_weight == "balanced": + # Find the weight of each class as present in y. + le = LabelEncoder() + y_ind = le.fit_transform(y) + if not all(np.isin(classes, le.classes_)): + raise ValueError("classes should have valid labels that are in y") + + recip_freq = len(y) / (len(le.classes_) * np.bincount(y_ind).astype(np.float64)) + weight = recip_freq[le.transform(classes)] + else: + # user-defined dictionary + weight = np.ones(classes.shape[0], dtype=np.float64, order="C") + unweighted_classes = [] + for i, c in enumerate(classes): + if c in class_weight: + weight[i] = class_weight[c] + else: + unweighted_classes.append(c) + + n_weighted_classes = len(classes) - len(unweighted_classes) + if unweighted_classes and n_weighted_classes != len(class_weight): + unweighted_classes_user_friendly_str = np.array(unweighted_classes).tolist() + raise ValueError( + f"The classes, {unweighted_classes_user_friendly_str}, are not in" + " class_weight" + ) + + return weight + + +@validate_params( + { + "class_weight": [dict, list, StrOptions({"balanced"}), None], + "y": ["array-like", "sparse matrix"], + "indices": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def compute_sample_weight(class_weight, y, *, indices=None): + """Estimate sample weights by class for unbalanced datasets. + + Parameters + ---------- + class_weight : dict, list of dicts, "balanced", or None + Weights associated with classes in the form `{class_label: weight}`. + If not given, all classes are supposed to have weight one. For + multi-output problems, a list of dicts can be provided in the same + order as the columns of y. + + Note that for multioutput (including multilabel) weights should be + defined for each class of every column in its own dict. For example, + for four-class multilabel classification weights should be + `[{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}]` instead of + `[{1:1}, {2:5}, {3:1}, {4:1}]`. + + The `"balanced"` mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data: + `n_samples / (n_classes * np.bincount(y))`. + + For multi-output, the weights of each column of y will be multiplied. + + y : {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs) + Array of original class labels per sample. + + indices : array-like of shape (n_subsample,), default=None + Array of indices to be used in a subsample. Can be of length less than + `n_samples` in the case of a subsample, or equal to `n_samples` in the + case of a bootstrap subsample with repeated indices. If `None`, the + sample weight will be calculated over the full sample. Only `"balanced"` + is supported for `class_weight` if this is provided. + + Returns + ------- + sample_weight_vect : ndarray of shape (n_samples,) + Array with sample weights as applied to the original `y`. + + Examples + -------- + >>> from sklearn.utils.class_weight import compute_sample_weight + >>> y = [1, 1, 1, 1, 0, 0] + >>> compute_sample_weight(class_weight="balanced", y=y) + array([0.75, 0.75, 0.75, 0.75, 1.5 , 1.5 ]) + """ + + # Ensure y is 2D. Sparse matrices are already 2D. + if not sparse.issparse(y): + y = np.atleast_1d(y) + if y.ndim == 1: + y = np.reshape(y, (-1, 1)) + n_outputs = y.shape[1] + + if indices is not None and class_weight != "balanced": + raise ValueError( + "The only valid class_weight for subsampling is 'balanced'. " + f"Given {class_weight}." + ) + elif n_outputs > 1: + if class_weight is None or isinstance(class_weight, dict): + raise ValueError( + "For multi-output, class_weight should be a list of dicts, or the " + "string 'balanced'." + ) + elif isinstance(class_weight, list) and len(class_weight) != n_outputs: + raise ValueError( + "For multi-output, number of elements in class_weight should match " + f"number of outputs. Got {len(class_weight)} element(s) while having " + f"{n_outputs} outputs." + ) + + expanded_class_weight = [] + for k in range(n_outputs): + if sparse.issparse(y): + # Ok to densify a single column at a time + y_full = y[:, [k]].toarray().flatten() + else: + y_full = y[:, k] + classes_full = np.unique(y_full) + classes_missing = None + + if class_weight == "balanced" or n_outputs == 1: + class_weight_k = class_weight + else: + class_weight_k = class_weight[k] + + if indices is not None: + # Get class weights for the subsample, covering all classes in + # case some labels that were present in the original data are + # missing from the sample. + y_subsample = y_full[indices] + classes_subsample = np.unique(y_subsample) + + weight_k = np.take( + compute_class_weight( + class_weight_k, classes=classes_subsample, y=y_subsample + ), + np.searchsorted(classes_subsample, classes_full), + mode="clip", + ) + + classes_missing = set(classes_full) - set(classes_subsample) + else: + weight_k = compute_class_weight( + class_weight_k, classes=classes_full, y=y_full + ) + + weight_k = weight_k[np.searchsorted(classes_full, y_full)] + + if classes_missing: + # Make missing classes' weight zero + weight_k[np.isin(y_full, list(classes_missing))] = 0.0 + + expanded_class_weight.append(weight_k) + + expanded_class_weight = np.prod(expanded_class_weight, axis=0, dtype=np.float64) + + return expanded_class_weight diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/deprecation.py b/venv/lib/python3.10/site-packages/sklearn/utils/deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..839bac125109682db8c6619466562cc18761d05a --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/deprecation.py @@ -0,0 +1,116 @@ +import functools +import warnings + +__all__ = ["deprecated"] + + +class deprecated: + """Decorator to mark a function or class as deprecated. + + Issue a warning when the function is called/the class is instantiated and + adds a warning to the docstring. + + The optional extra argument will be appended to the deprecation message + and the docstring. Note: to use this with the default value for extra, put + in an empty of parentheses: + + Examples + -------- + >>> from sklearn.utils import deprecated + >>> deprecated() + + >>> @deprecated() + ... def some_function(): pass + + Parameters + ---------- + extra : str, default='' + To be added to the deprecation messages. + """ + + # Adapted from https://wiki.python.org/moin/PythonDecoratorLibrary, + # but with many changes. + + def __init__(self, extra=""): + self.extra = extra + + def __call__(self, obj): + """Call method + + Parameters + ---------- + obj : object + """ + if isinstance(obj, type): + return self._decorate_class(obj) + elif isinstance(obj, property): + # Note that this is only triggered properly if the `property` + # decorator comes before the `deprecated` decorator, like so: + # + # @deprecated(msg) + # @property + # def deprecated_attribute_(self): + # ... + return self._decorate_property(obj) + else: + return self._decorate_fun(obj) + + def _decorate_class(self, cls): + msg = "Class %s is deprecated" % cls.__name__ + if self.extra: + msg += "; %s" % self.extra + + new = cls.__new__ + + def wrapped(cls, *args, **kwargs): + warnings.warn(msg, category=FutureWarning) + if new is object.__new__: + return object.__new__(cls) + return new(cls, *args, **kwargs) + + cls.__new__ = wrapped + + wrapped.__name__ = "__new__" + wrapped.deprecated_original = new + + return cls + + def _decorate_fun(self, fun): + """Decorate function fun""" + + msg = "Function %s is deprecated" % fun.__name__ + if self.extra: + msg += "; %s" % self.extra + + @functools.wraps(fun) + def wrapped(*args, **kwargs): + warnings.warn(msg, category=FutureWarning) + return fun(*args, **kwargs) + + # Add a reference to the wrapped function so that we can introspect + # on function arguments in Python 2 (already works in Python 3) + wrapped.__wrapped__ = fun + + return wrapped + + def _decorate_property(self, prop): + msg = self.extra + + @property + @functools.wraps(prop) + def wrapped(*args, **kwargs): + warnings.warn(msg, category=FutureWarning) + return prop.fget(*args, **kwargs) + + return wrapped + + +def _is_deprecated(func): + """Helper to check if func is wrapped by our deprecated decorator""" + closures = getattr(func, "__closure__", []) + if closures is None: + closures = [] + is_deprecated = "deprecated" in "".join( + [c.cell_contents for c in closures if isinstance(c.cell_contents, str)] + ) + return is_deprecated diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/extmath.py b/venv/lib/python3.10/site-packages/sklearn/utils/extmath.py new file mode 100644 index 0000000000000000000000000000000000000000..9336ad851665926010bd7c99fc6f7b35fae2a574 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/extmath.py @@ -0,0 +1,1284 @@ +""" +The :mod:`sklearn.utils.extmath` module includes utilities to perform +optimal mathematical operations in scikit-learn that are not available in SciPy. +""" +# Authors: Gael Varoquaux +# Alexandre Gramfort +# Alexandre T. Passos +# Olivier Grisel +# Lars Buitinck +# Stefan van der Walt +# Kyle Kastner +# Giorgio Patrini +# License: BSD 3 clause + +import warnings +from functools import partial +from numbers import Integral + +import numpy as np +from scipy import linalg, sparse + +from ..utils import deprecated +from ..utils._param_validation import Interval, StrOptions, validate_params +from . import check_random_state +from ._array_api import _is_numpy_namespace, device, get_namespace +from .sparsefuncs_fast import csr_row_norms +from .validation import check_array + + +def squared_norm(x): + """Squared Euclidean or Frobenius norm of x. + + Faster than norm(x) ** 2. + + Parameters + ---------- + x : array-like + The input array which could be either be a vector or a 2 dimensional array. + + Returns + ------- + float + The Euclidean norm when x is a vector, the Frobenius norm when x + is a matrix (2-d array). + """ + x = np.ravel(x, order="K") + if np.issubdtype(x.dtype, np.integer): + warnings.warn( + ( + "Array type is integer, np.dot may overflow. " + "Data should be float type to avoid this issue" + ), + UserWarning, + ) + return np.dot(x, x) + + +def row_norms(X, squared=False): + """Row-wise (squared) Euclidean norm of X. + + Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports sparse + matrices and does not create an X.shape-sized temporary. + + Performs no input validation. + + Parameters + ---------- + X : array-like + The input array. + squared : bool, default=False + If True, return squared norms. + + Returns + ------- + array-like + The row-wise (squared) Euclidean norm of X. + """ + if sparse.issparse(X): + X = X.tocsr() + norms = csr_row_norms(X) + if not squared: + norms = np.sqrt(norms) + else: + xp, _ = get_namespace(X) + if _is_numpy_namespace(xp): + X = np.asarray(X) + norms = np.einsum("ij,ij->i", X, X) + norms = xp.asarray(norms) + else: + norms = xp.sum(xp.multiply(X, X), axis=1) + if not squared: + norms = xp.sqrt(norms) + return norms + + +def fast_logdet(A): + """Compute logarithm of determinant of a square matrix. + + The (natural) logarithm of the determinant of a square matrix + is returned if det(A) is non-negative and well defined. + If the determinant is zero or negative returns -Inf. + + Equivalent to : np.log(np.det(A)) but more robust. + + Parameters + ---------- + A : array_like of shape (n, n) + The square matrix. + + Returns + ------- + logdet : float + When det(A) is strictly positive, log(det(A)) is returned. + When det(A) is non-positive or not defined, then -inf is returned. + + See Also + -------- + numpy.linalg.slogdet : Compute the sign and (natural) logarithm of the determinant + of an array. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.utils.extmath import fast_logdet + >>> a = np.array([[5, 1], [2, 8]]) + >>> fast_logdet(a) + 3.6375861597263857 + """ + xp, _ = get_namespace(A) + sign, ld = xp.linalg.slogdet(A) + if not sign > 0: + return -xp.inf + return ld + + +def density(w): + """Compute density of a sparse vector. + + Parameters + ---------- + w : {ndarray, sparse matrix} + The input data can be numpy ndarray or a sparse matrix. + + Returns + ------- + float + The density of w, between 0 and 1. + + Examples + -------- + >>> from scipy import sparse + >>> from sklearn.utils.extmath import density + >>> X = sparse.random(10, 10, density=0.25, random_state=0) + >>> density(X) + 0.25 + """ + if hasattr(w, "toarray"): + d = float(w.nnz) / (w.shape[0] * w.shape[1]) + else: + d = 0 if w is None else float((w != 0).sum()) / w.size + return d + + +def safe_sparse_dot(a, b, *, dense_output=False): + """Dot product that handle the sparse matrix case correctly. + + Parameters + ---------- + a : {ndarray, sparse matrix} + b : {ndarray, sparse matrix} + dense_output : bool, default=False + When False, ``a`` and ``b`` both being sparse will yield sparse output. + When True, output will always be a dense array. + + Returns + ------- + dot_product : {ndarray, sparse matrix} + Sparse if ``a`` and ``b`` are sparse and ``dense_output=False``. + + Examples + -------- + >>> from scipy.sparse import csr_matrix + >>> from sklearn.utils.extmath import safe_sparse_dot + >>> X = csr_matrix([[1, 2], [3, 4], [5, 6]]) + >>> dot_product = safe_sparse_dot(X, X.T) + >>> dot_product.toarray() + array([[ 5, 11, 17], + [11, 25, 39], + [17, 39, 61]]) + """ + if a.ndim > 2 or b.ndim > 2: + if sparse.issparse(a): + # sparse is always 2D. Implies b is 3D+ + # [i, j] @ [k, ..., l, m, n] -> [i, k, ..., l, n] + b_ = np.rollaxis(b, -2) + b_2d = b_.reshape((b.shape[-2], -1)) + ret = a @ b_2d + ret = ret.reshape(a.shape[0], *b_.shape[1:]) + elif sparse.issparse(b): + # sparse is always 2D. Implies a is 3D+ + # [k, ..., l, m] @ [i, j] -> [k, ..., l, j] + a_2d = a.reshape(-1, a.shape[-1]) + ret = a_2d @ b + ret = ret.reshape(*a.shape[:-1], b.shape[1]) + else: + ret = np.dot(a, b) + else: + ret = a @ b + + if ( + sparse.issparse(a) + and sparse.issparse(b) + and dense_output + and hasattr(ret, "toarray") + ): + return ret.toarray() + return ret + + +def randomized_range_finder( + A, *, size, n_iter, power_iteration_normalizer="auto", random_state=None +): + """Compute an orthonormal matrix whose range approximates the range of A. + + Parameters + ---------- + A : 2D array + The input data matrix. + + size : int + Size of the return array. + + n_iter : int + Number of power iterations used to stabilize the result. + + power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto' + Whether the power iterations are normalized with step-by-step + QR factorization (the slowest but most accurate), 'none' + (the fastest but numerically unstable when `n_iter` is large, e.g. + typically 5 or larger), or 'LU' factorization (numerically stable + but can lose slightly in accuracy). The 'auto' mode applies no + normalization if `n_iter` <= 2 and switches to LU otherwise. + + .. versionadded:: 0.18 + + random_state : int, RandomState instance or None, default=None + The seed of the pseudo random number generator to use when shuffling + the data, i.e. getting the random vectors to initialize the algorithm. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + Returns + ------- + Q : ndarray + A (size x size) projection matrix, the range of which + approximates well the range of the input matrix A. + + Notes + ----- + + Follows Algorithm 4.3 of + :arxiv:`"Finding structure with randomness: + Stochastic algorithms for constructing approximate matrix decompositions" + <0909.4061>` + Halko, et al. (2009) + + An implementation of a randomized algorithm for principal component + analysis + A. Szlam et al. 2014 + + Examples + -------- + >>> import numpy as np + >>> from sklearn.utils.extmath import randomized_range_finder + >>> A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + >>> randomized_range_finder(A, size=2, n_iter=2, random_state=42) + array([[-0.21..., 0.88...], + [-0.52..., 0.24...], + [-0.82..., -0.38...]]) + """ + xp, is_array_api_compliant = get_namespace(A) + random_state = check_random_state(random_state) + + # Generating normal random vectors with shape: (A.shape[1], size) + # XXX: generate random number directly from xp if it's possible + # one day. + Q = xp.asarray(random_state.normal(size=(A.shape[1], size))) + if hasattr(A, "dtype") and xp.isdtype(A.dtype, kind="real floating"): + # Use float32 computation and components if A has a float32 dtype. + Q = xp.astype(Q, A.dtype, copy=False) + + # Move Q to device if needed only after converting to float32 if needed to + # avoid allocating unnecessary memory on the device. + + # Note: we cannot combine the astype and to_device operations in one go + # using xp.asarray(..., dtype=dtype, device=device) because downcasting + # from float64 to float32 in asarray might not always be accepted as only + # casts following type promotion rules are guarateed to work. + # https://github.com/data-apis/array-api/issues/647 + if is_array_api_compliant: + Q = xp.asarray(Q, device=device(A)) + + # Deal with "auto" mode + if power_iteration_normalizer == "auto": + if n_iter <= 2: + power_iteration_normalizer = "none" + elif is_array_api_compliant: + # XXX: https://github.com/data-apis/array-api/issues/627 + warnings.warn( + "Array API does not support LU factorization, falling back to QR" + " instead. Set `power_iteration_normalizer='QR'` explicitly to silence" + " this warning." + ) + power_iteration_normalizer = "QR" + else: + power_iteration_normalizer = "LU" + elif power_iteration_normalizer == "LU" and is_array_api_compliant: + raise ValueError( + "Array API does not support LU factorization. Set " + "`power_iteration_normalizer='QR'` instead." + ) + + if is_array_api_compliant: + qr_normalizer = partial(xp.linalg.qr, mode="reduced") + else: + # Use scipy.linalg instead of numpy.linalg when not explicitly + # using the Array API. + qr_normalizer = partial(linalg.qr, mode="economic") + + if power_iteration_normalizer == "QR": + normalizer = qr_normalizer + elif power_iteration_normalizer == "LU": + normalizer = partial(linalg.lu, permute_l=True) + else: + normalizer = lambda x: (x, None) + + # Perform power iterations with Q to further 'imprint' the top + # singular vectors of A in Q + for _ in range(n_iter): + Q, _ = normalizer(A @ Q) + Q, _ = normalizer(A.T @ Q) + + # Sample the range of A using by linear projection of Q + # Extract an orthonormal basis + Q, _ = qr_normalizer(A @ Q) + + return Q + + +@validate_params( + { + "M": [np.ndarray, "sparse matrix"], + "n_components": [Interval(Integral, 1, None, closed="left")], + "n_oversamples": [Interval(Integral, 0, None, closed="left")], + "n_iter": [Interval(Integral, 0, None, closed="left"), StrOptions({"auto"})], + "power_iteration_normalizer": [StrOptions({"auto", "QR", "LU", "none"})], + "transpose": ["boolean", StrOptions({"auto"})], + "flip_sign": ["boolean"], + "random_state": ["random_state"], + "svd_lapack_driver": [StrOptions({"gesdd", "gesvd"})], + }, + prefer_skip_nested_validation=True, +) +def randomized_svd( + M, + n_components, + *, + n_oversamples=10, + n_iter="auto", + power_iteration_normalizer="auto", + transpose="auto", + flip_sign=True, + random_state=None, + svd_lapack_driver="gesdd", +): + """Compute a truncated randomized SVD. + + This method solves the fixed-rank approximation problem described in [1]_ + (problem (1.5), p5). + + Parameters + ---------- + M : {ndarray, sparse matrix} + Matrix to decompose. + + n_components : int + Number of singular values and vectors to extract. + + n_oversamples : int, default=10 + Additional number of random vectors to sample the range of `M` so as + to ensure proper conditioning. The total number of random vectors + used to find the range of `M` is `n_components + n_oversamples`. Smaller + number can improve speed but can negatively impact the quality of + approximation of singular vectors and singular values. Users might wish + to increase this parameter up to `2*k - n_components` where k is the + effective rank, for large matrices, noisy problems, matrices with + slowly decaying spectrums, or to increase precision accuracy. See [1]_ + (pages 5, 23 and 26). + + n_iter : int or 'auto', default='auto' + Number of power iterations. It can be used to deal with very noisy + problems. When 'auto', it is set to 4, unless `n_components` is small + (< .1 * min(X.shape)) in which case `n_iter` is set to 7. + This improves precision with few components. Note that in general + users should rather increase `n_oversamples` before increasing `n_iter` + as the principle of the randomized method is to avoid usage of these + more costly power iterations steps. When `n_components` is equal + or greater to the effective matrix rank and the spectrum does not + present a slow decay, `n_iter=0` or `1` should even work fine in theory + (see [1]_ page 9). + + .. versionchanged:: 0.18 + + power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto' + Whether the power iterations are normalized with step-by-step + QR factorization (the slowest but most accurate), 'none' + (the fastest but numerically unstable when `n_iter` is large, e.g. + typically 5 or larger), or 'LU' factorization (numerically stable + but can lose slightly in accuracy). The 'auto' mode applies no + normalization if `n_iter` <= 2 and switches to LU otherwise. + + .. versionadded:: 0.18 + + transpose : bool or 'auto', default='auto' + Whether the algorithm should be applied to M.T instead of M. The + result should approximately be the same. The 'auto' mode will + trigger the transposition if M.shape[1] > M.shape[0] since this + implementation of randomized SVD tend to be a little faster in that + case. + + .. versionchanged:: 0.18 + + flip_sign : bool, default=True + The output of a singular value decomposition is only unique up to a + permutation of the signs of the singular vectors. If `flip_sign` is + set to `True`, the sign ambiguity is resolved by making the largest + loadings for each component in the left singular vectors positive. + + random_state : int, RandomState instance or None, default='warn' + The seed of the pseudo random number generator to use when + shuffling the data, i.e. getting the random vectors to initialize + the algorithm. Pass an int for reproducible results across multiple + function calls. See :term:`Glossary `. + + .. versionchanged:: 1.2 + The default value changed from 0 to None. + + svd_lapack_driver : {"gesdd", "gesvd"}, default="gesdd" + Whether to use the more efficient divide-and-conquer approach + (`"gesdd"`) or more general rectangular approach (`"gesvd"`) to compute + the SVD of the matrix B, which is the projection of M into a low + dimensional subspace, as described in [1]_. + + .. versionadded:: 1.2 + + Returns + ------- + u : ndarray of shape (n_samples, n_components) + Unitary matrix having left singular vectors with signs flipped as columns. + s : ndarray of shape (n_components,) + The singular values, sorted in non-increasing order. + vh : ndarray of shape (n_components, n_features) + Unitary matrix having right singular vectors with signs flipped as rows. + + Notes + ----- + This algorithm finds a (usually very good) approximate truncated + singular value decomposition using randomization to speed up the + computations. It is particularly fast on large matrices on which + you wish to extract only a small number of components. In order to + obtain further speed up, `n_iter` can be set <=2 (at the cost of + loss of precision). To increase the precision it is recommended to + increase `n_oversamples`, up to `2*k-n_components` where k is the + effective rank. Usually, `n_components` is chosen to be greater than k + so increasing `n_oversamples` up to `n_components` should be enough. + + References + ---------- + .. [1] :arxiv:`"Finding structure with randomness: + Stochastic algorithms for constructing approximate matrix decompositions" + <0909.4061>` + Halko, et al. (2009) + + .. [2] A randomized algorithm for the decomposition of matrices + Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert + + .. [3] An implementation of a randomized algorithm for principal component + analysis A. Szlam et al. 2014 + + Examples + -------- + >>> import numpy as np + >>> from sklearn.utils.extmath import randomized_svd + >>> a = np.array([[1, 2, 3, 5], + ... [3, 4, 5, 6], + ... [7, 8, 9, 10]]) + >>> U, s, Vh = randomized_svd(a, n_components=2, random_state=0) + >>> U.shape, s.shape, Vh.shape + ((3, 2), (2,), (2, 4)) + """ + if sparse.issparse(M) and M.format in ("lil", "dok"): + warnings.warn( + "Calculating SVD of a {} is expensive. " + "csr_matrix is more efficient.".format(type(M).__name__), + sparse.SparseEfficiencyWarning, + ) + + random_state = check_random_state(random_state) + n_random = n_components + n_oversamples + n_samples, n_features = M.shape + + if n_iter == "auto": + # Checks if the number of iterations is explicitly specified + # Adjust n_iter. 7 was found a good compromise for PCA. See #5299 + n_iter = 7 if n_components < 0.1 * min(M.shape) else 4 + + if transpose == "auto": + transpose = n_samples < n_features + if transpose: + # this implementation is a bit faster with smaller shape[1] + M = M.T + + Q = randomized_range_finder( + M, + size=n_random, + n_iter=n_iter, + power_iteration_normalizer=power_iteration_normalizer, + random_state=random_state, + ) + + # project M to the (k + p) dimensional space using the basis vectors + B = Q.T @ M + + # compute the SVD on the thin matrix: (k + p) wide + xp, is_array_api_compliant = get_namespace(B) + if is_array_api_compliant: + Uhat, s, Vt = xp.linalg.svd(B, full_matrices=False) + else: + # When when array_api_dispatch is disabled, rely on scipy.linalg + # instead of numpy.linalg to avoid introducing a behavior change w.r.t. + # previous versions of scikit-learn. + Uhat, s, Vt = linalg.svd( + B, full_matrices=False, lapack_driver=svd_lapack_driver + ) + del B + U = Q @ Uhat + + if flip_sign: + if not transpose: + U, Vt = svd_flip(U, Vt) + else: + # In case of transpose u_based_decision=false + # to actually flip based on u and not v. + U, Vt = svd_flip(U, Vt, u_based_decision=False) + + if transpose: + # transpose back the results according to the input convention + return Vt[:n_components, :].T, s[:n_components], U[:, :n_components].T + else: + return U[:, :n_components], s[:n_components], Vt[:n_components, :] + + +def _randomized_eigsh( + M, + n_components, + *, + n_oversamples=10, + n_iter="auto", + power_iteration_normalizer="auto", + selection="module", + random_state=None, +): + """Computes a truncated eigendecomposition using randomized methods + + This method solves the fixed-rank approximation problem described in the + Halko et al paper. + + The choice of which components to select can be tuned with the `selection` + parameter. + + .. versionadded:: 0.24 + + Parameters + ---------- + M : ndarray or sparse matrix + Matrix to decompose, it should be real symmetric square or complex + hermitian + + n_components : int + Number of eigenvalues and vectors to extract. + + n_oversamples : int, default=10 + Additional number of random vectors to sample the range of M so as + to ensure proper conditioning. The total number of random vectors + used to find the range of M is n_components + n_oversamples. Smaller + number can improve speed but can negatively impact the quality of + approximation of eigenvectors and eigenvalues. Users might wish + to increase this parameter up to `2*k - n_components` where k is the + effective rank, for large matrices, noisy problems, matrices with + slowly decaying spectrums, or to increase precision accuracy. See Halko + et al (pages 5, 23 and 26). + + n_iter : int or 'auto', default='auto' + Number of power iterations. It can be used to deal with very noisy + problems. When 'auto', it is set to 4, unless `n_components` is small + (< .1 * min(X.shape)) in which case `n_iter` is set to 7. + This improves precision with few components. Note that in general + users should rather increase `n_oversamples` before increasing `n_iter` + as the principle of the randomized method is to avoid usage of these + more costly power iterations steps. When `n_components` is equal + or greater to the effective matrix rank and the spectrum does not + present a slow decay, `n_iter=0` or `1` should even work fine in theory + (see Halko et al paper, page 9). + + power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto' + Whether the power iterations are normalized with step-by-step + QR factorization (the slowest but most accurate), 'none' + (the fastest but numerically unstable when `n_iter` is large, e.g. + typically 5 or larger), or 'LU' factorization (numerically stable + but can lose slightly in accuracy). The 'auto' mode applies no + normalization if `n_iter` <= 2 and switches to LU otherwise. + + selection : {'value', 'module'}, default='module' + Strategy used to select the n components. When `selection` is `'value'` + (not yet implemented, will become the default when implemented), the + components corresponding to the n largest eigenvalues are returned. + When `selection` is `'module'`, the components corresponding to the n + eigenvalues with largest modules are returned. + + random_state : int, RandomState instance, default=None + The seed of the pseudo random number generator to use when shuffling + the data, i.e. getting the random vectors to initialize the algorithm. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + Notes + ----- + This algorithm finds a (usually very good) approximate truncated + eigendecomposition using randomized methods to speed up the computations. + + This method is particularly fast on large matrices on which + you wish to extract only a small number of components. In order to + obtain further speed up, `n_iter` can be set <=2 (at the cost of + loss of precision). To increase the precision it is recommended to + increase `n_oversamples`, up to `2*k-n_components` where k is the + effective rank. Usually, `n_components` is chosen to be greater than k + so increasing `n_oversamples` up to `n_components` should be enough. + + Strategy 'value': not implemented yet. + Algorithms 5.3, 5.4 and 5.5 in the Halko et al paper should provide good + candidates for a future implementation. + + Strategy 'module': + The principle is that for diagonalizable matrices, the singular values and + eigenvalues are related: if t is an eigenvalue of A, then :math:`|t|` is a + singular value of A. This method relies on a randomized SVD to find the n + singular components corresponding to the n singular values with largest + modules, and then uses the signs of the singular vectors to find the true + sign of t: if the sign of left and right singular vectors are different + then the corresponding eigenvalue is negative. + + Returns + ------- + eigvals : 1D array of shape (n_components,) containing the `n_components` + eigenvalues selected (see ``selection`` parameter). + eigvecs : 2D array of shape (M.shape[0], n_components) containing the + `n_components` eigenvectors corresponding to the `eigvals`, in the + corresponding order. Note that this follows the `scipy.linalg.eigh` + convention. + + See Also + -------- + :func:`randomized_svd` + + References + ---------- + * :arxiv:`"Finding structure with randomness: + Stochastic algorithms for constructing approximate matrix decompositions" + (Algorithm 4.3 for strategy 'module') <0909.4061>` + Halko, et al. (2009) + """ + if selection == "value": # pragma: no cover + # to do : an algorithm can be found in the Halko et al reference + raise NotImplementedError() + + elif selection == "module": + # Note: no need for deterministic U and Vt (flip_sign=True), + # as we only use the dot product UVt afterwards + U, S, Vt = randomized_svd( + M, + n_components=n_components, + n_oversamples=n_oversamples, + n_iter=n_iter, + power_iteration_normalizer=power_iteration_normalizer, + flip_sign=False, + random_state=random_state, + ) + + eigvecs = U[:, :n_components] + eigvals = S[:n_components] + + # Conversion of Singular values into Eigenvalues: + # For any eigenvalue t, the corresponding singular value is |t|. + # So if there is a negative eigenvalue t, the corresponding singular + # value will be -t, and the left (U) and right (V) singular vectors + # will have opposite signs. + # Fastest way: see + diag_VtU = np.einsum("ji,ij->j", Vt[:n_components, :], U[:, :n_components]) + signs = np.sign(diag_VtU) + eigvals = eigvals * signs + + else: # pragma: no cover + raise ValueError("Invalid `selection`: %r" % selection) + + return eigvals, eigvecs + + +def weighted_mode(a, w, *, axis=0): + """Return an array of the weighted modal (most common) value in the passed array. + + If there is more than one such value, only the first is returned. + The bin-count for the modal bins is also returned. + + This is an extension of the algorithm in scipy.stats.mode. + + Parameters + ---------- + a : array-like of shape (n_samples,) + Array of which values to find mode(s). + w : array-like of shape (n_samples,) + Array of weights for each value. + axis : int, default=0 + Axis along which to operate. Default is 0, i.e. the first axis. + + Returns + ------- + vals : ndarray + Array of modal values. + score : ndarray + Array of weighted counts for each mode. + + See Also + -------- + scipy.stats.mode: Calculates the Modal (most common) value of array elements + along specified axis. + + Examples + -------- + >>> from sklearn.utils.extmath import weighted_mode + >>> x = [4, 1, 4, 2, 4, 2] + >>> weights = [1, 1, 1, 1, 1, 1] + >>> weighted_mode(x, weights) + (array([4.]), array([3.])) + + The value 4 appears three times: with uniform weights, the result is + simply the mode of the distribution. + + >>> weights = [1, 3, 0.5, 1.5, 1, 2] # deweight the 4's + >>> weighted_mode(x, weights) + (array([2.]), array([3.5])) + + The value 2 has the highest score: it appears twice with weights of + 1.5 and 2: the sum of these is 3.5. + """ + if axis is None: + a = np.ravel(a) + w = np.ravel(w) + axis = 0 + else: + a = np.asarray(a) + w = np.asarray(w) + + if a.shape != w.shape: + w = np.full(a.shape, w, dtype=w.dtype) + + scores = np.unique(np.ravel(a)) # get ALL unique values + testshape = list(a.shape) + testshape[axis] = 1 + oldmostfreq = np.zeros(testshape) + oldcounts = np.zeros(testshape) + for score in scores: + template = np.zeros(a.shape) + ind = a == score + template[ind] = w[ind] + counts = np.expand_dims(np.sum(template, axis), axis) + mostfrequent = np.where(counts > oldcounts, score, oldmostfreq) + oldcounts = np.maximum(counts, oldcounts) + oldmostfreq = mostfrequent + return mostfrequent, oldcounts + + +def cartesian(arrays, out=None): + """Generate a cartesian product of input arrays. + + Parameters + ---------- + arrays : list of array-like + 1-D arrays to form the cartesian product of. + out : ndarray of shape (M, len(arrays)), default=None + Array to place the cartesian product in. + + Returns + ------- + out : ndarray of shape (M, len(arrays)) + Array containing the cartesian products formed of input arrays. + If not provided, the `dtype` of the output array is set to the most + permissive `dtype` of the input arrays, according to NumPy type + promotion. + + .. versionadded:: 1.2 + Add support for arrays of different types. + + Notes + ----- + This function may not be used on more than 32 arrays + because the underlying numpy functions do not support it. + + Examples + -------- + >>> from sklearn.utils.extmath import cartesian + >>> cartesian(([1, 2, 3], [4, 5], [6, 7])) + array([[1, 4, 6], + [1, 4, 7], + [1, 5, 6], + [1, 5, 7], + [2, 4, 6], + [2, 4, 7], + [2, 5, 6], + [2, 5, 7], + [3, 4, 6], + [3, 4, 7], + [3, 5, 6], + [3, 5, 7]]) + """ + arrays = [np.asarray(x) for x in arrays] + shape = (len(x) for x in arrays) + + ix = np.indices(shape) + ix = ix.reshape(len(arrays), -1).T + + if out is None: + dtype = np.result_type(*arrays) # find the most permissive dtype + out = np.empty_like(ix, dtype=dtype) + + for n, arr in enumerate(arrays): + out[:, n] = arrays[n][ix[:, n]] + + return out + + +def svd_flip(u, v, u_based_decision=True): + """Sign correction to ensure deterministic output from SVD. + + Adjusts the columns of u and the rows of v such that the loadings in the + columns in u that are largest in absolute value are always positive. + + If u_based_decision is False, then the same sign correction is applied to + so that the rows in v that are largest in absolute value are always + positive. + + Parameters + ---------- + u : ndarray + Parameters u and v are the output of `linalg.svd` or + :func:`~sklearn.utils.extmath.randomized_svd`, with matching inner + dimensions so one can compute `np.dot(u * s, v)`. + + v : ndarray + Parameters u and v are the output of `linalg.svd` or + :func:`~sklearn.utils.extmath.randomized_svd`, with matching inner + dimensions so one can compute `np.dot(u * s, v)`. The input v should + really be called vt to be consistent with scipy's output. + + u_based_decision : bool, default=True + If True, use the columns of u as the basis for sign flipping. + Otherwise, use the rows of v. The choice of which variable to base the + decision on is generally algorithm dependent. + + Returns + ------- + u_adjusted : ndarray + Array u with adjusted columns and the same dimensions as u. + + v_adjusted : ndarray + Array v with adjusted rows and the same dimensions as v. + """ + xp, _ = get_namespace(u, v) + device = getattr(u, "device", None) + + if u_based_decision: + # columns of u, rows of v, or equivalently rows of u.T and v + max_abs_u_cols = xp.argmax(xp.abs(u.T), axis=1) + shift = xp.arange(u.T.shape[0], device=device) + indices = max_abs_u_cols + shift * u.T.shape[1] + signs = xp.sign(xp.take(xp.reshape(u.T, (-1,)), indices, axis=0)) + u *= signs[np.newaxis, :] + v *= signs[:, np.newaxis] + else: + # rows of v, columns of u + max_abs_v_rows = xp.argmax(xp.abs(v), axis=1) + shift = xp.arange(v.shape[0], device=device) + indices = max_abs_v_rows + shift * v.shape[1] + signs = xp.sign(xp.take(xp.reshape(v, (-1,)), indices)) + u *= signs[np.newaxis, :] + v *= signs[:, np.newaxis] + return u, v + + +# TODO(1.6): remove +@deprecated( # type: ignore + "The function `log_logistic` is deprecated and will be removed in 1.6. " + "Use `-np.logaddexp(0, -x)` instead." +) +def log_logistic(X, out=None): + """Compute the log of the logistic function, ``log(1 / (1 + e ** -x))``. + + This implementation is numerically stable and uses `-np.logaddexp(0, -x)`. + + For the ordinary logistic function, use ``scipy.special.expit``. + + Parameters + ---------- + X : array-like of shape (M, N) or (M,) + Argument to the logistic function. + + out : array-like of shape (M, N) or (M,), default=None + Preallocated output array. + + Returns + ------- + out : ndarray of shape (M, N) or (M,) + Log of the logistic function evaluated at every point in x. + + Notes + ----- + See the blog post describing this implementation: + http://fa.bianp.net/blog/2013/numerical-optimizers-for-logistic-regression/ + """ + X = check_array(X, dtype=np.float64, ensure_2d=False) + + if out is None: + out = np.empty_like(X) + + np.logaddexp(0, -X, out=out) + out *= -1 + return out + + +def softmax(X, copy=True): + """ + Calculate the softmax function. + + The softmax function is calculated by + np.exp(X) / np.sum(np.exp(X), axis=1) + + This will cause overflow when large values are exponentiated. + Hence the largest value in each row is subtracted from each data + point to prevent this. + + Parameters + ---------- + X : array-like of float of shape (M, N) + Argument to the logistic function. + + copy : bool, default=True + Copy X or not. + + Returns + ------- + out : ndarray of shape (M, N) + Softmax function evaluated at every point in x. + """ + xp, is_array_api_compliant = get_namespace(X) + if copy: + X = xp.asarray(X, copy=True) + max_prob = xp.reshape(xp.max(X, axis=1), (-1, 1)) + X -= max_prob + + if _is_numpy_namespace(xp): + # optimization for NumPy arrays + np.exp(X, out=np.asarray(X)) + else: + # array_api does not have `out=` + X = xp.exp(X) + + sum_prob = xp.reshape(xp.sum(X, axis=1), (-1, 1)) + X /= sum_prob + return X + + +def make_nonnegative(X, min_value=0): + """Ensure `X.min()` >= `min_value`. + + Parameters + ---------- + X : array-like + The matrix to make non-negative. + min_value : float, default=0 + The threshold value. + + Returns + ------- + array-like + The thresholded array. + + Raises + ------ + ValueError + When X is sparse. + """ + min_ = X.min() + if min_ < min_value: + if sparse.issparse(X): + raise ValueError( + "Cannot make the data matrix" + " nonnegative because it is sparse." + " Adding a value to every entry would" + " make it no longer sparse." + ) + X = X + (min_value - min_) + return X + + +# Use at least float64 for the accumulating functions to avoid precision issue +# see https://github.com/numpy/numpy/issues/9393. The float64 is also retained +# as it is in case the float overflows +def _safe_accumulator_op(op, x, *args, **kwargs): + """ + This function provides numpy accumulator functions with a float64 dtype + when used on a floating point input. This prevents accumulator overflow on + smaller floating point dtypes. + + Parameters + ---------- + op : function + A numpy accumulator function such as np.mean or np.sum. + x : ndarray + A numpy array to apply the accumulator function. + *args : positional arguments + Positional arguments passed to the accumulator function after the + input x. + **kwargs : keyword arguments + Keyword arguments passed to the accumulator function. + + Returns + ------- + result + The output of the accumulator function passed to this function. + """ + if np.issubdtype(x.dtype, np.floating) and x.dtype.itemsize < 8: + result = op(x, *args, **kwargs, dtype=np.float64) + else: + result = op(x, *args, **kwargs) + return result + + +def _incremental_mean_and_var( + X, last_mean, last_variance, last_sample_count, sample_weight=None +): + """Calculate mean update and a Youngs and Cramer variance update. + + If sample_weight is given, the weighted mean and variance is computed. + + Update a given mean and (possibly) variance according to new data given + in X. last_mean is always required to compute the new mean. + If last_variance is None, no variance is computed and None return for + updated_variance. + + From the paper "Algorithms for computing the sample variance: analysis and + recommendations", by Chan, Golub, and LeVeque. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Data to use for variance update. + + last_mean : array-like of shape (n_features,) + + last_variance : array-like of shape (n_features,) + + last_sample_count : array-like of shape (n_features,) + The number of samples encountered until now if sample_weight is None. + If sample_weight is not None, this is the sum of sample_weight + encountered. + + sample_weight : array-like of shape (n_samples,) or None + Sample weights. If None, compute the unweighted mean/variance. + + Returns + ------- + updated_mean : ndarray of shape (n_features,) + + updated_variance : ndarray of shape (n_features,) + None if last_variance was None. + + updated_sample_count : ndarray of shape (n_features,) + + Notes + ----- + NaNs are ignored during the algorithm. + + References + ---------- + T. Chan, G. Golub, R. LeVeque. Algorithms for computing the sample + variance: recommendations, The American Statistician, Vol. 37, No. 3, + pp. 242-247 + + Also, see the sparse implementation of this in + `utils.sparsefuncs.incr_mean_variance_axis` and + `utils.sparsefuncs_fast.incr_mean_variance_axis0` + """ + # old = stats until now + # new = the current increment + # updated = the aggregated stats + last_sum = last_mean * last_sample_count + X_nan_mask = np.isnan(X) + if np.any(X_nan_mask): + sum_op = np.nansum + else: + sum_op = np.sum + if sample_weight is not None: + # equivalent to np.nansum(X * sample_weight, axis=0) + # safer because np.float64(X*W) != np.float64(X)*np.float64(W) + new_sum = _safe_accumulator_op( + np.matmul, sample_weight, np.where(X_nan_mask, 0, X) + ) + new_sample_count = _safe_accumulator_op( + np.sum, sample_weight[:, None] * (~X_nan_mask), axis=0 + ) + else: + new_sum = _safe_accumulator_op(sum_op, X, axis=0) + n_samples = X.shape[0] + new_sample_count = n_samples - np.sum(X_nan_mask, axis=0) + + updated_sample_count = last_sample_count + new_sample_count + + updated_mean = (last_sum + new_sum) / updated_sample_count + + if last_variance is None: + updated_variance = None + else: + T = new_sum / new_sample_count + temp = X - T + if sample_weight is not None: + # equivalent to np.nansum((X-T)**2 * sample_weight, axis=0) + # safer because np.float64(X*W) != np.float64(X)*np.float64(W) + correction = _safe_accumulator_op( + np.matmul, sample_weight, np.where(X_nan_mask, 0, temp) + ) + temp **= 2 + new_unnormalized_variance = _safe_accumulator_op( + np.matmul, sample_weight, np.where(X_nan_mask, 0, temp) + ) + else: + correction = _safe_accumulator_op(sum_op, temp, axis=0) + temp **= 2 + new_unnormalized_variance = _safe_accumulator_op(sum_op, temp, axis=0) + + # correction term of the corrected 2 pass algorithm. + # See "Algorithms for computing the sample variance: analysis + # and recommendations", by Chan, Golub, and LeVeque. + new_unnormalized_variance -= correction**2 / new_sample_count + + last_unnormalized_variance = last_variance * last_sample_count + + with np.errstate(divide="ignore", invalid="ignore"): + last_over_new_count = last_sample_count / new_sample_count + updated_unnormalized_variance = ( + last_unnormalized_variance + + new_unnormalized_variance + + last_over_new_count + / updated_sample_count + * (last_sum / last_over_new_count - new_sum) ** 2 + ) + + zeros = last_sample_count == 0 + updated_unnormalized_variance[zeros] = new_unnormalized_variance[zeros] + updated_variance = updated_unnormalized_variance / updated_sample_count + + return updated_mean, updated_variance, updated_sample_count + + +def _deterministic_vector_sign_flip(u): + """Modify the sign of vectors for reproducibility. + + Flips the sign of elements of all the vectors (rows of u) such that + the absolute maximum element of each vector is positive. + + Parameters + ---------- + u : ndarray + Array with vectors as its rows. + + Returns + ------- + u_flipped : ndarray with same shape as u + Array with the sign flipped vectors as its rows. + """ + max_abs_rows = np.argmax(np.abs(u), axis=1) + signs = np.sign(u[range(u.shape[0]), max_abs_rows]) + u *= signs[:, np.newaxis] + return u + + +def stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08): + """Use high precision for cumsum and check that final value matches sum. + + Warns if the final cumulative sum does not match the sum (up to the chosen + tolerance). + + Parameters + ---------- + arr : array-like + To be cumulatively summed as flat. + axis : int, default=None + Axis along which the cumulative sum is computed. + The default (None) is to compute the cumsum over the flattened array. + rtol : float, default=1e-05 + Relative tolerance, see ``np.allclose``. + atol : float, default=1e-08 + Absolute tolerance, see ``np.allclose``. + + Returns + ------- + out : ndarray + Array with the cumulative sums along the chosen axis. + """ + out = np.cumsum(arr, axis=axis, dtype=np.float64) + expected = np.sum(arr, axis=axis, dtype=np.float64) + if not np.allclose( + out.take(-1, axis=axis), expected, rtol=rtol, atol=atol, equal_nan=True + ): + warnings.warn( + ( + "cumsum was found to be unstable: " + "its last element does not correspond to sum" + ), + RuntimeWarning, + ) + return out + + +def _nanaverage(a, weights=None): + """Compute the weighted average, ignoring NaNs. + + Parameters + ---------- + a : ndarray + Array containing data to be averaged. + weights : array-like, default=None + An array of weights associated with the values in a. Each value in a + contributes to the average according to its associated weight. The + weights array can either be 1-D of the same shape as a. If `weights=None`, + then all data in a are assumed to have a weight equal to one. + + Returns + ------- + weighted_average : float + The weighted average. + + Notes + ----- + This wrapper to combine :func:`numpy.average` and :func:`numpy.nanmean`, so + that :func:`np.nan` values are ignored from the average and weights can + be passed. Note that when possible, we delegate to the prime methods. + """ + + if len(a) == 0: + return np.nan + + mask = np.isnan(a) + if mask.all(): + return np.nan + + if weights is None: + return np.nanmean(a) + + weights = np.asarray(weights) + a, weights = a[~mask], weights[~mask] + try: + return np.average(a, weights=weights) + except ZeroDivisionError: + # this is when all weights are zero, then ignore them + return np.average(a) diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/optimize.py b/venv/lib/python3.10/site-packages/sklearn/utils/optimize.py new file mode 100644 index 0000000000000000000000000000000000000000..024b0bcaf95ee7bfdb0cf67047b84d68dbe24849 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/optimize.py @@ -0,0 +1,302 @@ +""" +Our own implementation of the Newton algorithm + +Unlike the scipy.optimize version, this version of the Newton conjugate +gradient solver uses only one function call to retrieve the +func value, the gradient value and a callable for the Hessian matvec +product. If the function call is very expensive (e.g. for logistic +regression with large design matrix), this approach gives very +significant speedups. +""" +# This is a modified file from scipy.optimize +# Original authors: Travis Oliphant, Eric Jones +# Modifications by Gael Varoquaux, Mathieu Blondel and Tom Dupre la Tour +# License: BSD + +import warnings + +import numpy as np +import scipy + +from ..exceptions import ConvergenceWarning +from .fixes import line_search_wolfe1, line_search_wolfe2 + + +class _LineSearchError(RuntimeError): + pass + + +def _line_search_wolfe12(f, fprime, xk, pk, gfk, old_fval, old_old_fval, **kwargs): + """ + Same as line_search_wolfe1, but fall back to line_search_wolfe2 if + suitable step length is not found, and raise an exception if a + suitable step length is not found. + + Raises + ------ + _LineSearchError + If no suitable step size is found. + + """ + ret = line_search_wolfe1(f, fprime, xk, pk, gfk, old_fval, old_old_fval, **kwargs) + + if ret[0] is None: + # Have a look at the line_search method of our NewtonSolver class. We borrow + # the logic from there + # Deal with relative loss differences around machine precision. + args = kwargs.get("args", tuple()) + fval = f(xk + pk, *args) + eps = 16 * np.finfo(np.asarray(old_fval).dtype).eps + tiny_loss = np.abs(old_fval * eps) + loss_improvement = fval - old_fval + check = np.abs(loss_improvement) <= tiny_loss + if check: + # 2.1 Check sum of absolute gradients as alternative condition. + sum_abs_grad_old = scipy.linalg.norm(gfk, ord=1) + grad = fprime(xk + pk, *args) + sum_abs_grad = scipy.linalg.norm(grad, ord=1) + check = sum_abs_grad < sum_abs_grad_old + if check: + ret = ( + 1.0, # step size + ret[1] + 1, # number of function evaluations + ret[2] + 1, # number of gradient evaluations + fval, + old_fval, + grad, + ) + + if ret[0] is None: + # line search failed: try different one. + # TODO: It seems that the new check for the sum of absolute gradients above + # catches all cases that, earlier, ended up here. In fact, our tests never + # trigger this "if branch" here and we can consider to remove it. + ret = line_search_wolfe2( + f, fprime, xk, pk, gfk, old_fval, old_old_fval, **kwargs + ) + + if ret[0] is None: + raise _LineSearchError() + + return ret + + +def _cg(fhess_p, fgrad, maxiter, tol): + """ + Solve iteratively the linear system 'fhess_p . xsupi = fgrad' + with a conjugate gradient descent. + + Parameters + ---------- + fhess_p : callable + Function that takes the gradient as a parameter and returns the + matrix product of the Hessian and gradient. + + fgrad : ndarray of shape (n_features,) or (n_features + 1,) + Gradient vector. + + maxiter : int + Number of CG iterations. + + tol : float + Stopping criterion. + + Returns + ------- + xsupi : ndarray of shape (n_features,) or (n_features + 1,) + Estimated solution. + """ + xsupi = np.zeros(len(fgrad), dtype=fgrad.dtype) + ri = np.copy(fgrad) + psupi = -ri + i = 0 + dri0 = np.dot(ri, ri) + # We also track of |p_i|^2. + psupi_norm2 = dri0 + + while i <= maxiter: + if np.sum(np.abs(ri)) <= tol: + break + + Ap = fhess_p(psupi) + # check curvature + curv = np.dot(psupi, Ap) + if 0 <= curv <= 16 * np.finfo(np.float64).eps * psupi_norm2: + # See https://arxiv.org/abs/1803.02924, Algo 1 Capped Conjugate Gradient. + break + elif curv < 0: + if i > 0: + break + else: + # fall back to steepest descent direction + xsupi += dri0 / curv * psupi + break + alphai = dri0 / curv + xsupi += alphai * psupi + ri += alphai * Ap + dri1 = np.dot(ri, ri) + betai = dri1 / dri0 + psupi = -ri + betai * psupi + # We use |p_i|^2 = |r_i|^2 + beta_i^2 |p_{i-1}|^2 + psupi_norm2 = dri1 + betai**2 * psupi_norm2 + i = i + 1 + dri0 = dri1 # update np.dot(ri,ri) for next time. + + return xsupi + + +def _newton_cg( + grad_hess, + func, + grad, + x0, + args=(), + tol=1e-4, + maxiter=100, + maxinner=200, + line_search=True, + warn=True, +): + """ + Minimization of scalar function of one or more variables using the + Newton-CG algorithm. + + Parameters + ---------- + grad_hess : callable + Should return the gradient and a callable returning the matvec product + of the Hessian. + + func : callable + Should return the value of the function. + + grad : callable + Should return the function value and the gradient. This is used + by the linesearch functions. + + x0 : array of float + Initial guess. + + args : tuple, default=() + Arguments passed to func_grad_hess, func and grad. + + tol : float, default=1e-4 + Stopping criterion. The iteration will stop when + ``max{|g_i | i = 1, ..., n} <= tol`` + where ``g_i`` is the i-th component of the gradient. + + maxiter : int, default=100 + Number of Newton iterations. + + maxinner : int, default=200 + Number of CG iterations. + + line_search : bool, default=True + Whether to use a line search or not. + + warn : bool, default=True + Whether to warn when didn't converge. + + Returns + ------- + xk : ndarray of float + Estimated minimum. + """ + x0 = np.asarray(x0).flatten() + xk = np.copy(x0) + k = 0 + + if line_search: + old_fval = func(x0, *args) + old_old_fval = None + + # Outer loop: our Newton iteration + while k < maxiter: + # Compute a search direction pk by applying the CG method to + # del2 f(xk) p = - fgrad f(xk) starting from 0. + fgrad, fhess_p = grad_hess(xk, *args) + + absgrad = np.abs(fgrad) + if np.max(absgrad) <= tol: + break + + maggrad = np.sum(absgrad) + eta = min([0.5, np.sqrt(maggrad)]) + termcond = eta * maggrad + + # Inner loop: solve the Newton update by conjugate gradient, to + # avoid inverting the Hessian + xsupi = _cg(fhess_p, fgrad, maxiter=maxinner, tol=termcond) + + alphak = 1.0 + + if line_search: + try: + alphak, fc, gc, old_fval, old_old_fval, gfkp1 = _line_search_wolfe12( + func, grad, xk, xsupi, fgrad, old_fval, old_old_fval, args=args + ) + except _LineSearchError: + warnings.warn("Line Search failed") + break + + xk += alphak * xsupi # upcast if necessary + k += 1 + + if warn and k >= maxiter: + warnings.warn( + "newton-cg failed to converge. Increase the number of iterations.", + ConvergenceWarning, + ) + return xk, k + + +def _check_optimize_result(solver, result, max_iter=None, extra_warning_msg=None): + """Check the OptimizeResult for successful convergence + + Parameters + ---------- + solver : str + Solver name. Currently only `lbfgs` is supported. + + result : OptimizeResult + Result of the scipy.optimize.minimize function. + + max_iter : int, default=None + Expected maximum number of iterations. + + extra_warning_msg : str, default=None + Extra warning message. + + Returns + ------- + n_iter : int + Number of iterations. + """ + # handle both scipy and scikit-learn solver names + if solver == "lbfgs": + if result.status != 0: + try: + # The message is already decoded in scipy>=1.6.0 + result_message = result.message.decode("latin1") + except AttributeError: + result_message = result.message + warning_msg = ( + "{} failed to converge (status={}):\n{}.\n\n" + "Increase the number of iterations (max_iter) " + "or scale the data as shown in:\n" + " https://scikit-learn.org/stable/modules/" + "preprocessing.html" + ).format(solver, result.status, result_message) + if extra_warning_msg is not None: + warning_msg += "\n" + extra_warning_msg + warnings.warn(warning_msg, ConvergenceWarning, stacklevel=2) + if max_iter is not None: + # In scipy <= 1.0.0, nit may exceed maxiter for lbfgs. + # See https://github.com/scipy/scipy/issues/7854 + n_iter_i = min(result.nit, max_iter) + else: + n_iter_i = result.nit + else: + raise NotImplementedError + + return n_iter_i diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/parallel.py b/venv/lib/python3.10/site-packages/sklearn/utils/parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..d0dc2ec2be030e341b90843122c6109e02462ad8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/parallel.py @@ -0,0 +1,129 @@ +""" +The :mod:`sklearn.utils.parallel` customizes `joblib` tools for scikit-learn usage. +""" + +import functools +import warnings +from functools import update_wrapper + +import joblib + +from .._config import config_context, get_config + + +def _with_config(delayed_func, config): + """Helper function that intends to attach a config to a delayed function.""" + if hasattr(delayed_func, "with_config"): + return delayed_func.with_config(config) + else: + warnings.warn( + ( + "`sklearn.utils.parallel.Parallel` needs to be used in " + "conjunction with `sklearn.utils.parallel.delayed` instead of " + "`joblib.delayed` to correctly propagate the scikit-learn " + "configuration to the joblib workers." + ), + UserWarning, + ) + return delayed_func + + +class Parallel(joblib.Parallel): + """Tweak of :class:`joblib.Parallel` that propagates the scikit-learn configuration. + + This subclass of :class:`joblib.Parallel` ensures that the active configuration + (thread-local) of scikit-learn is propagated to the parallel workers for the + duration of the execution of the parallel tasks. + + The API does not change and you can refer to :class:`joblib.Parallel` + documentation for more details. + + .. versionadded:: 1.3 + """ + + def __call__(self, iterable): + """Dispatch the tasks and return the results. + + Parameters + ---------- + iterable : iterable + Iterable containing tuples of (delayed_function, args, kwargs) that should + be consumed. + + Returns + ------- + results : list + List of results of the tasks. + """ + # Capture the thread-local scikit-learn configuration at the time + # Parallel.__call__ is issued since the tasks can be dispatched + # in a different thread depending on the backend and on the value of + # pre_dispatch and n_jobs. + config = get_config() + iterable_with_config = ( + (_with_config(delayed_func, config), args, kwargs) + for delayed_func, args, kwargs in iterable + ) + return super().__call__(iterable_with_config) + + +# remove when https://github.com/joblib/joblib/issues/1071 is fixed +def delayed(function): + """Decorator used to capture the arguments of a function. + + This alternative to `joblib.delayed` is meant to be used in conjunction + with `sklearn.utils.parallel.Parallel`. The latter captures the scikit- + learn configuration by calling `sklearn.get_config()` in the current + thread, prior to dispatching the first task. The captured configuration is + then propagated and enabled for the duration of the execution of the + delayed function in the joblib workers. + + .. versionchanged:: 1.3 + `delayed` was moved from `sklearn.utils.fixes` to `sklearn.utils.parallel` + in scikit-learn 1.3. + + Parameters + ---------- + function : callable + The function to be delayed. + + Returns + ------- + output: tuple + Tuple containing the delayed function, the positional arguments, and the + keyword arguments. + """ + + @functools.wraps(function) + def delayed_function(*args, **kwargs): + return _FuncWrapper(function), args, kwargs + + return delayed_function + + +class _FuncWrapper: + """Load the global configuration before calling the function.""" + + def __init__(self, function): + self.function = function + update_wrapper(self, self.function) + + def with_config(self, config): + self.config = config + return self + + def __call__(self, *args, **kwargs): + config = getattr(self, "config", None) + if config is None: + warnings.warn( + ( + "`sklearn.utils.parallel.delayed` should be used with" + " `sklearn.utils.parallel.Parallel` to make it possible to" + " propagate the scikit-learn configuration of the current thread to" + " the joblib workers." + ), + UserWarning, + ) + config = {} + with config_context(**config): + return self.function(*args, **kwargs) diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/sparsefuncs.py b/venv/lib/python3.10/site-packages/sklearn/utils/sparsefuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..a46e9e4d9ed934139a1308df8336d957f14be99b --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/sparsefuncs.py @@ -0,0 +1,745 @@ +""" +The :mod:`sklearn.utils.sparsefuncs` module includes a collection of utilities to +work with sparse matrices and arrays. +""" + +# Authors: Manoj Kumar +# Thomas Unterthiner +# Giorgio Patrini +# +# License: BSD 3 clause +import numpy as np +import scipy.sparse as sp +from scipy.sparse.linalg import LinearOperator + +from ..utils.fixes import _sparse_min_max, _sparse_nan_min_max +from ..utils.validation import _check_sample_weight +from .sparsefuncs_fast import ( + csc_mean_variance_axis0 as _csc_mean_var_axis0, +) +from .sparsefuncs_fast import ( + csr_mean_variance_axis0 as _csr_mean_var_axis0, +) +from .sparsefuncs_fast import ( + incr_mean_variance_axis0 as _incr_mean_var_axis0, +) + + +def _raise_typeerror(X): + """Raises a TypeError if X is not a CSR or CSC matrix""" + input_type = X.format if sp.issparse(X) else type(X) + err = "Expected a CSR or CSC sparse matrix, got %s." % input_type + raise TypeError(err) + + +def _raise_error_wrong_axis(axis): + if axis not in (0, 1): + raise ValueError( + "Unknown axis value: %d. Use 0 for rows, or 1 for columns" % axis + ) + + +def inplace_csr_column_scale(X, scale): + """Inplace column scaling of a CSR matrix. + + Scale each feature of the data matrix by multiplying with specific scale + provided by the caller assuming a (n_samples, n_features) shape. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix to normalize using the variance of the features. + It should be of CSR format. + + scale : ndarray of shape (n_features,), dtype={np.float32, np.float64} + Array of precomputed feature-wise values to use for scaling. + + Examples + -------- + >>> from sklearn.utils import sparsefuncs + >>> from scipy import sparse + >>> import numpy as np + >>> indptr = np.array([0, 3, 4, 4, 4]) + >>> indices = np.array([0, 1, 2, 2]) + >>> data = np.array([8, 1, 2, 5]) + >>> scale = np.array([2, 3, 2]) + >>> csr = sparse.csr_matrix((data, indices, indptr)) + >>> csr.todense() + matrix([[8, 1, 2], + [0, 0, 5], + [0, 0, 0], + [0, 0, 0]]) + >>> sparsefuncs.inplace_csr_column_scale(csr, scale) + >>> csr.todense() + matrix([[16, 3, 4], + [ 0, 0, 10], + [ 0, 0, 0], + [ 0, 0, 0]]) + """ + assert scale.shape[0] == X.shape[1] + X.data *= scale.take(X.indices, mode="clip") + + +def inplace_csr_row_scale(X, scale): + """Inplace row scaling of a CSR matrix. + + Scale each sample of the data matrix by multiplying with specific scale + provided by the caller assuming a (n_samples, n_features) shape. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix to be scaled. It should be of CSR format. + + scale : ndarray of float of shape (n_samples,) + Array of precomputed sample-wise values to use for scaling. + """ + assert scale.shape[0] == X.shape[0] + X.data *= np.repeat(scale, np.diff(X.indptr)) + + +def mean_variance_axis(X, axis, weights=None, return_sum_weights=False): + """Compute mean and variance along an axis on a CSR or CSC matrix. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Input data. It can be of CSR or CSC format. + + axis : {0, 1} + Axis along which the axis should be computed. + + weights : ndarray of shape (n_samples,) or (n_features,), default=None + If axis is set to 0 shape is (n_samples,) or + if axis is set to 1 shape is (n_features,). + If it is set to None, then samples are equally weighted. + + .. versionadded:: 0.24 + + return_sum_weights : bool, default=False + If True, returns the sum of weights seen for each feature + if `axis=0` or each sample if `axis=1`. + + .. versionadded:: 0.24 + + Returns + ------- + + means : ndarray of shape (n_features,), dtype=floating + Feature-wise means. + + variances : ndarray of shape (n_features,), dtype=floating + Feature-wise variances. + + sum_weights : ndarray of shape (n_features,), dtype=floating + Returned if `return_sum_weights` is `True`. + + Examples + -------- + >>> from sklearn.utils import sparsefuncs + >>> from scipy import sparse + >>> import numpy as np + >>> indptr = np.array([0, 3, 4, 4, 4]) + >>> indices = np.array([0, 1, 2, 2]) + >>> data = np.array([8, 1, 2, 5]) + >>> scale = np.array([2, 3, 2]) + >>> csr = sparse.csr_matrix((data, indices, indptr)) + >>> csr.todense() + matrix([[8, 1, 2], + [0, 0, 5], + [0, 0, 0], + [0, 0, 0]]) + >>> sparsefuncs.mean_variance_axis(csr, axis=0) + (array([2. , 0.25, 1.75]), array([12. , 0.1875, 4.1875])) + """ + _raise_error_wrong_axis(axis) + + if sp.issparse(X) and X.format == "csr": + if axis == 0: + return _csr_mean_var_axis0( + X, weights=weights, return_sum_weights=return_sum_weights + ) + else: + return _csc_mean_var_axis0( + X.T, weights=weights, return_sum_weights=return_sum_weights + ) + elif sp.issparse(X) and X.format == "csc": + if axis == 0: + return _csc_mean_var_axis0( + X, weights=weights, return_sum_weights=return_sum_weights + ) + else: + return _csr_mean_var_axis0( + X.T, weights=weights, return_sum_weights=return_sum_weights + ) + else: + _raise_typeerror(X) + + +def incr_mean_variance_axis(X, *, axis, last_mean, last_var, last_n, weights=None): + """Compute incremental mean and variance along an axis on a CSR or CSC matrix. + + last_mean, last_var are the statistics computed at the last step by this + function. Both must be initialized to 0-arrays of the proper size, i.e. + the number of features in X. last_n is the number of samples encountered + until now. + + Parameters + ---------- + X : CSR or CSC sparse matrix of shape (n_samples, n_features) + Input data. + + axis : {0, 1} + Axis along which the axis should be computed. + + last_mean : ndarray of shape (n_features,) or (n_samples,), dtype=floating + Array of means to update with the new data X. + Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1. + + last_var : ndarray of shape (n_features,) or (n_samples,), dtype=floating + Array of variances to update with the new data X. + Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1. + + last_n : float or ndarray of shape (n_features,) or (n_samples,), \ + dtype=floating + Sum of the weights seen so far, excluding the current weights + If not float, it should be of shape (n_features,) if + axis=0 or (n_samples,) if axis=1. If float it corresponds to + having same weights for all samples (or features). + + weights : ndarray of shape (n_samples,) or (n_features,), default=None + If axis is set to 0 shape is (n_samples,) or + if axis is set to 1 shape is (n_features,). + If it is set to None, then samples are equally weighted. + + .. versionadded:: 0.24 + + Returns + ------- + means : ndarray of shape (n_features,) or (n_samples,), dtype=floating + Updated feature-wise means if axis = 0 or + sample-wise means if axis = 1. + + variances : ndarray of shape (n_features,) or (n_samples,), dtype=floating + Updated feature-wise variances if axis = 0 or + sample-wise variances if axis = 1. + + n : ndarray of shape (n_features,) or (n_samples,), dtype=integral + Updated number of seen samples per feature if axis=0 + or number of seen features per sample if axis=1. + + If weights is not None, n is a sum of the weights of the seen + samples or features instead of the actual number of seen + samples or features. + + Notes + ----- + NaNs are ignored in the algorithm. + + Examples + -------- + >>> from sklearn.utils import sparsefuncs + >>> from scipy import sparse + >>> import numpy as np + >>> indptr = np.array([0, 3, 4, 4, 4]) + >>> indices = np.array([0, 1, 2, 2]) + >>> data = np.array([8, 1, 2, 5]) + >>> scale = np.array([2, 3, 2]) + >>> csr = sparse.csr_matrix((data, indices, indptr)) + >>> csr.todense() + matrix([[8, 1, 2], + [0, 0, 5], + [0, 0, 0], + [0, 0, 0]]) + >>> sparsefuncs.incr_mean_variance_axis( + ... csr, axis=0, last_mean=np.zeros(3), last_var=np.zeros(3), last_n=2 + ... ) + (array([1.3..., 0.1..., 1.1...]), array([8.8..., 0.1..., 3.4...]), + array([6., 6., 6.])) + """ + _raise_error_wrong_axis(axis) + + if not (sp.issparse(X) and X.format in ("csc", "csr")): + _raise_typeerror(X) + + if np.size(last_n) == 1: + last_n = np.full(last_mean.shape, last_n, dtype=last_mean.dtype) + + if not (np.size(last_mean) == np.size(last_var) == np.size(last_n)): + raise ValueError("last_mean, last_var, last_n do not have the same shapes.") + + if axis == 1: + if np.size(last_mean) != X.shape[0]: + raise ValueError( + "If axis=1, then last_mean, last_n, last_var should be of " + f"size n_samples {X.shape[0]} (Got {np.size(last_mean)})." + ) + else: # axis == 0 + if np.size(last_mean) != X.shape[1]: + raise ValueError( + "If axis=0, then last_mean, last_n, last_var should be of " + f"size n_features {X.shape[1]} (Got {np.size(last_mean)})." + ) + + X = X.T if axis == 1 else X + + if weights is not None: + weights = _check_sample_weight(weights, X, dtype=X.dtype) + + return _incr_mean_var_axis0( + X, last_mean=last_mean, last_var=last_var, last_n=last_n, weights=weights + ) + + +def inplace_column_scale(X, scale): + """Inplace column scaling of a CSC/CSR matrix. + + Scale each feature of the data matrix by multiplying with specific scale + provided by the caller assuming a (n_samples, n_features) shape. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix to normalize using the variance of the features. It should be + of CSC or CSR format. + + scale : ndarray of shape (n_features,), dtype={np.float32, np.float64} + Array of precomputed feature-wise values to use for scaling. + + Examples + -------- + >>> from sklearn.utils import sparsefuncs + >>> from scipy import sparse + >>> import numpy as np + >>> indptr = np.array([0, 3, 4, 4, 4]) + >>> indices = np.array([0, 1, 2, 2]) + >>> data = np.array([8, 1, 2, 5]) + >>> scale = np.array([2, 3, 2]) + >>> csr = sparse.csr_matrix((data, indices, indptr)) + >>> csr.todense() + matrix([[8, 1, 2], + [0, 0, 5], + [0, 0, 0], + [0, 0, 0]]) + >>> sparsefuncs.inplace_column_scale(csr, scale) + >>> csr.todense() + matrix([[16, 3, 4], + [ 0, 0, 10], + [ 0, 0, 0], + [ 0, 0, 0]]) + """ + if sp.issparse(X) and X.format == "csc": + inplace_csr_row_scale(X.T, scale) + elif sp.issparse(X) and X.format == "csr": + inplace_csr_column_scale(X, scale) + else: + _raise_typeerror(X) + + +def inplace_row_scale(X, scale): + """Inplace row scaling of a CSR or CSC matrix. + + Scale each row of the data matrix by multiplying with specific scale + provided by the caller assuming a (n_samples, n_features) shape. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix to be scaled. It should be of CSR or CSC format. + + scale : ndarray of shape (n_features,), dtype={np.float32, np.float64} + Array of precomputed sample-wise values to use for scaling. + + Examples + -------- + >>> from sklearn.utils import sparsefuncs + >>> from scipy import sparse + >>> import numpy as np + >>> indptr = np.array([0, 2, 3, 4, 5]) + >>> indices = np.array([0, 1, 2, 3, 3]) + >>> data = np.array([8, 1, 2, 5, 6]) + >>> scale = np.array([2, 3, 4, 5]) + >>> csr = sparse.csr_matrix((data, indices, indptr)) + >>> csr.todense() + matrix([[8, 1, 0, 0], + [0, 0, 2, 0], + [0, 0, 0, 5], + [0, 0, 0, 6]]) + >>> sparsefuncs.inplace_row_scale(csr, scale) + >>> csr.todense() + matrix([[16, 2, 0, 0], + [ 0, 0, 6, 0], + [ 0, 0, 0, 20], + [ 0, 0, 0, 30]]) + """ + if sp.issparse(X) and X.format == "csc": + inplace_csr_column_scale(X.T, scale) + elif sp.issparse(X) and X.format == "csr": + inplace_csr_row_scale(X, scale) + else: + _raise_typeerror(X) + + +def inplace_swap_row_csc(X, m, n): + """Swap two rows of a CSC matrix in-place. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix whose two rows are to be swapped. It should be of + CSC format. + + m : int + Index of the row of X to be swapped. + + n : int + Index of the row of X to be swapped. + """ + for t in [m, n]: + if isinstance(t, np.ndarray): + raise TypeError("m and n should be valid integers") + + if m < 0: + m += X.shape[0] + if n < 0: + n += X.shape[0] + + m_mask = X.indices == m + X.indices[X.indices == n] = m + X.indices[m_mask] = n + + +def inplace_swap_row_csr(X, m, n): + """Swap two rows of a CSR matrix in-place. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix whose two rows are to be swapped. It should be of + CSR format. + + m : int + Index of the row of X to be swapped. + + n : int + Index of the row of X to be swapped. + """ + for t in [m, n]: + if isinstance(t, np.ndarray): + raise TypeError("m and n should be valid integers") + + if m < 0: + m += X.shape[0] + if n < 0: + n += X.shape[0] + + # The following swapping makes life easier since m is assumed to be the + # smaller integer below. + if m > n: + m, n = n, m + + indptr = X.indptr + m_start = indptr[m] + m_stop = indptr[m + 1] + n_start = indptr[n] + n_stop = indptr[n + 1] + nz_m = m_stop - m_start + nz_n = n_stop - n_start + + if nz_m != nz_n: + # Modify indptr first + X.indptr[m + 2 : n] += nz_n - nz_m + X.indptr[m + 1] = m_start + nz_n + X.indptr[n] = n_stop - nz_m + + X.indices = np.concatenate( + [ + X.indices[:m_start], + X.indices[n_start:n_stop], + X.indices[m_stop:n_start], + X.indices[m_start:m_stop], + X.indices[n_stop:], + ] + ) + X.data = np.concatenate( + [ + X.data[:m_start], + X.data[n_start:n_stop], + X.data[m_stop:n_start], + X.data[m_start:m_stop], + X.data[n_stop:], + ] + ) + + +def inplace_swap_row(X, m, n): + """ + Swap two rows of a CSC/CSR matrix in-place. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix whose two rows are to be swapped. It should be of CSR or + CSC format. + + m : int + Index of the row of X to be swapped. + + n : int + Index of the row of X to be swapped. + + Examples + -------- + >>> from sklearn.utils import sparsefuncs + >>> from scipy import sparse + >>> import numpy as np + >>> indptr = np.array([0, 2, 3, 3, 3]) + >>> indices = np.array([0, 2, 2]) + >>> data = np.array([8, 2, 5]) + >>> csr = sparse.csr_matrix((data, indices, indptr)) + >>> csr.todense() + matrix([[8, 0, 2], + [0, 0, 5], + [0, 0, 0], + [0, 0, 0]]) + >>> sparsefuncs.inplace_swap_row(csr, 0, 1) + >>> csr.todense() + matrix([[0, 0, 5], + [8, 0, 2], + [0, 0, 0], + [0, 0, 0]]) + """ + if sp.issparse(X) and X.format == "csc": + inplace_swap_row_csc(X, m, n) + elif sp.issparse(X) and X.format == "csr": + inplace_swap_row_csr(X, m, n) + else: + _raise_typeerror(X) + + +def inplace_swap_column(X, m, n): + """ + Swap two columns of a CSC/CSR matrix in-place. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix whose two columns are to be swapped. It should be of + CSR or CSC format. + + m : int + Index of the column of X to be swapped. + + n : int + Index of the column of X to be swapped. + + Examples + -------- + >>> from sklearn.utils import sparsefuncs + >>> from scipy import sparse + >>> import numpy as np + >>> indptr = np.array([0, 2, 3, 3, 3]) + >>> indices = np.array([0, 2, 2]) + >>> data = np.array([8, 2, 5]) + >>> csr = sparse.csr_matrix((data, indices, indptr)) + >>> csr.todense() + matrix([[8, 0, 2], + [0, 0, 5], + [0, 0, 0], + [0, 0, 0]]) + >>> sparsefuncs.inplace_swap_column(csr, 0, 1) + >>> csr.todense() + matrix([[0, 8, 2], + [0, 0, 5], + [0, 0, 0], + [0, 0, 0]]) + """ + if m < 0: + m += X.shape[1] + if n < 0: + n += X.shape[1] + if sp.issparse(X) and X.format == "csc": + inplace_swap_row_csr(X, m, n) + elif sp.issparse(X) and X.format == "csr": + inplace_swap_row_csc(X, m, n) + else: + _raise_typeerror(X) + + +def min_max_axis(X, axis, ignore_nan=False): + """Compute minimum and maximum along an axis on a CSR or CSC matrix. + + Optionally ignore NaN values. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Input data. It should be of CSR or CSC format. + + axis : {0, 1} + Axis along which the axis should be computed. + + ignore_nan : bool, default=False + Ignore or passing through NaN values. + + .. versionadded:: 0.20 + + Returns + ------- + + mins : ndarray of shape (n_features,), dtype={np.float32, np.float64} + Feature-wise minima. + + maxs : ndarray of shape (n_features,), dtype={np.float32, np.float64} + Feature-wise maxima. + """ + if sp.issparse(X) and X.format in ("csr", "csc"): + if ignore_nan: + return _sparse_nan_min_max(X, axis=axis) + else: + return _sparse_min_max(X, axis=axis) + else: + _raise_typeerror(X) + + +def count_nonzero(X, axis=None, sample_weight=None): + """A variant of X.getnnz() with extension to weighting on axis 0. + + Useful in efficiently calculating multilabel metrics. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_labels) + Input data. It should be of CSR format. + + axis : {0, 1}, default=None + The axis on which the data is aggregated. + + sample_weight : array-like of shape (n_samples,), default=None + Weight for each row of X. + + Returns + ------- + nnz : int, float, ndarray of shape (n_samples,) or ndarray of shape (n_features,) + Number of non-zero values in the array along a given axis. Otherwise, + the total number of non-zero values in the array is returned. + """ + if axis == -1: + axis = 1 + elif axis == -2: + axis = 0 + elif X.format != "csr": + raise TypeError("Expected CSR sparse format, got {0}".format(X.format)) + + # We rely here on the fact that np.diff(Y.indptr) for a CSR + # will return the number of nonzero entries in each row. + # A bincount over Y.indices will return the number of nonzeros + # in each column. See ``csr_matrix.getnnz`` in scipy >= 0.14. + if axis is None: + if sample_weight is None: + return X.nnz + else: + return np.dot(np.diff(X.indptr), sample_weight) + elif axis == 1: + out = np.diff(X.indptr) + if sample_weight is None: + # astype here is for consistency with axis=0 dtype + return out.astype("intp") + return out * sample_weight + elif axis == 0: + if sample_weight is None: + return np.bincount(X.indices, minlength=X.shape[1]) + else: + weights = np.repeat(sample_weight, np.diff(X.indptr)) + return np.bincount(X.indices, minlength=X.shape[1], weights=weights) + else: + raise ValueError("Unsupported axis: {0}".format(axis)) + + +def _get_median(data, n_zeros): + """Compute the median of data with n_zeros additional zeros. + + This function is used to support sparse matrices; it modifies data + in-place. + """ + n_elems = len(data) + n_zeros + if not n_elems: + return np.nan + n_negative = np.count_nonzero(data < 0) + middle, is_odd = divmod(n_elems, 2) + data.sort() + + if is_odd: + return _get_elem_at_rank(middle, data, n_negative, n_zeros) + + return ( + _get_elem_at_rank(middle - 1, data, n_negative, n_zeros) + + _get_elem_at_rank(middle, data, n_negative, n_zeros) + ) / 2.0 + + +def _get_elem_at_rank(rank, data, n_negative, n_zeros): + """Find the value in data augmented with n_zeros for the given rank""" + if rank < n_negative: + return data[rank] + if rank - n_negative < n_zeros: + return 0 + return data[rank - n_zeros] + + +def csc_median_axis_0(X): + """Find the median across axis 0 of a CSC matrix. + + It is equivalent to doing np.median(X, axis=0). + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Input data. It should be of CSC format. + + Returns + ------- + median : ndarray of shape (n_features,) + Median. + """ + if not (sp.issparse(X) and X.format == "csc"): + raise TypeError("Expected matrix of CSC format, got %s" % X.format) + + indptr = X.indptr + n_samples, n_features = X.shape + median = np.zeros(n_features) + + for f_ind, (start, end) in enumerate(zip(indptr[:-1], indptr[1:])): + # Prevent modifying X in place + data = np.copy(X.data[start:end]) + nz = n_samples - data.size + median[f_ind] = _get_median(data, nz) + + return median + + +def _implicit_column_offset(X, offset): + """Create an implicitly offset linear operator. + + This is used by PCA on sparse data to avoid densifying the whole data + matrix. + + Params + ------ + X : sparse matrix of shape (n_samples, n_features) + offset : ndarray of shape (n_features,) + + Returns + ------- + centered : LinearOperator + """ + offset = offset[None, :] + XT = X.T + return LinearOperator( + matvec=lambda x: X @ x - offset @ x, + matmat=lambda x: X @ x - offset @ x, + rmatvec=lambda x: XT @ x - (offset * x.sum()), + rmatmat=lambda x: XT @ x - offset.T @ x.sum(axis=0)[None, :], + dtype=X.dtype, + shape=X.shape, + ) diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/sparsefuncs_fast.cpython-310-x86_64-linux-gnu.so b/venv/lib/python3.10/site-packages/sklearn/utils/sparsefuncs_fast.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..47afe02937a1f316299331a4138f2add8702eb66 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/sparsefuncs_fast.cpython-310-x86_64-linux-gnu.so differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/stats.py b/venv/lib/python3.10/site-packages/sklearn/utils/stats.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e22ea3694f47a89f4c55f9da1dafdc9f54b815 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/stats.py @@ -0,0 +1,69 @@ +import numpy as np + +from .extmath import stable_cumsum + + +def _weighted_percentile(array, sample_weight, percentile=50): + """Compute weighted percentile + + Computes lower weighted percentile. If `array` is a 2D array, the + `percentile` is computed along the axis 0. + + .. versionchanged:: 0.24 + Accepts 2D `array`. + + Parameters + ---------- + array : 1D or 2D array + Values to take the weighted percentile of. + + sample_weight: 1D or 2D array + Weights for each value in `array`. Must be same shape as `array` or + of shape `(array.shape[0],)`. + + percentile: int or float, default=50 + Percentile to compute. Must be value between 0 and 100. + + Returns + ------- + percentile : int if `array` 1D, ndarray if `array` 2D + Weighted percentile. + """ + n_dim = array.ndim + if n_dim == 0: + return array[()] + if array.ndim == 1: + array = array.reshape((-1, 1)) + # When sample_weight 1D, repeat for each array.shape[1] + if array.shape != sample_weight.shape and array.shape[0] == sample_weight.shape[0]: + sample_weight = np.tile(sample_weight, (array.shape[1], 1)).T + sorted_idx = np.argsort(array, axis=0) + sorted_weights = np.take_along_axis(sample_weight, sorted_idx, axis=0) + + # Find index of median prediction for each sample + weight_cdf = stable_cumsum(sorted_weights, axis=0) + adjusted_percentile = percentile / 100 * weight_cdf[-1] + + # For percentile=0, ignore leading observations with sample_weight=0. GH20528 + mask = adjusted_percentile == 0 + adjusted_percentile[mask] = np.nextafter( + adjusted_percentile[mask], adjusted_percentile[mask] + 1 + ) + + percentile_idx = np.array( + [ + np.searchsorted(weight_cdf[:, i], adjusted_percentile[i]) + for i in range(weight_cdf.shape[1]) + ] + ) + percentile_idx = np.array(percentile_idx) + # In rare cases, percentile_idx equals to sorted_idx.shape[0] + max_idx = sorted_idx.shape[0] - 1 + percentile_idx = np.apply_along_axis( + lambda x: np.clip(x, 0, max_idx), axis=0, arr=percentile_idx + ) + + col_index = np.arange(array.shape[1]) + percentile_in_sorted = sorted_idx[percentile_idx, col_index] + percentile = array[percentile_in_sorted, col_index] + return percentile[0] if n_dim == 1 else percentile diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/__init__.py b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_bunch.cpython-310.pyc b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_bunch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95eab01b6b5a74a5bf3f9021972913f9d97a2af0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_bunch.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a09a890ba89c470e5e3eced35c524ad61f197fa Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_multiclass.cpython-310.pyc b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_multiclass.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e085e585e05008893919b939523fa4365fd64f4 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_multiclass.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e7819f99d146d18a82b910a2739bd48ccec8b80 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_param_validation.cpython-310.pyc b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_param_validation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63e52f48851caef3279e87b6c5bef16cc775cb38 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_param_validation.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_plotting.cpython-310.pyc b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_plotting.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eedbbd9e6299a201dda1f9d1e40e146431477e87 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_plotting.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_seq_dataset.cpython-310.pyc b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_seq_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a68d50cfd9349e5e90c110fe38cac2dd6a08e5be Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_seq_dataset.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_show_versions.cpython-310.pyc b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_show_versions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3ade03c64b25afd1843dd93db3e01453a4a45c6 Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_show_versions.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_stats.cpython-310.pyc b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_stats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15430befa5c308c14a6ad4ceb9c5a0fe0381320f Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_stats.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_weight_vector.cpython-310.pyc b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_weight_vector.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4b2b1d08e5424fc6736de4b1587ade9e209335a Binary files /dev/null and b/venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_weight_vector.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_arpack.py b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_arpack.py new file mode 100644 index 0000000000000000000000000000000000000000..ab1d622d51a08eca5ecf526b77d1bbeab17737f6 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_arpack.py @@ -0,0 +1,16 @@ +import pytest +from numpy.testing import assert_allclose + +from sklearn.utils import check_random_state +from sklearn.utils._arpack import _init_arpack_v0 + + +@pytest.mark.parametrize("seed", range(100)) +def test_init_arpack_v0(seed): + # check that the initialization a sampling from an uniform distribution + # where we can fix the random state + size = 1000 + v0 = _init_arpack_v0(size, seed) + + rng = check_random_state(seed) + assert_allclose(v0, rng.uniform(-1, 1, size=size)) diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_array_api.py b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_array_api.py new file mode 100644 index 0000000000000000000000000000000000000000..1df81cf823bd696703712ab7e2713cfa54b6f510 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_array_api.py @@ -0,0 +1,331 @@ +from functools import partial + +import numpy +import pytest +from numpy.testing import assert_allclose + +from sklearn._config import config_context +from sklearn.base import BaseEstimator +from sklearn.utils._array_api import ( + _ArrayAPIWrapper, + _asarray_with_order, + _atol_for_type, + _convert_to_numpy, + _estimator_with_converted_arrays, + _nanmax, + _nanmin, + _NumPyAPIWrapper, + _weighted_sum, + get_namespace, + supported_float_dtypes, + yield_namespace_device_dtype_combinations, +) +from sklearn.utils._testing import ( + _array_api_for_tests, + skip_if_array_api_compat_not_configured, +) + +pytestmark = pytest.mark.filterwarnings( + "ignore:The numpy.array_api submodule:UserWarning" +) + + +@pytest.mark.parametrize("X", [numpy.asarray([1, 2, 3]), [1, 2, 3]]) +def test_get_namespace_ndarray_default(X): + """Check that get_namespace returns NumPy wrapper""" + xp_out, is_array_api_compliant = get_namespace(X) + assert isinstance(xp_out, _NumPyAPIWrapper) + assert not is_array_api_compliant + + +def test_get_namespace_ndarray_creation_device(): + """Check expected behavior with device and creation functions.""" + X = numpy.asarray([1, 2, 3]) + xp_out, _ = get_namespace(X) + + full_array = xp_out.full(10, fill_value=2.0, device="cpu") + assert_allclose(full_array, [2.0] * 10) + + with pytest.raises(ValueError, match="Unsupported device"): + xp_out.zeros(10, device="cuda") + + +@skip_if_array_api_compat_not_configured +def test_get_namespace_ndarray_with_dispatch(): + """Test get_namespace on NumPy ndarrays.""" + array_api_compat = pytest.importorskip("array_api_compat") + + X_np = numpy.asarray([[1, 2, 3]]) + + with config_context(array_api_dispatch=True): + xp_out, is_array_api_compliant = get_namespace(X_np) + assert is_array_api_compliant + assert xp_out is array_api_compat.numpy + + +@skip_if_array_api_compat_not_configured +def test_get_namespace_array_api(): + """Test get_namespace for ArrayAPI arrays.""" + xp = pytest.importorskip("numpy.array_api") + + X_np = numpy.asarray([[1, 2, 3]]) + X_xp = xp.asarray(X_np) + with config_context(array_api_dispatch=True): + xp_out, is_array_api_compliant = get_namespace(X_xp) + assert is_array_api_compliant + assert isinstance(xp_out, _ArrayAPIWrapper) + + with pytest.raises(TypeError): + xp_out, is_array_api_compliant = get_namespace(X_xp, X_np) + + +class _AdjustableNameAPITestWrapper(_ArrayAPIWrapper): + """API wrapper that has an adjustable name. Used for testing.""" + + def __init__(self, array_namespace, name): + super().__init__(array_namespace=array_namespace) + self.__name__ = name + + +def test_array_api_wrapper_astype(): + """Test _ArrayAPIWrapper for ArrayAPIs that is not NumPy.""" + numpy_array_api = pytest.importorskip("numpy.array_api") + xp_ = _AdjustableNameAPITestWrapper(numpy_array_api, "wrapped_numpy.array_api") + xp = _ArrayAPIWrapper(xp_) + + X = xp.asarray(([[1, 2, 3], [3, 4, 5]]), dtype=xp.float64) + X_converted = xp.astype(X, xp.float32) + assert X_converted.dtype == xp.float32 + + X_converted = xp.asarray(X, dtype=xp.float32) + assert X_converted.dtype == xp.float32 + + +@pytest.mark.parametrize("array_api", ["numpy", "numpy.array_api"]) +def test_asarray_with_order(array_api): + """Test _asarray_with_order passes along order for NumPy arrays.""" + xp = pytest.importorskip(array_api) + + X = xp.asarray([1.2, 3.4, 5.1]) + X_new = _asarray_with_order(X, order="F", xp=xp) + + X_new_np = numpy.asarray(X_new) + assert X_new_np.flags["F_CONTIGUOUS"] + + +def test_asarray_with_order_ignored(): + """Test _asarray_with_order ignores order for Generic ArrayAPI.""" + xp = pytest.importorskip("numpy.array_api") + xp_ = _AdjustableNameAPITestWrapper(xp, "wrapped.array_api") + + X = numpy.asarray([[1.2, 3.4, 5.1], [3.4, 5.5, 1.2]], order="C") + X = xp_.asarray(X) + + X_new = _asarray_with_order(X, order="F", xp=xp_) + + X_new_np = numpy.asarray(X_new) + assert X_new_np.flags["C_CONTIGUOUS"] + assert not X_new_np.flags["F_CONTIGUOUS"] + + +@pytest.mark.parametrize( + "array_namespace, device, dtype_name", yield_namespace_device_dtype_combinations() +) +@pytest.mark.parametrize( + "sample_weight, normalize, expected", + [ + (None, False, 10.0), + (None, True, 2.5), + ([0.4, 0.4, 0.5, 0.7], False, 5.5), + ([0.4, 0.4, 0.5, 0.7], True, 2.75), + ([1, 2, 3, 4], False, 30.0), + ([1, 2, 3, 4], True, 3.0), + ], +) +def test_weighted_sum( + array_namespace, device, dtype_name, sample_weight, normalize, expected +): + xp = _array_api_for_tests(array_namespace, device) + sample_score = numpy.asarray([1, 2, 3, 4], dtype=dtype_name) + sample_score = xp.asarray(sample_score, device=device) + if sample_weight is not None: + sample_weight = numpy.asarray(sample_weight, dtype=dtype_name) + sample_weight = xp.asarray(sample_weight, device=device) + + with config_context(array_api_dispatch=True): + result = _weighted_sum(sample_score, sample_weight, normalize) + + assert isinstance(result, float) + assert_allclose(result, expected, atol=_atol_for_type(dtype_name)) + + +@skip_if_array_api_compat_not_configured +@pytest.mark.parametrize( + "library", ["numpy", "numpy.array_api", "cupy", "cupy.array_api", "torch"] +) +@pytest.mark.parametrize( + "X,reduction,expected", + [ + ([1, 2, numpy.nan], _nanmin, 1), + ([1, -2, -numpy.nan], _nanmin, -2), + ([numpy.inf, numpy.inf], _nanmin, numpy.inf), + ( + [[1, 2, 3], [numpy.nan, numpy.nan, numpy.nan], [4, 5, 6.0]], + partial(_nanmin, axis=0), + [1.0, 2.0, 3.0], + ), + ( + [[1, 2, 3], [numpy.nan, numpy.nan, numpy.nan], [4, 5, 6.0]], + partial(_nanmin, axis=1), + [1.0, numpy.nan, 4.0], + ), + ([1, 2, numpy.nan], _nanmax, 2), + ([1, 2, numpy.nan], _nanmax, 2), + ([-numpy.inf, -numpy.inf], _nanmax, -numpy.inf), + ( + [[1, 2, 3], [numpy.nan, numpy.nan, numpy.nan], [4, 5, 6.0]], + partial(_nanmax, axis=0), + [4.0, 5.0, 6.0], + ), + ( + [[1, 2, 3], [numpy.nan, numpy.nan, numpy.nan], [4, 5, 6.0]], + partial(_nanmax, axis=1), + [3.0, numpy.nan, 6.0], + ), + ], +) +def test_nan_reductions(library, X, reduction, expected): + """Check NaN reductions like _nanmin and _nanmax""" + xp = pytest.importorskip(library) + + if isinstance(expected, list): + expected = xp.asarray(expected) + + with config_context(array_api_dispatch=True): + result = reduction(xp.asarray(X)) + + assert_allclose(result, expected) + + +@skip_if_array_api_compat_not_configured +@pytest.mark.parametrize("library", ["cupy", "torch", "cupy.array_api"]) +def test_convert_to_numpy_gpu(library): # pragma: nocover + """Check convert_to_numpy for GPU backed libraries.""" + xp = pytest.importorskip(library) + + if library == "torch": + if not xp.backends.cuda.is_built(): + pytest.skip("test requires cuda") + X_gpu = xp.asarray([1.0, 2.0, 3.0], device="cuda") + else: + X_gpu = xp.asarray([1.0, 2.0, 3.0]) + + X_cpu = _convert_to_numpy(X_gpu, xp=xp) + expected_output = numpy.asarray([1.0, 2.0, 3.0]) + assert_allclose(X_cpu, expected_output) + + +def test_convert_to_numpy_cpu(): + """Check convert_to_numpy for PyTorch CPU arrays.""" + torch = pytest.importorskip("torch") + X_torch = torch.asarray([1.0, 2.0, 3.0], device="cpu") + + X_cpu = _convert_to_numpy(X_torch, xp=torch) + expected_output = numpy.asarray([1.0, 2.0, 3.0]) + assert_allclose(X_cpu, expected_output) + + +class SimpleEstimator(BaseEstimator): + def fit(self, X, y=None): + self.X_ = X + self.n_features_ = X.shape[0] + return self + + +@skip_if_array_api_compat_not_configured +@pytest.mark.parametrize( + "array_namespace, converter", + [ + ("torch", lambda array: array.cpu().numpy()), + ("numpy.array_api", lambda array: numpy.asarray(array)), + ("cupy.array_api", lambda array: array._array.get()), + ], +) +def test_convert_estimator_to_ndarray(array_namespace, converter): + """Convert estimator attributes to ndarray.""" + xp = pytest.importorskip(array_namespace) + + X = xp.asarray([[1.3, 4.5]]) + est = SimpleEstimator().fit(X) + + new_est = _estimator_with_converted_arrays(est, converter) + assert isinstance(new_est.X_, numpy.ndarray) + + +@skip_if_array_api_compat_not_configured +def test_convert_estimator_to_array_api(): + """Convert estimator attributes to ArrayAPI arrays.""" + xp = pytest.importorskip("numpy.array_api") + + X_np = numpy.asarray([[1.3, 4.5]]) + est = SimpleEstimator().fit(X_np) + + new_est = _estimator_with_converted_arrays(est, lambda array: xp.asarray(array)) + assert hasattr(new_est.X_, "__array_namespace__") + + +def test_reshape_behavior(): + """Check reshape behavior with copy and is strict with non-tuple shape.""" + xp = _NumPyAPIWrapper() + X = xp.asarray([[1, 2, 3], [3, 4, 5]]) + + X_no_copy = xp.reshape(X, (-1,), copy=False) + assert X_no_copy.base is X + + X_copy = xp.reshape(X, (6, 1), copy=True) + assert X_copy.base is not X.base + + with pytest.raises(TypeError, match="shape must be a tuple"): + xp.reshape(X, -1) + + +@pytest.mark.parametrize("wrapper", [_ArrayAPIWrapper, _NumPyAPIWrapper]) +def test_get_namespace_array_api_isdtype(wrapper): + """Test isdtype implementation from _ArrayAPIWrapper and _NumPyAPIWrapper.""" + + if wrapper == _ArrayAPIWrapper: + xp_ = pytest.importorskip("numpy.array_api") + xp = _ArrayAPIWrapper(xp_) + else: + xp = _NumPyAPIWrapper() + + assert xp.isdtype(xp.float32, xp.float32) + assert xp.isdtype(xp.float32, "real floating") + assert xp.isdtype(xp.float64, "real floating") + assert not xp.isdtype(xp.int32, "real floating") + + for dtype in supported_float_dtypes(xp): + assert xp.isdtype(dtype, "real floating") + + assert xp.isdtype(xp.bool, "bool") + assert not xp.isdtype(xp.float32, "bool") + + assert xp.isdtype(xp.int16, "signed integer") + assert not xp.isdtype(xp.uint32, "signed integer") + + assert xp.isdtype(xp.uint16, "unsigned integer") + assert not xp.isdtype(xp.int64, "unsigned integer") + + assert xp.isdtype(xp.int64, "numeric") + assert xp.isdtype(xp.float32, "numeric") + assert xp.isdtype(xp.uint32, "numeric") + + assert not xp.isdtype(xp.float32, "complex floating") + + if wrapper == _NumPyAPIWrapper: + assert not xp.isdtype(xp.int8, "complex floating") + assert xp.isdtype(xp.complex64, "complex floating") + assert xp.isdtype(xp.complex128, "complex floating") + + with pytest.raises(ValueError, match="Unrecognized data type"): + assert xp.isdtype(xp.int16, "unknown") diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_arrayfuncs.py b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_arrayfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..4a80a4c1edefd9df99eeed570133998a27e985d9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_arrayfuncs.py @@ -0,0 +1,38 @@ +import numpy as np +import pytest + +from sklearn.utils._testing import assert_allclose +from sklearn.utils.arrayfuncs import _all_with_any_reduction_axis_1, min_pos + + +def test_min_pos(): + # Check that min_pos returns a positive value and that it's consistent + # between float and double + X = np.random.RandomState(0).randn(100) + + min_double = min_pos(X) + min_float = min_pos(X.astype(np.float32)) + + assert_allclose(min_double, min_float) + assert min_double >= 0 + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_min_pos_no_positive(dtype): + # Check that the return value of min_pos is the maximum representable + # value of the input dtype when all input elements are <= 0 (#19328) + X = np.full(100, -1.0).astype(dtype, copy=False) + + assert min_pos(X) == np.finfo(dtype).max + + +@pytest.mark.parametrize("dtype", [np.int16, np.int32, np.float32, np.float64]) +@pytest.mark.parametrize("value", [0, 1.5, -1]) +def test_all_with_any_reduction_axis_1(dtype, value): + # Check that return value is False when there is no row equal to `value` + X = np.arange(12, dtype=dtype).reshape(3, 4) + assert not _all_with_any_reduction_axis_1(X, value=value) + + # Make a row equal to `value` + X[1, :] = value + assert _all_with_any_reduction_axis_1(X, value=value) diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_bunch.py b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_bunch.py new file mode 100644 index 0000000000000000000000000000000000000000..15463475747f4229ed7ab320d8f5be8005f9cf0a --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_bunch.py @@ -0,0 +1,32 @@ +import warnings + +import numpy as np +import pytest + +from sklearn.utils import Bunch + + +def test_bunch_attribute_deprecation(): + """Check that bunch raises deprecation message with `__getattr__`.""" + bunch = Bunch() + values = np.asarray([1, 2, 3]) + msg = ( + "Key: 'values', is deprecated in 1.3 and will be " + "removed in 1.5. Please use 'grid_values' instead" + ) + bunch._set_deprecated( + values, new_key="grid_values", deprecated_key="values", warning_message=msg + ) + + with warnings.catch_warnings(): + # Does not warn for "grid_values" + warnings.simplefilter("error") + v = bunch["grid_values"] + + assert v is values + + with pytest.warns(FutureWarning, match=msg): + # Warns for "values" + v = bunch["values"] + + assert v is values diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_class_weight.py b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_class_weight.py new file mode 100644 index 0000000000000000000000000000000000000000..b98ce6be056584697da799e4dbe631c1845cff1d --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_class_weight.py @@ -0,0 +1,316 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose + +from sklearn.datasets import make_blobs +from sklearn.linear_model import LogisticRegression +from sklearn.tree import DecisionTreeClassifier +from sklearn.utils._testing import assert_almost_equal, assert_array_almost_equal +from sklearn.utils.class_weight import compute_class_weight, compute_sample_weight +from sklearn.utils.fixes import CSC_CONTAINERS + + +def test_compute_class_weight(): + # Test (and demo) compute_class_weight. + y = np.asarray([2, 2, 2, 3, 3, 4]) + classes = np.unique(y) + + cw = compute_class_weight("balanced", classes=classes, y=y) + # total effect of samples is preserved + class_counts = np.bincount(y)[2:] + assert_almost_equal(np.dot(cw, class_counts), y.shape[0]) + assert cw[0] < cw[1] < cw[2] + + +@pytest.mark.parametrize( + "y_type, class_weight, classes, err_msg", + [ + ( + "numeric", + "balanced", + np.arange(4), + "classes should have valid labels that are in y", + ), + # Non-regression for https://github.com/scikit-learn/scikit-learn/issues/8312 + ( + "numeric", + {"label_not_present": 1.0}, + np.arange(4), + r"The classes, \[0, 1, 2, 3\], are not in class_weight", + ), + ( + "numeric", + "balanced", + np.arange(2), + "classes should include all valid labels", + ), + ( + "numeric", + {0: 1.0, 1: 2.0}, + np.arange(2), + "classes should include all valid labels", + ), + ( + "string", + {"dogs": 3, "cat": 2}, + np.array(["dog", "cat"]), + r"The classes, \['dog'\], are not in class_weight", + ), + ], +) +def test_compute_class_weight_not_present(y_type, class_weight, classes, err_msg): + # Raise error when y does not contain all class labels + y = ( + np.asarray([0, 0, 0, 1, 1, 2]) + if y_type == "numeric" + else np.asarray(["dog", "cat", "dog"]) + ) + + print(y) + with pytest.raises(ValueError, match=err_msg): + compute_class_weight(class_weight, classes=classes, y=y) + + +def test_compute_class_weight_dict(): + classes = np.arange(3) + class_weights = {0: 1.0, 1: 2.0, 2: 3.0} + y = np.asarray([0, 0, 1, 2]) + cw = compute_class_weight(class_weights, classes=classes, y=y) + + # When the user specifies class weights, compute_class_weights should just + # return them. + assert_array_almost_equal(np.asarray([1.0, 2.0, 3.0]), cw) + + # When a class weight is specified that isn't in classes, the weight is ignored + class_weights = {0: 1.0, 1: 2.0, 2: 3.0, 4: 1.5} + cw = compute_class_weight(class_weights, classes=classes, y=y) + assert_allclose([1.0, 2.0, 3.0], cw) + + class_weights = {-1: 5.0, 0: 4.0, 1: 2.0, 2: 3.0} + cw = compute_class_weight(class_weights, classes=classes, y=y) + assert_allclose([4.0, 2.0, 3.0], cw) + + +def test_compute_class_weight_invariance(): + # Test that results with class_weight="balanced" is invariant wrt + # class imbalance if the number of samples is identical. + # The test uses a balanced two class dataset with 100 datapoints. + # It creates three versions, one where class 1 is duplicated + # resulting in 150 points of class 1 and 50 of class 0, + # one where there are 50 points in class 1 and 150 in class 0, + # and one where there are 100 points of each class (this one is balanced + # again). + # With balancing class weights, all three should give the same model. + X, y = make_blobs(centers=2, random_state=0) + # create dataset where class 1 is duplicated twice + X_1 = np.vstack([X] + [X[y == 1]] * 2) + y_1 = np.hstack([y] + [y[y == 1]] * 2) + # create dataset where class 0 is duplicated twice + X_0 = np.vstack([X] + [X[y == 0]] * 2) + y_0 = np.hstack([y] + [y[y == 0]] * 2) + # duplicate everything + X_ = np.vstack([X] * 2) + y_ = np.hstack([y] * 2) + # results should be identical + logreg1 = LogisticRegression(class_weight="balanced").fit(X_1, y_1) + logreg0 = LogisticRegression(class_weight="balanced").fit(X_0, y_0) + logreg = LogisticRegression(class_weight="balanced").fit(X_, y_) + assert_array_almost_equal(logreg1.coef_, logreg0.coef_) + assert_array_almost_equal(logreg.coef_, logreg0.coef_) + + +def test_compute_class_weight_balanced_negative(): + # Test compute_class_weight when labels are negative + # Test with balanced class labels. + classes = np.array([-2, -1, 0]) + y = np.asarray([-1, -1, 0, 0, -2, -2]) + + cw = compute_class_weight("balanced", classes=classes, y=y) + assert len(cw) == len(classes) + assert_array_almost_equal(cw, np.array([1.0, 1.0, 1.0])) + + # Test with unbalanced class labels. + y = np.asarray([-1, 0, 0, -2, -2, -2]) + + cw = compute_class_weight("balanced", classes=classes, y=y) + assert len(cw) == len(classes) + class_counts = np.bincount(y + 2) + assert_almost_equal(np.dot(cw, class_counts), y.shape[0]) + assert_array_almost_equal(cw, [2.0 / 3, 2.0, 1.0]) + + +def test_compute_class_weight_balanced_unordered(): + # Test compute_class_weight when classes are unordered + classes = np.array([1, 0, 3]) + y = np.asarray([1, 0, 0, 3, 3, 3]) + + cw = compute_class_weight("balanced", classes=classes, y=y) + class_counts = np.bincount(y)[classes] + assert_almost_equal(np.dot(cw, class_counts), y.shape[0]) + assert_array_almost_equal(cw, [2.0, 1.0, 2.0 / 3]) + + +def test_compute_class_weight_default(): + # Test for the case where no weight is given for a present class. + # Current behaviour is to assign the unweighted classes a weight of 1. + y = np.asarray([2, 2, 2, 3, 3, 4]) + classes = np.unique(y) + classes_len = len(classes) + + # Test for non specified weights + cw = compute_class_weight(None, classes=classes, y=y) + assert len(cw) == classes_len + assert_array_almost_equal(cw, np.ones(3)) + + # Tests for partly specified weights + cw = compute_class_weight({2: 1.5}, classes=classes, y=y) + assert len(cw) == classes_len + assert_array_almost_equal(cw, [1.5, 1.0, 1.0]) + + cw = compute_class_weight({2: 1.5, 4: 0.5}, classes=classes, y=y) + assert len(cw) == classes_len + assert_array_almost_equal(cw, [1.5, 1.0, 0.5]) + + +def test_compute_sample_weight(): + # Test (and demo) compute_sample_weight. + # Test with balanced classes + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("balanced", y) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with user-defined weights + sample_weight = compute_sample_weight({1: 2, 2: 1}, y) + assert_array_almost_equal(sample_weight, [2.0, 2.0, 2.0, 1.0, 1.0, 1.0]) + + # Test with column vector of balanced classes + y = np.asarray([[1], [1], [1], [2], [2], [2]]) + sample_weight = compute_sample_weight("balanced", y) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with unbalanced classes + y = np.asarray([1, 1, 1, 2, 2, 2, 3]) + sample_weight = compute_sample_weight("balanced", y) + expected_balanced = np.array( + [0.7777, 0.7777, 0.7777, 0.7777, 0.7777, 0.7777, 2.3333] + ) + assert_array_almost_equal(sample_weight, expected_balanced, decimal=4) + + # Test with `None` weights + sample_weight = compute_sample_weight(None, y) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with multi-output of balanced classes + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + sample_weight = compute_sample_weight("balanced", y) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with multi-output with user-defined weights + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + sample_weight = compute_sample_weight([{1: 2, 2: 1}, {0: 1, 1: 2}], y) + assert_array_almost_equal(sample_weight, [2.0, 2.0, 2.0, 2.0, 2.0, 2.0]) + + # Test with multi-output of unbalanced classes + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [3, -1]]) + sample_weight = compute_sample_weight("balanced", y) + assert_array_almost_equal(sample_weight, expected_balanced**2, decimal=3) + + +def test_compute_sample_weight_with_subsample(): + # Test compute_sample_weight with subsamples specified. + # Test with balanced classes and all samples present + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("balanced", y, indices=range(6)) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with column vector of balanced classes and all samples present + y = np.asarray([[1], [1], [1], [2], [2], [2]]) + sample_weight = compute_sample_weight("balanced", y, indices=range(6)) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with a subsample + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("balanced", y, indices=range(4)) + assert_array_almost_equal(sample_weight, [2.0 / 3, 2.0 / 3, 2.0 / 3, 2.0, 2.0, 2.0]) + + # Test with a bootstrap subsample + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("balanced", y, indices=[0, 1, 1, 2, 2, 3]) + expected_balanced = np.asarray([0.6, 0.6, 0.6, 3.0, 3.0, 3.0]) + assert_array_almost_equal(sample_weight, expected_balanced) + + # Test with a bootstrap subsample for multi-output + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + sample_weight = compute_sample_weight("balanced", y, indices=[0, 1, 1, 2, 2, 3]) + assert_array_almost_equal(sample_weight, expected_balanced**2) + + # Test with a missing class + y = np.asarray([1, 1, 1, 2, 2, 2, 3]) + sample_weight = compute_sample_weight("balanced", y, indices=range(6)) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]) + + # Test with a missing class for multi-output + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [2, 2]]) + sample_weight = compute_sample_weight("balanced", y, indices=range(6)) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]) + + +@pytest.mark.parametrize( + "y_type, class_weight, indices, err_msg", + [ + ( + "single-output", + {1: 2, 2: 1}, + range(4), + "The only valid class_weight for subsampling is 'balanced'.", + ), + ( + "multi-output", + {1: 2, 2: 1}, + None, + "For multi-output, class_weight should be a list of dicts, or the string", + ), + ( + "multi-output", + [{1: 2, 2: 1}], + None, + r"Got 1 element\(s\) while having 2 outputs", + ), + ], +) +def test_compute_sample_weight_errors(y_type, class_weight, indices, err_msg): + # Test compute_sample_weight raises errors expected. + # Invalid preset string + y_single_output = np.asarray([1, 1, 1, 2, 2, 2]) + y_multi_output = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + + y = y_single_output if y_type == "single-output" else y_multi_output + with pytest.raises(ValueError, match=err_msg): + compute_sample_weight(class_weight, y, indices=indices) + + +def test_compute_sample_weight_more_than_32(): + # Non-regression smoke test for #12146 + y = np.arange(50) # more than 32 distinct classes + indices = np.arange(50) # use subsampling + weight = compute_sample_weight("balanced", y, indices=indices) + assert_array_almost_equal(weight, np.ones(y.shape[0])) + + +def test_class_weight_does_not_contains_more_classes(): + """Check that class_weight can contain more labels than in y. + + Non-regression test for #22413 + """ + tree = DecisionTreeClassifier(class_weight={0: 1, 1: 10, 2: 20}) + + # Does not raise + tree.fit([[0, 0, 1], [1, 0, 1], [1, 2, 0]], [0, 0, 1]) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_compute_sample_weight_sparse(csc_container): + """Check that we can compute weight for sparse `y`.""" + y = csc_container(np.asarray([[0], [1], [1]])) + sample_weight = compute_sample_weight("balanced", y) + assert_allclose(sample_weight, [1.5, 0.75, 0.75]) diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_cython_blas.py b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_cython_blas.py new file mode 100644 index 0000000000000000000000000000000000000000..e57bfc3ec5a9c58c8202ad06cf9ede7f65673788 --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_cython_blas.py @@ -0,0 +1,234 @@ +import numpy as np +import pytest + +from sklearn.utils._cython_blas import ( + ColMajor, + NoTrans, + RowMajor, + Trans, + _asum_memview, + _axpy_memview, + _copy_memview, + _dot_memview, + _gemm_memview, + _gemv_memview, + _ger_memview, + _nrm2_memview, + _rot_memview, + _rotg_memview, + _scal_memview, +) +from sklearn.utils._testing import assert_allclose + + +def _numpy_to_cython(dtype): + cython = pytest.importorskip("cython") + if dtype == np.float32: + return cython.float + elif dtype == np.float64: + return cython.double + + +RTOL = {np.float32: 1e-6, np.float64: 1e-12} +ORDER = {RowMajor: "C", ColMajor: "F"} + + +def _no_op(x): + return x + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_dot(dtype): + dot = _dot_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + y = rng.random_sample(10).astype(dtype, copy=False) + + expected = x.dot(y) + actual = dot(x, y) + + assert_allclose(actual, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_asum(dtype): + asum = _asum_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + + expected = np.abs(x).sum() + actual = asum(x) + + assert_allclose(actual, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_axpy(dtype): + axpy = _axpy_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + y = rng.random_sample(10).astype(dtype, copy=False) + alpha = 2.5 + + expected = alpha * x + y + axpy(alpha, x, y) + + assert_allclose(y, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_nrm2(dtype): + nrm2 = _nrm2_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + + expected = np.linalg.norm(x) + actual = nrm2(x) + + assert_allclose(actual, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_copy(dtype): + copy = _copy_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + y = np.empty_like(x) + + expected = x.copy() + copy(x, y) + + assert_allclose(y, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_scal(dtype): + scal = _scal_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + alpha = 2.5 + + expected = alpha * x + scal(alpha, x) + + assert_allclose(x, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_rotg(dtype): + rotg = _rotg_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + a = dtype(rng.randn()) + b = dtype(rng.randn()) + c, s = 0.0, 0.0 + + def expected_rotg(a, b): + roe = a if abs(a) > abs(b) else b + if a == 0 and b == 0: + c, s, r, z = (1, 0, 0, 0) + else: + r = np.sqrt(a**2 + b**2) * (1 if roe >= 0 else -1) + c, s = a / r, b / r + z = s if roe == a else (1 if c == 0 else 1 / c) + return r, z, c, s + + expected = expected_rotg(a, b) + actual = rotg(a, b, c, s) + + assert_allclose(actual, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_rot(dtype): + rot = _rot_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + y = rng.random_sample(10).astype(dtype, copy=False) + c = dtype(rng.randn()) + s = dtype(rng.randn()) + + expected_x = c * x + s * y + expected_y = c * y - s * x + + rot(x, y, c, s) + + assert_allclose(x, expected_x) + assert_allclose(y, expected_y) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize( + "opA, transA", [(_no_op, NoTrans), (np.transpose, Trans)], ids=["NoTrans", "Trans"] +) +@pytest.mark.parametrize("order", [RowMajor, ColMajor], ids=["RowMajor", "ColMajor"]) +def test_gemv(dtype, opA, transA, order): + gemv = _gemv_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + A = np.asarray( + opA(rng.random_sample((20, 10)).astype(dtype, copy=False)), order=ORDER[order] + ) + x = rng.random_sample(10).astype(dtype, copy=False) + y = rng.random_sample(20).astype(dtype, copy=False) + alpha, beta = 2.5, -0.5 + + expected = alpha * opA(A).dot(x) + beta * y + gemv(transA, alpha, A, x, beta, y) + + assert_allclose(y, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize("order", [RowMajor, ColMajor], ids=["RowMajor", "ColMajor"]) +def test_ger(dtype, order): + ger = _ger_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + y = rng.random_sample(20).astype(dtype, copy=False) + A = np.asarray( + rng.random_sample((10, 20)).astype(dtype, copy=False), order=ORDER[order] + ) + alpha = 2.5 + + expected = alpha * np.outer(x, y) + A + ger(alpha, x, y, A) + + assert_allclose(A, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize( + "opB, transB", [(_no_op, NoTrans), (np.transpose, Trans)], ids=["NoTrans", "Trans"] +) +@pytest.mark.parametrize( + "opA, transA", [(_no_op, NoTrans), (np.transpose, Trans)], ids=["NoTrans", "Trans"] +) +@pytest.mark.parametrize("order", [RowMajor, ColMajor], ids=["RowMajor", "ColMajor"]) +def test_gemm(dtype, opA, transA, opB, transB, order): + gemm = _gemm_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + A = np.asarray( + opA(rng.random_sample((30, 10)).astype(dtype, copy=False)), order=ORDER[order] + ) + B = np.asarray( + opB(rng.random_sample((10, 20)).astype(dtype, copy=False)), order=ORDER[order] + ) + C = np.asarray( + rng.random_sample((30, 20)).astype(dtype, copy=False), order=ORDER[order] + ) + alpha, beta = 2.5, -0.5 + + expected = alpha * opA(A).dot(opB(B)) + beta * C + gemm(transA, transB, alpha, A, B, beta, C) + + assert_allclose(C, expected, rtol=RTOL[dtype]) diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_cython_templating.py b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_cython_templating.py new file mode 100644 index 0000000000000000000000000000000000000000..f5c9fa7a9087e81dcf8bd01f155458b5cb1a723f --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_cython_templating.py @@ -0,0 +1,22 @@ +import pathlib + +import pytest + +import sklearn + + +def test_files_generated_by_templates_are_git_ignored(): + """Check the consistence of the files generated from template files.""" + gitignore_file = pathlib.Path(sklearn.__file__).parent.parent / ".gitignore" + if not gitignore_file.exists(): + pytest.skip("Tests are not run from the source folder") + + base_dir = pathlib.Path(sklearn.__file__).parent + ignored_files = gitignore_file.read_text().split("\n") + ignored_files = [pathlib.Path(line) for line in ignored_files] + + for filename in base_dir.glob("**/*.tp"): + filename = filename.relative_to(base_dir.parent) + # From "path/to/template.p??.tp" to "path/to/template.p??" + filename_wo_tempita_suffix = filename.with_suffix("") + assert filename_wo_tempita_suffix in ignored_files diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_deprecation.py b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..4d04b48da2f0b799dcf4f801865dd2b375dea01b --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_deprecation.py @@ -0,0 +1,88 @@ +# Authors: Raghav RV +# License: BSD 3 clause + + +import pickle + +import pytest + +from sklearn.utils.deprecation import _is_deprecated, deprecated + + +@deprecated("qwerty") +class MockClass1: + pass + + +class MockClass2: + @deprecated("mockclass2_method") + def method(self): + pass + + @deprecated("n_features_ is deprecated") # type: ignore + @property + def n_features_(self): + """Number of input features.""" + return 10 + + +class MockClass3: + @deprecated() + def __init__(self): + pass + + +class MockClass4: + pass + + +class MockClass5(MockClass1): + """Inherit from deprecated class but does not call super().__init__.""" + + def __init__(self, a): + self.a = a + + +@deprecated("a message") +class MockClass6: + """A deprecated class that overrides __new__.""" + + def __new__(cls, *args, **kwargs): + assert len(args) > 0 + return super().__new__(cls) + + +@deprecated() +def mock_function(): + return 10 + + +def test_deprecated(): + with pytest.warns(FutureWarning, match="qwerty"): + MockClass1() + with pytest.warns(FutureWarning, match="mockclass2_method"): + MockClass2().method() + with pytest.warns(FutureWarning, match="deprecated"): + MockClass3() + with pytest.warns(FutureWarning, match="qwerty"): + MockClass5(42) + with pytest.warns(FutureWarning, match="a message"): + MockClass6(42) + with pytest.warns(FutureWarning, match="deprecated"): + val = mock_function() + assert val == 10 + + +def test_is_deprecated(): + # Test if _is_deprecated helper identifies wrapping via deprecated + # NOTE it works only for class methods and functions + assert _is_deprecated(MockClass1.__new__) + assert _is_deprecated(MockClass2().method) + assert _is_deprecated(MockClass3.__init__) + assert not _is_deprecated(MockClass4.__init__) + assert _is_deprecated(MockClass5.__new__) + assert _is_deprecated(mock_function) + + +def test_pickle(): + pickle.loads(pickle.dumps(mock_function)) diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_encode.py b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_encode.py new file mode 100644 index 0000000000000000000000000000000000000000..9118eb56f0ba4bbc5227b6c57450af891876acfa --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_encode.py @@ -0,0 +1,274 @@ +import pickle + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +from sklearn.utils._encode import _check_unknown, _encode, _get_counts, _unique + + +@pytest.mark.parametrize( + "values, expected", + [ + (np.array([2, 1, 3, 1, 3], dtype="int64"), np.array([1, 2, 3], dtype="int64")), + ( + np.array([2, 1, np.nan, 1, np.nan], dtype="float32"), + np.array([1, 2, np.nan], dtype="float32"), + ), + ( + np.array(["b", "a", "c", "a", "c"], dtype=object), + np.array(["a", "b", "c"], dtype=object), + ), + ( + np.array(["b", "a", None, "a", None], dtype=object), + np.array(["a", "b", None], dtype=object), + ), + (np.array(["b", "a", "c", "a", "c"]), np.array(["a", "b", "c"])), + ], + ids=["int64", "float32-nan", "object", "object-None", "str"], +) +def test_encode_util(values, expected): + uniques = _unique(values) + assert_array_equal(uniques, expected) + + result, encoded = _unique(values, return_inverse=True) + assert_array_equal(result, expected) + assert_array_equal(encoded, np.array([1, 0, 2, 0, 2])) + + encoded = _encode(values, uniques=uniques) + assert_array_equal(encoded, np.array([1, 0, 2, 0, 2])) + + result, counts = _unique(values, return_counts=True) + assert_array_equal(result, expected) + assert_array_equal(counts, np.array([2, 1, 2])) + + result, encoded, counts = _unique(values, return_inverse=True, return_counts=True) + assert_array_equal(result, expected) + assert_array_equal(encoded, np.array([1, 0, 2, 0, 2])) + assert_array_equal(counts, np.array([2, 1, 2])) + + +def test_encode_with_check_unknown(): + # test for the check_unknown parameter of _encode() + uniques = np.array([1, 2, 3]) + values = np.array([1, 2, 3, 4]) + + # Default is True, raise error + with pytest.raises(ValueError, match="y contains previously unseen labels"): + _encode(values, uniques=uniques, check_unknown=True) + + # dont raise error if False + _encode(values, uniques=uniques, check_unknown=False) + + # parameter is ignored for object dtype + uniques = np.array(["a", "b", "c"], dtype=object) + values = np.array(["a", "b", "c", "d"], dtype=object) + with pytest.raises(ValueError, match="y contains previously unseen labels"): + _encode(values, uniques=uniques, check_unknown=False) + + +def _assert_check_unknown(values, uniques, expected_diff, expected_mask): + diff = _check_unknown(values, uniques) + assert_array_equal(diff, expected_diff) + + diff, valid_mask = _check_unknown(values, uniques, return_mask=True) + assert_array_equal(diff, expected_diff) + assert_array_equal(valid_mask, expected_mask) + + +@pytest.mark.parametrize( + "values, uniques, expected_diff, expected_mask", + [ + (np.array([1, 2, 3, 4]), np.array([1, 2, 3]), [4], [True, True, True, False]), + (np.array([2, 1, 4, 5]), np.array([2, 5, 1]), [4], [True, True, False, True]), + (np.array([2, 1, np.nan]), np.array([2, 5, 1]), [np.nan], [True, True, False]), + ( + np.array([2, 1, 4, np.nan]), + np.array([2, 5, 1, np.nan]), + [4], + [True, True, False, True], + ), + ( + np.array([2, 1, 4, np.nan]), + np.array([2, 5, 1]), + [4, np.nan], + [True, True, False, False], + ), + ( + np.array([2, 1, 4, 5]), + np.array([2, 5, 1, np.nan]), + [4], + [True, True, False, True], + ), + ( + np.array(["a", "b", "c", "d"], dtype=object), + np.array(["a", "b", "c"], dtype=object), + np.array(["d"], dtype=object), + [True, True, True, False], + ), + ( + np.array(["d", "c", "a", "b"], dtype=object), + np.array(["a", "c", "b"], dtype=object), + np.array(["d"], dtype=object), + [False, True, True, True], + ), + ( + np.array(["a", "b", "c", "d"]), + np.array(["a", "b", "c"]), + np.array(["d"]), + [True, True, True, False], + ), + ( + np.array(["d", "c", "a", "b"]), + np.array(["a", "c", "b"]), + np.array(["d"]), + [False, True, True, True], + ), + ], +) +def test_check_unknown(values, uniques, expected_diff, expected_mask): + _assert_check_unknown(values, uniques, expected_diff, expected_mask) + + +@pytest.mark.parametrize("missing_value", [None, np.nan, float("nan")]) +@pytest.mark.parametrize("pickle_uniques", [True, False]) +def test_check_unknown_missing_values(missing_value, pickle_uniques): + # check for check_unknown with missing values with object dtypes + values = np.array(["d", "c", "a", "b", missing_value], dtype=object) + uniques = np.array(["c", "a", "b", missing_value], dtype=object) + if pickle_uniques: + uniques = pickle.loads(pickle.dumps(uniques)) + + expected_diff = ["d"] + expected_mask = [False, True, True, True, True] + _assert_check_unknown(values, uniques, expected_diff, expected_mask) + + values = np.array(["d", "c", "a", "b", missing_value], dtype=object) + uniques = np.array(["c", "a", "b"], dtype=object) + if pickle_uniques: + uniques = pickle.loads(pickle.dumps(uniques)) + + expected_diff = ["d", missing_value] + + expected_mask = [False, True, True, True, False] + _assert_check_unknown(values, uniques, expected_diff, expected_mask) + + values = np.array(["a", missing_value], dtype=object) + uniques = np.array(["a", "b", "z"], dtype=object) + if pickle_uniques: + uniques = pickle.loads(pickle.dumps(uniques)) + + expected_diff = [missing_value] + expected_mask = [True, False] + _assert_check_unknown(values, uniques, expected_diff, expected_mask) + + +@pytest.mark.parametrize("missing_value", [np.nan, None, float("nan")]) +@pytest.mark.parametrize("pickle_uniques", [True, False]) +def test_unique_util_missing_values_objects(missing_value, pickle_uniques): + # check for _unique and _encode with missing values with object dtypes + values = np.array(["a", "c", "c", missing_value, "b"], dtype=object) + expected_uniques = np.array(["a", "b", "c", missing_value], dtype=object) + + uniques = _unique(values) + + if missing_value is None: + assert_array_equal(uniques, expected_uniques) + else: # missing_value == np.nan + assert_array_equal(uniques[:-1], expected_uniques[:-1]) + assert np.isnan(uniques[-1]) + + if pickle_uniques: + uniques = pickle.loads(pickle.dumps(uniques)) + + encoded = _encode(values, uniques=uniques) + assert_array_equal(encoded, np.array([0, 2, 2, 3, 1])) + + +def test_unique_util_missing_values_numeric(): + # Check missing values in numerical values + values = np.array([3, 1, np.nan, 5, 3, np.nan], dtype=float) + expected_uniques = np.array([1, 3, 5, np.nan], dtype=float) + expected_inverse = np.array([1, 0, 3, 2, 1, 3]) + + uniques = _unique(values) + assert_array_equal(uniques, expected_uniques) + + uniques, inverse = _unique(values, return_inverse=True) + assert_array_equal(uniques, expected_uniques) + assert_array_equal(inverse, expected_inverse) + + encoded = _encode(values, uniques=uniques) + assert_array_equal(encoded, expected_inverse) + + +def test_unique_util_with_all_missing_values(): + # test for all types of missing values for object dtype + values = np.array([np.nan, "a", "c", "c", None, float("nan"), None], dtype=object) + + uniques = _unique(values) + assert_array_equal(uniques[:-1], ["a", "c", None]) + # last value is nan + assert np.isnan(uniques[-1]) + + expected_inverse = [3, 0, 1, 1, 2, 3, 2] + _, inverse = _unique(values, return_inverse=True) + assert_array_equal(inverse, expected_inverse) + + +def test_check_unknown_with_both_missing_values(): + # test for both types of missing values for object dtype + values = np.array([np.nan, "a", "c", "c", None, np.nan, None], dtype=object) + + diff = _check_unknown(values, known_values=np.array(["a", "c"], dtype=object)) + assert diff[0] is None + assert np.isnan(diff[1]) + + diff, valid_mask = _check_unknown( + values, known_values=np.array(["a", "c"], dtype=object), return_mask=True + ) + + assert diff[0] is None + assert np.isnan(diff[1]) + assert_array_equal(valid_mask, [False, True, True, True, False, False, False]) + + +@pytest.mark.parametrize( + "values, uniques, expected_counts", + [ + (np.array([1] * 10 + [2] * 4 + [3] * 15), np.array([1, 2, 3]), [10, 4, 15]), + ( + np.array([1] * 10 + [2] * 4 + [3] * 15), + np.array([1, 2, 3, 5]), + [10, 4, 15, 0], + ), + ( + np.array([np.nan] * 10 + [2] * 4 + [3] * 15), + np.array([2, 3, np.nan]), + [4, 15, 10], + ), + ( + np.array(["b"] * 4 + ["a"] * 16 + ["c"] * 20, dtype=object), + ["a", "b", "c"], + [16, 4, 20], + ), + ( + np.array(["b"] * 4 + ["a"] * 16 + ["c"] * 20, dtype=object), + ["c", "b", "a"], + [20, 4, 16], + ), + ( + np.array([np.nan] * 4 + ["a"] * 16 + ["c"] * 20, dtype=object), + ["c", np.nan, "a"], + [20, 4, 16], + ), + ( + np.array(["b"] * 4 + ["a"] * 16 + ["c"] * 20, dtype=object), + ["a", "b", "c", "e"], + [16, 4, 20, 0], + ), + ], +) +def test_get_counts(values, uniques, expected_counts): + counts = _get_counts(values, uniques) + assert_array_equal(counts, expected_counts) diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_estimator_checks.py b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_estimator_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..f52ef27df4015fb5bcb4b0280fce5800ec2b969e --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_estimator_checks.py @@ -0,0 +1,1260 @@ +# We can not use pytest here, because we run +# build_tools/azure/test_pytest_soft_dependency.sh on these +# tests to make sure estimator_checks works without pytest. + +import importlib +import sys +import unittest +import warnings +from numbers import Integral, Real + +import joblib +import numpy as np +import scipy.sparse as sp + +from sklearn import config_context, get_config +from sklearn.base import BaseEstimator, ClassifierMixin, OutlierMixin +from sklearn.cluster import MiniBatchKMeans +from sklearn.datasets import make_multilabel_classification +from sklearn.decomposition import PCA +from sklearn.ensemble import ExtraTreesClassifier +from sklearn.exceptions import ConvergenceWarning, SkipTestWarning +from sklearn.linear_model import ( + LinearRegression, + LogisticRegression, + MultiTaskElasticNet, + SGDClassifier, +) +from sklearn.mixture import GaussianMixture +from sklearn.neighbors import KNeighborsRegressor +from sklearn.svm import SVC, NuSVC +from sklearn.utils import _array_api, all_estimators, deprecated +from sklearn.utils._param_validation import Interval, StrOptions +from sklearn.utils._testing import ( + MinimalClassifier, + MinimalRegressor, + MinimalTransformer, + SkipTest, + ignore_warnings, + raises, +) +from sklearn.utils.estimator_checks import ( + _NotAnArray, + _set_checking_parameters, + _yield_all_checks, + check_array_api_input, + check_class_weight_balanced_linear_classifier, + check_classifier_data_not_an_array, + check_classifiers_multilabel_output_format_decision_function, + check_classifiers_multilabel_output_format_predict, + check_classifiers_multilabel_output_format_predict_proba, + check_dataframe_column_names_consistency, + check_decision_proba_consistency, + check_estimator, + check_estimator_get_tags_default_keys, + check_estimators_unfitted, + check_fit_check_is_fitted, + check_fit_score_takes_y, + check_methods_sample_order_invariance, + check_methods_subset_invariance, + check_no_attributes_set_in_init, + check_outlier_contamination, + check_outlier_corruption, + check_regressor_data_not_an_array, + check_requires_y_none, + set_random_state, +) +from sklearn.utils.fixes import CSR_CONTAINERS +from sklearn.utils.metaestimators import available_if +from sklearn.utils.validation import check_array, check_is_fitted, check_X_y + + +class CorrectNotFittedError(ValueError): + """Exception class to raise if estimator is used before fitting. + + Like NotFittedError, it inherits from ValueError, but not from + AttributeError. Used for testing only. + """ + + +class BaseBadClassifier(ClassifierMixin, BaseEstimator): + def fit(self, X, y): + return self + + def predict(self, X): + return np.ones(X.shape[0]) + + +class ChangesDict(BaseEstimator): + def __init__(self, key=0): + self.key = key + + def fit(self, X, y=None): + X, y = self._validate_data(X, y) + return self + + def predict(self, X): + X = check_array(X) + self.key = 1000 + return np.ones(X.shape[0]) + + +class SetsWrongAttribute(BaseEstimator): + def __init__(self, acceptable_key=0): + self.acceptable_key = acceptable_key + + def fit(self, X, y=None): + self.wrong_attribute = 0 + X, y = self._validate_data(X, y) + return self + + +class ChangesWrongAttribute(BaseEstimator): + def __init__(self, wrong_attribute=0): + self.wrong_attribute = wrong_attribute + + def fit(self, X, y=None): + self.wrong_attribute = 1 + X, y = self._validate_data(X, y) + return self + + +class ChangesUnderscoreAttribute(BaseEstimator): + def fit(self, X, y=None): + self._good_attribute = 1 + X, y = self._validate_data(X, y) + return self + + +class RaisesErrorInSetParams(BaseEstimator): + def __init__(self, p=0): + self.p = p + + def set_params(self, **kwargs): + if "p" in kwargs: + p = kwargs.pop("p") + if p < 0: + raise ValueError("p can't be less than 0") + self.p = p + return super().set_params(**kwargs) + + def fit(self, X, y=None): + X, y = self._validate_data(X, y) + return self + + +class HasMutableParameters(BaseEstimator): + def __init__(self, p=object()): + self.p = p + + def fit(self, X, y=None): + X, y = self._validate_data(X, y) + return self + + +class HasImmutableParameters(BaseEstimator): + # Note that object is an uninitialized class, thus immutable. + def __init__(self, p=42, q=np.int32(42), r=object): + self.p = p + self.q = q + self.r = r + + def fit(self, X, y=None): + X, y = self._validate_data(X, y) + return self + + +class ModifiesValueInsteadOfRaisingError(BaseEstimator): + def __init__(self, p=0): + self.p = p + + def set_params(self, **kwargs): + if "p" in kwargs: + p = kwargs.pop("p") + if p < 0: + p = 0 + self.p = p + return super().set_params(**kwargs) + + def fit(self, X, y=None): + X, y = self._validate_data(X, y) + return self + + +class ModifiesAnotherValue(BaseEstimator): + def __init__(self, a=0, b="method1"): + self.a = a + self.b = b + + def set_params(self, **kwargs): + if "a" in kwargs: + a = kwargs.pop("a") + self.a = a + if a is None: + kwargs.pop("b") + self.b = "method2" + return super().set_params(**kwargs) + + def fit(self, X, y=None): + X, y = self._validate_data(X, y) + return self + + +class NoCheckinPredict(BaseBadClassifier): + def fit(self, X, y): + X, y = self._validate_data(X, y) + return self + + +class NoSparseClassifier(BaseBadClassifier): + def fit(self, X, y): + X, y = self._validate_data(X, y, accept_sparse=["csr", "csc"]) + if sp.issparse(X): + raise ValueError("Nonsensical Error") + return self + + def predict(self, X): + X = check_array(X) + return np.ones(X.shape[0]) + + +class CorrectNotFittedErrorClassifier(BaseBadClassifier): + def fit(self, X, y): + X, y = self._validate_data(X, y) + self.coef_ = np.ones(X.shape[1]) + return self + + def predict(self, X): + check_is_fitted(self) + X = check_array(X) + return np.ones(X.shape[0]) + + +class NoSampleWeightPandasSeriesType(BaseEstimator): + def fit(self, X, y, sample_weight=None): + # Convert data + X, y = self._validate_data( + X, y, accept_sparse=("csr", "csc"), multi_output=True, y_numeric=True + ) + # Function is only called after we verify that pandas is installed + from pandas import Series + + if isinstance(sample_weight, Series): + raise ValueError( + "Estimator does not accept 'sample_weight'of type pandas.Series" + ) + return self + + def predict(self, X): + X = check_array(X) + return np.ones(X.shape[0]) + + +class BadBalancedWeightsClassifier(BaseBadClassifier): + def __init__(self, class_weight=None): + self.class_weight = class_weight + + def fit(self, X, y): + from sklearn.preprocessing import LabelEncoder + from sklearn.utils import compute_class_weight + + label_encoder = LabelEncoder().fit(y) + classes = label_encoder.classes_ + class_weight = compute_class_weight(self.class_weight, classes=classes, y=y) + + # Intentionally modify the balanced class_weight + # to simulate a bug and raise an exception + if self.class_weight == "balanced": + class_weight += 1.0 + + # Simply assigning coef_ to the class_weight + self.coef_ = class_weight + return self + + +class BadTransformerWithoutMixin(BaseEstimator): + def fit(self, X, y=None): + X = self._validate_data(X) + return self + + def transform(self, X): + X = check_array(X) + return X + + +class NotInvariantPredict(BaseEstimator): + def fit(self, X, y): + # Convert data + X, y = self._validate_data( + X, y, accept_sparse=("csr", "csc"), multi_output=True, y_numeric=True + ) + return self + + def predict(self, X): + # return 1 if X has more than one element else return 0 + X = check_array(X) + if X.shape[0] > 1: + return np.ones(X.shape[0]) + return np.zeros(X.shape[0]) + + +class NotInvariantSampleOrder(BaseEstimator): + def fit(self, X, y): + X, y = self._validate_data( + X, y, accept_sparse=("csr", "csc"), multi_output=True, y_numeric=True + ) + # store the original X to check for sample order later + self._X = X + return self + + def predict(self, X): + X = check_array(X) + # if the input contains the same elements but different sample order, + # then just return zeros. + if ( + np.array_equiv(np.sort(X, axis=0), np.sort(self._X, axis=0)) + and (X != self._X).any() + ): + return np.zeros(X.shape[0]) + return X[:, 0] + + +class OneClassSampleErrorClassifier(BaseBadClassifier): + """Classifier allowing to trigger different behaviors when `sample_weight` reduces + the number of classes to 1.""" + + def __init__(self, raise_when_single_class=False): + self.raise_when_single_class = raise_when_single_class + + def fit(self, X, y, sample_weight=None): + X, y = check_X_y( + X, y, accept_sparse=("csr", "csc"), multi_output=True, y_numeric=True + ) + + self.has_single_class_ = False + self.classes_, y = np.unique(y, return_inverse=True) + n_classes_ = self.classes_.shape[0] + if n_classes_ < 2 and self.raise_when_single_class: + self.has_single_class_ = True + raise ValueError("normal class error") + + # find the number of class after trimming + if sample_weight is not None: + if isinstance(sample_weight, np.ndarray) and len(sample_weight) > 0: + n_classes_ = np.count_nonzero(np.bincount(y, sample_weight)) + if n_classes_ < 2: + self.has_single_class_ = True + raise ValueError("Nonsensical Error") + + return self + + def predict(self, X): + check_is_fitted(self) + X = check_array(X) + if self.has_single_class_: + return np.zeros(X.shape[0]) + return np.ones(X.shape[0]) + + +class LargeSparseNotSupportedClassifier(BaseEstimator): + def fit(self, X, y): + X, y = self._validate_data( + X, + y, + accept_sparse=("csr", "csc", "coo"), + accept_large_sparse=True, + multi_output=True, + y_numeric=True, + ) + if sp.issparse(X): + if X.getformat() == "coo": + if X.row.dtype == "int64" or X.col.dtype == "int64": + raise ValueError("Estimator doesn't support 64-bit indices") + elif X.getformat() in ["csc", "csr"]: + assert "int64" not in ( + X.indices.dtype, + X.indptr.dtype, + ), "Estimator doesn't support 64-bit indices" + + return self + + +class SparseTransformer(BaseEstimator): + def __init__(self, sparse_container=None): + self.sparse_container = sparse_container + + def fit(self, X, y=None): + self.X_shape_ = self._validate_data(X).shape + return self + + def fit_transform(self, X, y=None): + return self.fit(X, y).transform(X) + + def transform(self, X): + X = check_array(X) + if X.shape[1] != self.X_shape_[1]: + raise ValueError("Bad number of features") + return self.sparse_container(X) + + +class EstimatorInconsistentForPandas(BaseEstimator): + def fit(self, X, y): + try: + from pandas import DataFrame + + if isinstance(X, DataFrame): + self.value_ = X.iloc[0, 0] + else: + X = check_array(X) + self.value_ = X[1, 0] + return self + + except ImportError: + X = check_array(X) + self.value_ = X[1, 0] + return self + + def predict(self, X): + X = check_array(X) + return np.array([self.value_] * X.shape[0]) + + +class UntaggedBinaryClassifier(SGDClassifier): + # Toy classifier that only supports binary classification, will fail tests. + def fit(self, X, y, coef_init=None, intercept_init=None, sample_weight=None): + super().fit(X, y, coef_init, intercept_init, sample_weight) + if len(self.classes_) > 2: + raise ValueError("Only 2 classes are supported") + return self + + def partial_fit(self, X, y, classes=None, sample_weight=None): + super().partial_fit(X=X, y=y, classes=classes, sample_weight=sample_weight) + if len(self.classes_) > 2: + raise ValueError("Only 2 classes are supported") + return self + + +class TaggedBinaryClassifier(UntaggedBinaryClassifier): + # Toy classifier that only supports binary classification. + def _more_tags(self): + return {"binary_only": True} + + +class EstimatorMissingDefaultTags(BaseEstimator): + def _get_tags(self): + tags = super()._get_tags().copy() + del tags["allow_nan"] + return tags + + +class RequiresPositiveXRegressor(LinearRegression): + def fit(self, X, y): + X, y = self._validate_data(X, y, multi_output=True) + if (X < 0).any(): + raise ValueError("negative X values not supported!") + return super().fit(X, y) + + def _more_tags(self): + return {"requires_positive_X": True} + + +class RequiresPositiveYRegressor(LinearRegression): + def fit(self, X, y): + X, y = self._validate_data(X, y, multi_output=True) + if (y <= 0).any(): + raise ValueError("negative y values not supported!") + return super().fit(X, y) + + def _more_tags(self): + return {"requires_positive_y": True} + + +class PoorScoreLogisticRegression(LogisticRegression): + def decision_function(self, X): + return super().decision_function(X) + 1 + + def _more_tags(self): + return {"poor_score": True} + + +class PartialFitChecksName(BaseEstimator): + def fit(self, X, y): + self._validate_data(X, y) + return self + + def partial_fit(self, X, y): + reset = not hasattr(self, "_fitted") + self._validate_data(X, y, reset=reset) + self._fitted = True + return self + + +class BrokenArrayAPI(BaseEstimator): + """Make different predictions when using Numpy and the Array API""" + + def fit(self, X, y): + return self + + def predict(self, X): + enabled = get_config()["array_api_dispatch"] + xp, _ = _array_api.get_namespace(X) + if enabled: + return xp.asarray([1, 2, 3]) + else: + return np.array([3, 2, 1]) + + +def test_check_array_api_input(): + try: + importlib.import_module("array_api_compat") + except ModuleNotFoundError: + raise SkipTest("array_api_compat is required to run this test") + try: + importlib.import_module("numpy.array_api") + except ModuleNotFoundError: # pragma: nocover + raise SkipTest("numpy.array_api is required to run this test") + + with raises(AssertionError, match="Not equal to tolerance"): + check_array_api_input( + "BrokenArrayAPI", + BrokenArrayAPI(), + array_namespace="numpy.array_api", + check_values=True, + ) + + +def test_not_an_array_array_function(): + not_array = _NotAnArray(np.ones(10)) + msg = "Don't want to call array_function sum!" + with raises(TypeError, match=msg): + np.sum(not_array) + # always returns True + assert np.may_share_memory(not_array, None) + + +def test_check_fit_score_takes_y_works_on_deprecated_fit(): + # Tests that check_fit_score_takes_y works on a class with + # a deprecated fit method + + class TestEstimatorWithDeprecatedFitMethod(BaseEstimator): + @deprecated("Deprecated for the purpose of testing check_fit_score_takes_y") + def fit(self, X, y): + return self + + check_fit_score_takes_y("test", TestEstimatorWithDeprecatedFitMethod()) + + +def test_check_estimator(): + # tests that the estimator actually fails on "bad" estimators. + # not a complete test of all checks, which are very extensive. + + # check that we have a set_params and can clone + msg = "Passing a class was deprecated" + with raises(TypeError, match=msg): + check_estimator(object) + msg = ( + "Parameter 'p' of estimator 'HasMutableParameters' is of type " + "object which is not allowed" + ) + # check that the "default_constructible" test checks for mutable parameters + check_estimator(HasImmutableParameters()) # should pass + with raises(AssertionError, match=msg): + check_estimator(HasMutableParameters()) + # check that values returned by get_params match set_params + msg = "get_params result does not match what was passed to set_params" + with raises(AssertionError, match=msg): + check_estimator(ModifiesValueInsteadOfRaisingError()) + with warnings.catch_warnings(record=True) as records: + check_estimator(RaisesErrorInSetParams()) + assert UserWarning in [rec.category for rec in records] + + with raises(AssertionError, match=msg): + check_estimator(ModifiesAnotherValue()) + # check that we have a fit method + msg = "object has no attribute 'fit'" + with raises(AttributeError, match=msg): + check_estimator(BaseEstimator()) + # check that fit does input validation + msg = "Did not raise" + with raises(AssertionError, match=msg): + check_estimator(BaseBadClassifier()) + # check that sample_weights in fit accepts pandas.Series type + try: + from pandas import Series # noqa + + msg = ( + "Estimator NoSampleWeightPandasSeriesType raises error if " + "'sample_weight' parameter is of type pandas.Series" + ) + with raises(ValueError, match=msg): + check_estimator(NoSampleWeightPandasSeriesType()) + except ImportError: + pass + # check that predict does input validation (doesn't accept dicts in input) + msg = "Estimator NoCheckinPredict doesn't check for NaN and inf in predict" + with raises(AssertionError, match=msg): + check_estimator(NoCheckinPredict()) + # check that estimator state does not change + # at transform/predict/predict_proba time + msg = "Estimator changes __dict__ during predict" + with raises(AssertionError, match=msg): + check_estimator(ChangesDict()) + # check that `fit` only changes attributes that + # are private (start with an _ or end with a _). + msg = ( + "Estimator ChangesWrongAttribute should not change or mutate " + "the parameter wrong_attribute from 0 to 1 during fit." + ) + with raises(AssertionError, match=msg): + check_estimator(ChangesWrongAttribute()) + check_estimator(ChangesUnderscoreAttribute()) + # check that `fit` doesn't add any public attribute + msg = ( + r"Estimator adds public attribute\(s\) during the fit method." + " Estimators are only allowed to add private attributes" + " either started with _ or ended" + " with _ but wrong_attribute added" + ) + with raises(AssertionError, match=msg): + check_estimator(SetsWrongAttribute()) + # check for sample order invariance + name = NotInvariantSampleOrder.__name__ + method = "predict" + msg = ( + "{method} of {name} is not invariant when applied to a dataset" + "with different sample order." + ).format(method=method, name=name) + with raises(AssertionError, match=msg): + check_estimator(NotInvariantSampleOrder()) + # check for invariant method + name = NotInvariantPredict.__name__ + method = "predict" + msg = ("{method} of {name} is not invariant when applied to a subset.").format( + method=method, name=name + ) + with raises(AssertionError, match=msg): + check_estimator(NotInvariantPredict()) + # check for sparse matrix input handling + name = NoSparseClassifier.__name__ + msg = "Estimator %s doesn't seem to fail gracefully on sparse data" % name + with raises(AssertionError, match=msg): + check_estimator(NoSparseClassifier()) + + # check for classifiers reducing to less than two classes via sample weights + name = OneClassSampleErrorClassifier.__name__ + msg = ( + f"{name} failed when fitted on one label after sample_weight " + "trimming. Error message is not explicit, it should have " + "'class'." + ) + with raises(AssertionError, match=msg): + check_estimator(OneClassSampleErrorClassifier()) + + # Large indices test on bad estimator + msg = ( + "Estimator LargeSparseNotSupportedClassifier doesn't seem to " + r"support \S{3}_64 matrix, and is not failing gracefully.*" + ) + with raises(AssertionError, match=msg): + check_estimator(LargeSparseNotSupportedClassifier()) + + # does error on binary_only untagged estimator + msg = "Only 2 classes are supported" + with raises(ValueError, match=msg): + check_estimator(UntaggedBinaryClassifier()) + + for csr_container in CSR_CONTAINERS: + # non-regression test for estimators transforming to sparse data + check_estimator(SparseTransformer(sparse_container=csr_container)) + + # doesn't error on actual estimator + check_estimator(LogisticRegression()) + check_estimator(LogisticRegression(C=0.01)) + check_estimator(MultiTaskElasticNet()) + + # doesn't error on binary_only tagged estimator + check_estimator(TaggedBinaryClassifier()) + check_estimator(RequiresPositiveXRegressor()) + + # Check regressor with requires_positive_y estimator tag + msg = "negative y values not supported!" + with raises(ValueError, match=msg): + check_estimator(RequiresPositiveYRegressor()) + + # Does not raise error on classifier with poor_score tag + check_estimator(PoorScoreLogisticRegression()) + + +def test_check_outlier_corruption(): + # should raise AssertionError + decision = np.array([0.0, 1.0, 1.5, 2.0]) + with raises(AssertionError): + check_outlier_corruption(1, 2, decision) + # should pass + decision = np.array([0.0, 1.0, 1.0, 2.0]) + check_outlier_corruption(1, 2, decision) + + +def test_check_estimator_transformer_no_mixin(): + # check that TransformerMixin is not required for transformer tests to run + with raises(AttributeError, ".*fit_transform.*"): + check_estimator(BadTransformerWithoutMixin()) + + +def test_check_estimator_clones(): + # check that check_estimator doesn't modify the estimator it receives + from sklearn.datasets import load_iris + + iris = load_iris() + + for Estimator in [ + GaussianMixture, + LinearRegression, + SGDClassifier, + PCA, + ExtraTreesClassifier, + MiniBatchKMeans, + ]: + # without fitting + with ignore_warnings(category=ConvergenceWarning): + est = Estimator() + _set_checking_parameters(est) + set_random_state(est) + old_hash = joblib.hash(est) + check_estimator(est) + assert old_hash == joblib.hash(est) + + # with fitting + with ignore_warnings(category=ConvergenceWarning): + est = Estimator() + _set_checking_parameters(est) + set_random_state(est) + est.fit(iris.data + 10, iris.target) + old_hash = joblib.hash(est) + check_estimator(est) + assert old_hash == joblib.hash(est) + + +def test_check_estimators_unfitted(): + # check that a ValueError/AttributeError is raised when calling predict + # on an unfitted estimator + msg = "Did not raise" + with raises(AssertionError, match=msg): + check_estimators_unfitted("estimator", NoSparseClassifier()) + + # check that CorrectNotFittedError inherit from either ValueError + # or AttributeError + check_estimators_unfitted("estimator", CorrectNotFittedErrorClassifier()) + + +def test_check_no_attributes_set_in_init(): + class NonConformantEstimatorPrivateSet(BaseEstimator): + def __init__(self): + self.you_should_not_set_this_ = None + + class NonConformantEstimatorNoParamSet(BaseEstimator): + def __init__(self, you_should_set_this_=None): + pass + + class ConformantEstimatorClassAttribute(BaseEstimator): + # making sure our __metadata_request__* class attributes are okay! + __metadata_request__fit = {"foo": True} + + msg = ( + "Estimator estimator_name should not set any" + " attribute apart from parameters during init." + r" Found attributes \['you_should_not_set_this_'\]." + ) + with raises(AssertionError, match=msg): + check_no_attributes_set_in_init( + "estimator_name", NonConformantEstimatorPrivateSet() + ) + + msg = ( + "Estimator estimator_name should store all parameters as an attribute" + " during init" + ) + with raises(AttributeError, match=msg): + check_no_attributes_set_in_init( + "estimator_name", NonConformantEstimatorNoParamSet() + ) + + # a private class attribute is okay! + check_no_attributes_set_in_init( + "estimator_name", ConformantEstimatorClassAttribute() + ) + # also check if cloning an estimator which has non-default set requests is + # fine. Setting a non-default value via `set_{method}_request` sets the + # private _metadata_request instance attribute which is copied in `clone`. + with config_context(enable_metadata_routing=True): + check_no_attributes_set_in_init( + "estimator_name", + ConformantEstimatorClassAttribute().set_fit_request(foo=True), + ) + + +def test_check_estimator_pairwise(): + # check that check_estimator() works on estimator with _pairwise + # kernel or metric + + # test precomputed kernel + est = SVC(kernel="precomputed") + check_estimator(est) + + # test precomputed metric + est = KNeighborsRegressor(metric="precomputed") + check_estimator(est) + + +def test_check_classifier_data_not_an_array(): + with raises(AssertionError, match="Not equal to tolerance"): + check_classifier_data_not_an_array( + "estimator_name", EstimatorInconsistentForPandas() + ) + + +def test_check_regressor_data_not_an_array(): + with raises(AssertionError, match="Not equal to tolerance"): + check_regressor_data_not_an_array( + "estimator_name", EstimatorInconsistentForPandas() + ) + + +def test_check_estimator_get_tags_default_keys(): + estimator = EstimatorMissingDefaultTags() + err_msg = ( + r"EstimatorMissingDefaultTags._get_tags\(\) is missing entries" + r" for the following default tags: {'allow_nan'}" + ) + with raises(AssertionError, match=err_msg): + check_estimator_get_tags_default_keys(estimator.__class__.__name__, estimator) + + # noop check when _get_tags is not available + estimator = MinimalTransformer() + check_estimator_get_tags_default_keys(estimator.__class__.__name__, estimator) + + +def test_check_dataframe_column_names_consistency(): + err_msg = "Estimator does not have a feature_names_in_" + with raises(ValueError, match=err_msg): + check_dataframe_column_names_consistency("estimator_name", BaseBadClassifier()) + check_dataframe_column_names_consistency("estimator_name", PartialFitChecksName()) + + lr = LogisticRegression() + check_dataframe_column_names_consistency(lr.__class__.__name__, lr) + lr.__doc__ = "Docstring that does not document the estimator's attributes" + err_msg = ( + "Estimator LogisticRegression does not document its feature_names_in_ attribute" + ) + with raises(ValueError, match=err_msg): + check_dataframe_column_names_consistency(lr.__class__.__name__, lr) + + +class _BaseMultiLabelClassifierMock(ClassifierMixin, BaseEstimator): + def __init__(self, response_output): + self.response_output = response_output + + def fit(self, X, y): + return self + + def _more_tags(self): + return {"multilabel": True} + + +def test_check_classifiers_multilabel_output_format_predict(): + n_samples, test_size, n_outputs = 100, 25, 5 + _, y = make_multilabel_classification( + n_samples=n_samples, + n_features=2, + n_classes=n_outputs, + n_labels=3, + length=50, + allow_unlabeled=True, + random_state=0, + ) + y_test = y[-test_size:] + + class MultiLabelClassifierPredict(_BaseMultiLabelClassifierMock): + def predict(self, X): + return self.response_output + + # 1. inconsistent array type + clf = MultiLabelClassifierPredict(response_output=y_test.tolist()) + err_msg = ( + r"MultiLabelClassifierPredict.predict is expected to output a " + r"NumPy array. Got instead." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict(clf.__class__.__name__, clf) + # 2. inconsistent shape + clf = MultiLabelClassifierPredict(response_output=y_test[:, :-1]) + err_msg = ( + r"MultiLabelClassifierPredict.predict outputs a NumPy array of " + r"shape \(25, 4\) instead of \(25, 5\)." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict(clf.__class__.__name__, clf) + # 3. inconsistent dtype + clf = MultiLabelClassifierPredict(response_output=y_test.astype(np.float64)) + err_msg = ( + r"MultiLabelClassifierPredict.predict does not output the same " + r"dtype than the targets." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict(clf.__class__.__name__, clf) + + +def test_check_classifiers_multilabel_output_format_predict_proba(): + n_samples, test_size, n_outputs = 100, 25, 5 + _, y = make_multilabel_classification( + n_samples=n_samples, + n_features=2, + n_classes=n_outputs, + n_labels=3, + length=50, + allow_unlabeled=True, + random_state=0, + ) + y_test = y[-test_size:] + + class MultiLabelClassifierPredictProba(_BaseMultiLabelClassifierMock): + def predict_proba(self, X): + return self.response_output + + for csr_container in CSR_CONTAINERS: + # 1. unknown output type + clf = MultiLabelClassifierPredictProba(response_output=csr_container(y_test)) + err_msg = ( + f"Unknown returned type .*{csr_container.__name__}.* by " + r"MultiLabelClassifierPredictProba.predict_proba. A list or a Numpy " + r"array is expected." + ) + with raises(ValueError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 2. for list output + # 2.1. inconsistent length + clf = MultiLabelClassifierPredictProba(response_output=y_test.tolist()) + err_msg = ( + "When MultiLabelClassifierPredictProba.predict_proba returns a list, " + "the list should be of length n_outputs and contain NumPy arrays. Got " + f"length of {test_size} instead of {n_outputs}." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 2.2. array of inconsistent shape + response_output = [np.ones_like(y_test) for _ in range(n_outputs)] + clf = MultiLabelClassifierPredictProba(response_output=response_output) + err_msg = ( + r"When MultiLabelClassifierPredictProba.predict_proba returns a list, " + r"this list should contain NumPy arrays of shape \(n_samples, 2\). Got " + r"NumPy arrays of shape \(25, 5\) instead of \(25, 2\)." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 2.3. array of inconsistent dtype + response_output = [ + np.ones(shape=(y_test.shape[0], 2), dtype=np.int64) for _ in range(n_outputs) + ] + clf = MultiLabelClassifierPredictProba(response_output=response_output) + err_msg = ( + "When MultiLabelClassifierPredictProba.predict_proba returns a list, " + "it should contain NumPy arrays with floating dtype." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 2.4. array does not contain probability (each row should sum to 1) + response_output = [ + np.ones(shape=(y_test.shape[0], 2), dtype=np.float64) for _ in range(n_outputs) + ] + clf = MultiLabelClassifierPredictProba(response_output=response_output) + err_msg = ( + r"When MultiLabelClassifierPredictProba.predict_proba returns a list, " + r"each NumPy array should contain probabilities for each class and " + r"thus each row should sum to 1" + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 3 for array output + # 3.1. array of inconsistent shape + clf = MultiLabelClassifierPredictProba(response_output=y_test[:, :-1]) + err_msg = ( + r"When MultiLabelClassifierPredictProba.predict_proba returns a NumPy " + r"array, the expected shape is \(n_samples, n_outputs\). Got \(25, 4\)" + r" instead of \(25, 5\)." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 3.2. array of inconsistent dtype + response_output = np.zeros_like(y_test, dtype=np.int64) + clf = MultiLabelClassifierPredictProba(response_output=response_output) + err_msg = ( + r"When MultiLabelClassifierPredictProba.predict_proba returns a NumPy " + r"array, the expected data type is floating." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + # 4. array does not contain probabilities + clf = MultiLabelClassifierPredictProba(response_output=y_test * 2.0) + err_msg = ( + r"When MultiLabelClassifierPredictProba.predict_proba returns a NumPy " + r"array, this array is expected to provide probabilities of the " + r"positive class and should therefore contain values between 0 and 1." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_predict_proba( + clf.__class__.__name__, + clf, + ) + + +def test_check_classifiers_multilabel_output_format_decision_function(): + n_samples, test_size, n_outputs = 100, 25, 5 + _, y = make_multilabel_classification( + n_samples=n_samples, + n_features=2, + n_classes=n_outputs, + n_labels=3, + length=50, + allow_unlabeled=True, + random_state=0, + ) + y_test = y[-test_size:] + + class MultiLabelClassifierDecisionFunction(_BaseMultiLabelClassifierMock): + def decision_function(self, X): + return self.response_output + + # 1. inconsistent array type + clf = MultiLabelClassifierDecisionFunction(response_output=y_test.tolist()) + err_msg = ( + r"MultiLabelClassifierDecisionFunction.decision_function is expected " + r"to output a NumPy array. Got instead." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_decision_function( + clf.__class__.__name__, + clf, + ) + # 2. inconsistent shape + clf = MultiLabelClassifierDecisionFunction(response_output=y_test[:, :-1]) + err_msg = ( + r"MultiLabelClassifierDecisionFunction.decision_function is expected " + r"to provide a NumPy array of shape \(n_samples, n_outputs\). Got " + r"\(25, 4\) instead of \(25, 5\)" + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_decision_function( + clf.__class__.__name__, + clf, + ) + # 3. inconsistent dtype + clf = MultiLabelClassifierDecisionFunction(response_output=y_test) + err_msg = ( + r"MultiLabelClassifierDecisionFunction.decision_function is expected " + r"to output a floating dtype." + ) + with raises(AssertionError, match=err_msg): + check_classifiers_multilabel_output_format_decision_function( + clf.__class__.__name__, + clf, + ) + + +def run_tests_without_pytest(): + """Runs the tests in this file without using pytest.""" + main_module = sys.modules["__main__"] + test_functions = [ + getattr(main_module, name) + for name in dir(main_module) + if name.startswith("test_") + ] + test_cases = [unittest.FunctionTestCase(fn) for fn in test_functions] + suite = unittest.TestSuite() + suite.addTests(test_cases) + runner = unittest.TextTestRunner() + runner.run(suite) + + +def test_check_class_weight_balanced_linear_classifier(): + # check that ill-computed balanced weights raises an exception + msg = "Classifier estimator_name is not computing class_weight=balanced properly" + with raises(AssertionError, match=msg): + check_class_weight_balanced_linear_classifier( + "estimator_name", BadBalancedWeightsClassifier + ) + + +def test_all_estimators_all_public(): + # all_estimator should not fail when pytest is not installed and return + # only public estimators + with warnings.catch_warnings(record=True) as record: + estimators = all_estimators() + # no warnings are raised + assert not record + for est in estimators: + assert not est.__class__.__name__.startswith("_") + + +if __name__ == "__main__": + # This module is run as a script to check that we have no dependency on + # pytest for estimator checks. + run_tests_without_pytest() + + +def test_xfail_ignored_in_check_estimator(): + # Make sure checks marked as xfail are just ignored and not run by + # check_estimator(), but still raise a warning. + with warnings.catch_warnings(record=True) as records: + check_estimator(NuSVC()) + assert SkipTestWarning in [rec.category for rec in records] + + +# FIXME: this test should be uncommented when the checks will be granular +# enough. In 0.24, these tests fail due to low estimator performance. +def test_minimal_class_implementation_checks(): + # Check that third-party library can run tests without inheriting from + # BaseEstimator. + # FIXME + raise SkipTest + minimal_estimators = [MinimalTransformer(), MinimalRegressor(), MinimalClassifier()] + for estimator in minimal_estimators: + check_estimator(estimator) + + +def test_check_fit_check_is_fitted(): + class Estimator(BaseEstimator): + def __init__(self, behavior="attribute"): + self.behavior = behavior + + def fit(self, X, y, **kwargs): + if self.behavior == "attribute": + self.is_fitted_ = True + elif self.behavior == "method": + self._is_fitted = True + return self + + @available_if(lambda self: self.behavior in {"method", "always-true"}) + def __sklearn_is_fitted__(self): + if self.behavior == "always-true": + return True + return hasattr(self, "_is_fitted") + + with raises(Exception, match="passes check_is_fitted before being fit"): + check_fit_check_is_fitted("estimator", Estimator(behavior="always-true")) + + check_fit_check_is_fitted("estimator", Estimator(behavior="method")) + check_fit_check_is_fitted("estimator", Estimator(behavior="attribute")) + + +def test_check_requires_y_none(): + class Estimator(BaseEstimator): + def fit(self, X, y): + X, y = check_X_y(X, y) + + with warnings.catch_warnings(record=True) as record: + check_requires_y_none("estimator", Estimator()) + + # no warnings are raised + assert not [r.message for r in record] + + +def test_non_deterministic_estimator_skip_tests(): + # check estimators with non_deterministic tag set to True + # will skip certain tests, refer to issue #22313 for details + for est in [MinimalTransformer, MinimalRegressor, MinimalClassifier]: + all_tests = list(_yield_all_checks(est())) + assert check_methods_sample_order_invariance in all_tests + assert check_methods_subset_invariance in all_tests + + class Estimator(est): + def _more_tags(self): + return {"non_deterministic": True} + + all_tests = list(_yield_all_checks(Estimator())) + assert check_methods_sample_order_invariance not in all_tests + assert check_methods_subset_invariance not in all_tests + + +def test_check_outlier_contamination(): + """Check the test for the contamination parameter in the outlier detectors.""" + + # Without any parameter constraints, the estimator will early exit the test by + # returning None. + class OutlierDetectorWithoutConstraint(OutlierMixin, BaseEstimator): + """Outlier detector without parameter validation.""" + + def __init__(self, contamination=0.1): + self.contamination = contamination + + def fit(self, X, y=None, sample_weight=None): + return self # pragma: no cover + + def predict(self, X, y=None): + return np.ones(X.shape[0]) + + detector = OutlierDetectorWithoutConstraint() + assert check_outlier_contamination(detector.__class__.__name__, detector) is None + + # Now, we check that with the parameter constraints, the test should only be valid + # if an Interval constraint with bound in [0, 1] is provided. + class OutlierDetectorWithConstraint(OutlierDetectorWithoutConstraint): + _parameter_constraints = {"contamination": [StrOptions({"auto"})]} + + detector = OutlierDetectorWithConstraint() + err_msg = "contamination constraints should contain a Real Interval constraint." + with raises(AssertionError, match=err_msg): + check_outlier_contamination(detector.__class__.__name__, detector) + + # Add a correct interval constraint and check that the test passes. + OutlierDetectorWithConstraint._parameter_constraints["contamination"] = [ + Interval(Real, 0, 0.5, closed="right") + ] + detector = OutlierDetectorWithConstraint() + check_outlier_contamination(detector.__class__.__name__, detector) + + incorrect_intervals = [ + Interval(Integral, 0, 1, closed="right"), # not an integral interval + Interval(Real, -1, 1, closed="right"), # lower bound is negative + Interval(Real, 0, 2, closed="right"), # upper bound is greater than 1 + Interval(Real, 0, 0.5, closed="left"), # lower bound include 0 + ] + + err_msg = r"contamination constraint should be an interval in \(0, 0.5\]" + for interval in incorrect_intervals: + OutlierDetectorWithConstraint._parameter_constraints["contamination"] = [ + interval + ] + detector = OutlierDetectorWithConstraint() + with raises(AssertionError, match=err_msg): + check_outlier_contamination(detector.__class__.__name__, detector) + + +def test_decision_proba_tie_ranking(): + """Check that in case with some probabilities ties, we relax the + ranking comparison with the decision function. + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/24025 + """ + estimator = SGDClassifier(loss="log_loss") + check_decision_proba_consistency("SGDClassifier", estimator) diff --git a/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_estimator_html_repr.py b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_estimator_html_repr.py new file mode 100644 index 0000000000000000000000000000000000000000..d59658998432da760acd0611774106bf85c2284e --- /dev/null +++ b/venv/lib/python3.10/site-packages/sklearn/utils/tests/test_estimator_html_repr.py @@ -0,0 +1,518 @@ +import html +import locale +import re +from contextlib import closing +from io import StringIO +from unittest.mock import patch + +import pytest + +from sklearn import config_context +from sklearn.base import BaseEstimator +from sklearn.cluster import AgglomerativeClustering, Birch +from sklearn.compose import ColumnTransformer, make_column_transformer +from sklearn.datasets import load_iris +from sklearn.decomposition import PCA, TruncatedSVD +from sklearn.ensemble import StackingClassifier, StackingRegressor, VotingClassifier +from sklearn.feature_selection import SelectPercentile +from sklearn.gaussian_process.kernels import ExpSineSquared +from sklearn.impute import SimpleImputer +from sklearn.kernel_ridge import KernelRidge +from sklearn.linear_model import LogisticRegression +from sklearn.model_selection import RandomizedSearchCV +from sklearn.multiclass import OneVsOneClassifier +from sklearn.neural_network import MLPClassifier +from sklearn.pipeline import FeatureUnion, Pipeline, make_pipeline +from sklearn.preprocessing import OneHotEncoder, StandardScaler +from sklearn.svm import LinearSVC, LinearSVR +from sklearn.tree import DecisionTreeClassifier +from sklearn.utils._estimator_html_repr import ( + _get_css_style, + _get_visual_block, + _HTMLDocumentationLinkMixin, + _write_label_html, + estimator_html_repr, +) +from sklearn.utils.fixes import parse_version + + +@pytest.mark.parametrize("checked", [True, False]) +def test_write_label_html(checked): + # Test checking logic and labeling + name = "LogisticRegression" + tool_tip = "hello-world" + + with closing(StringIO()) as out: + _write_label_html(out, name, tool_tip, checked=checked) + html_label = out.getvalue() + + p = ( + r'