applied-ai-018 commited on
Commit
aa913b2
·
verified ·
1 Parent(s): 6d870c6

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step40/zero/10.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
  2. ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/exp_avg.pt +3 -0
  3. ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/exp_avg_sq.pt +3 -0
  4. ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
  5. ckpts/universal/global_step40/zero/21.attention.query_key_value.weight/exp_avg.pt +3 -0
  6. ckpts/universal/global_step40/zero/21.attention.query_key_value.weight/exp_avg_sq.pt +3 -0
  7. venv/lib/python3.10/site-packages/sklearn/utils/_bunch.py +67 -0
  8. venv/lib/python3.10/site-packages/sklearn/utils/_cython_blas.cpython-310-x86_64-linux-gnu.so +0 -0
  9. venv/lib/python3.10/site-packages/sklearn/utils/_cython_blas.pxd +41 -0
  10. venv/lib/python3.10/site-packages/sklearn/utils/_fast_dict.cpython-310-x86_64-linux-gnu.so +0 -0
  11. venv/lib/python3.10/site-packages/sklearn/utils/_heap.pxd +14 -0
  12. venv/lib/python3.10/site-packages/sklearn/utils/_mask.py +63 -0
  13. venv/lib/python3.10/site-packages/sklearn/utils/_mocking.py +400 -0
  14. venv/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.cpython-310-x86_64-linux-gnu.so +0 -0
  15. venv/lib/python3.10/site-packages/sklearn/utils/_plotting.py +98 -0
  16. venv/lib/python3.10/site-packages/sklearn/utils/_random.cpython-310-x86_64-linux-gnu.so +0 -0
  17. venv/lib/python3.10/site-packages/sklearn/utils/_response.py +298 -0
  18. venv/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.pxd +104 -0
  19. venv/lib/python3.10/site-packages/sklearn/utils/_set_output.py +441 -0
  20. venv/lib/python3.10/site-packages/sklearn/utils/_sorting.pxd +9 -0
  21. venv/lib/python3.10/site-packages/sklearn/utils/_tags.py +68 -0
  22. venv/lib/python3.10/site-packages/sklearn/utils/_testing.py +1169 -0
  23. venv/lib/python3.10/site-packages/sklearn/utils/_typedefs.pxd +29 -0
  24. venv/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so +0 -0
  25. venv/lib/python3.10/site-packages/sklearn/utils/_weight_vector.cpython-310-x86_64-linux-gnu.so +0 -0
  26. venv/lib/python3.10/site-packages/sklearn/utils/_weight_vector.pxd +48 -0
  27. venv/lib/python3.10/site-packages/sklearn/utils/class_weight.py +224 -0
  28. venv/lib/python3.10/site-packages/sklearn/utils/deprecation.py +116 -0
  29. venv/lib/python3.10/site-packages/sklearn/utils/extmath.py +1284 -0
  30. venv/lib/python3.10/site-packages/sklearn/utils/optimize.py +302 -0
  31. venv/lib/python3.10/site-packages/sklearn/utils/parallel.py +129 -0
  32. venv/lib/python3.10/site-packages/sklearn/utils/sparsefuncs.py +745 -0
  33. venv/lib/python3.10/site-packages/sklearn/utils/sparsefuncs_fast.cpython-310-x86_64-linux-gnu.so +0 -0
  34. venv/lib/python3.10/site-packages/sklearn/utils/stats.py +69 -0
  35. venv/lib/python3.10/site-packages/sklearn/utils/tests/__init__.py +0 -0
  36. venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_bunch.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_multiclass.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_param_validation.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_plotting.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_seq_dataset.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_show_versions.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_stats.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_weight_vector.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/sklearn/utils/tests/test_arpack.py +16 -0
  47. venv/lib/python3.10/site-packages/sklearn/utils/tests/test_array_api.py +331 -0
  48. venv/lib/python3.10/site-packages/sklearn/utils/tests/test_arrayfuncs.py +38 -0
  49. venv/lib/python3.10/site-packages/sklearn/utils/tests/test_bunch.py +32 -0
  50. venv/lib/python3.10/site-packages/sklearn/utils/tests/test_class_weight.py +316 -0
ckpts/universal/global_step40/zero/10.mlp.dense_4h_to_h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bae3355ac505dba276fbc9ef1a8d8a4a431a137ebb360756af8d63420c8d51f2
3
+ size 33555533
ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cadac90d4f41233545e34e5aa5b51138130b7cd0ade41055f9eb78dfffab118d
3
+ size 33555612
ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4e379e326b77e978f944bd8a16ac6eabfab08f8e5c84039959e2281e0f6f331f
3
+ size 33555627
ckpts/universal/global_step40/zero/19.mlp.dense_h_to_4h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:10f2fae360748617999505b629e700527fd4f54adec3a0a0d65e18d641104e1c
3
+ size 33555533
ckpts/universal/global_step40/zero/21.attention.query_key_value.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33d6a07534b7dcdeb437b1000f825147b2ad45d03b9447841dad2ec134b17d00
3
+ size 50332828
ckpts/universal/global_step40/zero/21.attention.query_key_value.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2062d08884b7b2cbf5001d295a8965e9df7e168728992285576d6a82f2934cb
3
+ size 50332843
venv/lib/python3.10/site-packages/sklearn/utils/_bunch.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+
4
+ class Bunch(dict):
5
+ """Container object exposing keys as attributes.
6
+
7
+ Bunch objects are sometimes used as an output for functions and methods.
8
+ They extend dictionaries by enabling values to be accessed by key,
9
+ `bunch["value_key"]`, or by an attribute, `bunch.value_key`.
10
+
11
+ Examples
12
+ --------
13
+ >>> from sklearn.utils import Bunch
14
+ >>> b = Bunch(a=1, b=2)
15
+ >>> b['b']
16
+ 2
17
+ >>> b.b
18
+ 2
19
+ >>> b.a = 3
20
+ >>> b['a']
21
+ 3
22
+ >>> b.c = 6
23
+ >>> b['c']
24
+ 6
25
+ """
26
+
27
+ def __init__(self, **kwargs):
28
+ super().__init__(kwargs)
29
+
30
+ # Map from deprecated key to warning message
31
+ self.__dict__["_deprecated_key_to_warnings"] = {}
32
+
33
+ def __getitem__(self, key):
34
+ if key in self.__dict__.get("_deprecated_key_to_warnings", {}):
35
+ warnings.warn(
36
+ self._deprecated_key_to_warnings[key],
37
+ FutureWarning,
38
+ )
39
+ return super().__getitem__(key)
40
+
41
+ def _set_deprecated(self, value, *, new_key, deprecated_key, warning_message):
42
+ """Set key in dictionary to be deprecated with its warning message."""
43
+ self.__dict__["_deprecated_key_to_warnings"][deprecated_key] = warning_message
44
+ self[new_key] = self[deprecated_key] = value
45
+
46
+ def __setattr__(self, key, value):
47
+ self[key] = value
48
+
49
+ def __dir__(self):
50
+ return self.keys()
51
+
52
+ def __getattr__(self, key):
53
+ try:
54
+ return self[key]
55
+ except KeyError:
56
+ raise AttributeError(key)
57
+
58
+ def __setstate__(self, state):
59
+ # Bunch pickles generated with scikit-learn 0.16.* have an non
60
+ # empty __dict__. This causes a surprising behaviour when
61
+ # loading these pickles scikit-learn 0.17: reading bunch.key
62
+ # uses __dict__ but assigning to bunch.key use __setattr__ and
63
+ # only changes bunch['key']. More details can be found at:
64
+ # https://github.com/scikit-learn/scikit-learn/issues/6196.
65
+ # Overriding __setstate__ to be a noop has the effect of
66
+ # ignoring the pickled __dict__
67
+ pass
venv/lib/python3.10/site-packages/sklearn/utils/_cython_blas.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (528 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/_cython_blas.pxd ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from cython cimport floating
2
+
3
+
4
+ cpdef enum BLAS_Order:
5
+ RowMajor # C contiguous
6
+ ColMajor # Fortran contiguous
7
+
8
+
9
+ cpdef enum BLAS_Trans:
10
+ NoTrans = 110 # correspond to 'n'
11
+ Trans = 116 # correspond to 't'
12
+
13
+
14
+ # BLAS Level 1 ################################################################
15
+ cdef floating _dot(int, const floating*, int, const floating*, int) noexcept nogil
16
+
17
+ cdef floating _asum(int, const floating*, int) noexcept nogil
18
+
19
+ cdef void _axpy(int, floating, const floating*, int, floating*, int) noexcept nogil
20
+
21
+ cdef floating _nrm2(int, const floating*, int) noexcept nogil
22
+
23
+ cdef void _copy(int, const floating*, int, const floating*, int) noexcept nogil
24
+
25
+ cdef void _scal(int, floating, const floating*, int) noexcept nogil
26
+
27
+ cdef void _rotg(floating*, floating*, floating*, floating*) noexcept nogil
28
+
29
+ cdef void _rot(int, floating*, int, floating*, int, floating, floating) noexcept nogil
30
+
31
+ # BLAS Level 2 ################################################################
32
+ cdef void _gemv(BLAS_Order, BLAS_Trans, int, int, floating, const floating*, int,
33
+ const floating*, int, floating, floating*, int) noexcept nogil
34
+
35
+ cdef void _ger(BLAS_Order, int, int, floating, const floating*, int, const floating*,
36
+ int, floating*, int) noexcept nogil
37
+
38
+ # BLASLevel 3 ################################################################
39
+ cdef void _gemm(BLAS_Order, BLAS_Trans, BLAS_Trans, int, int, int, floating,
40
+ const floating*, int, const floating*, int, floating, floating*,
41
+ int) noexcept nogil
venv/lib/python3.10/site-packages/sklearn/utils/_fast_dict.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (288 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/_heap.pxd ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Heap routines, used in various Cython implementations.
2
+
3
+ from cython cimport floating
4
+
5
+ from ._typedefs cimport intp_t
6
+
7
+
8
+ cdef int heap_push(
9
+ floating* values,
10
+ intp_t* indices,
11
+ intp_t size,
12
+ floating val,
13
+ intp_t val_idx,
14
+ ) noexcept nogil
venv/lib/python3.10/site-packages/sklearn/utils/_mask.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import suppress
2
+
3
+ import numpy as np
4
+ from scipy import sparse as sp
5
+
6
+ from . import is_scalar_nan
7
+ from .fixes import _object_dtype_isnan
8
+
9
+
10
+ def _get_dense_mask(X, value_to_mask):
11
+ with suppress(ImportError, AttributeError):
12
+ # We also suppress `AttributeError` because older versions of pandas do
13
+ # not have `NA`.
14
+ import pandas
15
+
16
+ if value_to_mask is pandas.NA:
17
+ return pandas.isna(X)
18
+
19
+ if is_scalar_nan(value_to_mask):
20
+ if X.dtype.kind == "f":
21
+ Xt = np.isnan(X)
22
+ elif X.dtype.kind in ("i", "u"):
23
+ # can't have NaNs in integer array.
24
+ Xt = np.zeros(X.shape, dtype=bool)
25
+ else:
26
+ # np.isnan does not work on object dtypes.
27
+ Xt = _object_dtype_isnan(X)
28
+ else:
29
+ Xt = X == value_to_mask
30
+
31
+ return Xt
32
+
33
+
34
+ def _get_mask(X, value_to_mask):
35
+ """Compute the boolean mask X == value_to_mask.
36
+
37
+ Parameters
38
+ ----------
39
+ X : {ndarray, sparse matrix} of shape (n_samples, n_features)
40
+ Input data, where ``n_samples`` is the number of samples and
41
+ ``n_features`` is the number of features.
42
+
43
+ value_to_mask : {int, float}
44
+ The value which is to be masked in X.
45
+
46
+ Returns
47
+ -------
48
+ X_mask : {ndarray, sparse matrix} of shape (n_samples, n_features)
49
+ Missing mask.
50
+ """
51
+ if not sp.issparse(X):
52
+ # For all cases apart of a sparse input where we need to reconstruct
53
+ # a sparse output
54
+ return _get_dense_mask(X, value_to_mask)
55
+
56
+ Xt = _get_dense_mask(X.data, value_to_mask)
57
+
58
+ sparse_constructor = sp.csr_matrix if X.format == "csr" else sp.csc_matrix
59
+ Xt_sparse = sparse_constructor(
60
+ (Xt, X.indices.copy(), X.indptr.copy()), shape=X.shape, dtype=bool
61
+ )
62
+
63
+ return Xt_sparse
venv/lib/python3.10/site-packages/sklearn/utils/_mocking.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from ..base import BaseEstimator, ClassifierMixin
4
+ from ..utils._metadata_requests import RequestMethod
5
+ from .metaestimators import available_if
6
+ from .validation import _check_sample_weight, _num_samples, check_array, check_is_fitted
7
+
8
+
9
+ class ArraySlicingWrapper:
10
+ """
11
+ Parameters
12
+ ----------
13
+ array
14
+ """
15
+
16
+ def __init__(self, array):
17
+ self.array = array
18
+
19
+ def __getitem__(self, aslice):
20
+ return MockDataFrame(self.array[aslice])
21
+
22
+
23
+ class MockDataFrame:
24
+ """
25
+ Parameters
26
+ ----------
27
+ array
28
+ """
29
+
30
+ # have shape and length but don't support indexing.
31
+
32
+ def __init__(self, array):
33
+ self.array = array
34
+ self.values = array
35
+ self.shape = array.shape
36
+ self.ndim = array.ndim
37
+ # ugly hack to make iloc work.
38
+ self.iloc = ArraySlicingWrapper(array)
39
+
40
+ def __len__(self):
41
+ return len(self.array)
42
+
43
+ def __array__(self, dtype=None):
44
+ # Pandas data frames also are array-like: we want to make sure that
45
+ # input validation in cross-validation does not try to call that
46
+ # method.
47
+ return self.array
48
+
49
+ def __eq__(self, other):
50
+ return MockDataFrame(self.array == other.array)
51
+
52
+ def __ne__(self, other):
53
+ return not self == other
54
+
55
+ def take(self, indices, axis=0):
56
+ return MockDataFrame(self.array.take(indices, axis=axis))
57
+
58
+
59
+ class CheckingClassifier(ClassifierMixin, BaseEstimator):
60
+ """Dummy classifier to test pipelining and meta-estimators.
61
+
62
+ Checks some property of `X` and `y`in fit / predict.
63
+ This allows testing whether pipelines / cross-validation or metaestimators
64
+ changed the input.
65
+
66
+ Can also be used to check if `fit_params` are passed correctly, and
67
+ to force a certain score to be returned.
68
+
69
+ Parameters
70
+ ----------
71
+ check_y, check_X : callable, default=None
72
+ The callable used to validate `X` and `y`. These callable should return
73
+ a bool where `False` will trigger an `AssertionError`. If `None`, the
74
+ data is not validated. Default is `None`.
75
+
76
+ check_y_params, check_X_params : dict, default=None
77
+ The optional parameters to pass to `check_X` and `check_y`. If `None`,
78
+ then no parameters are passed in.
79
+
80
+ methods_to_check : "all" or list of str, default="all"
81
+ The methods in which the checks should be applied. By default,
82
+ all checks will be done on all methods (`fit`, `predict`,
83
+ `predict_proba`, `decision_function` and `score`).
84
+
85
+ foo_param : int, default=0
86
+ A `foo` param. When `foo > 1`, the output of :meth:`score` will be 1
87
+ otherwise it is 0.
88
+
89
+ expected_sample_weight : bool, default=False
90
+ Whether to check if a valid `sample_weight` was passed to `fit`.
91
+
92
+ expected_fit_params : list of str, default=None
93
+ A list of the expected parameters given when calling `fit`.
94
+
95
+ Attributes
96
+ ----------
97
+ classes_ : int
98
+ The classes seen during `fit`.
99
+
100
+ n_features_in_ : int
101
+ The number of features seen during `fit`.
102
+
103
+ Examples
104
+ --------
105
+ >>> from sklearn.utils._mocking import CheckingClassifier
106
+
107
+ This helper allow to assert to specificities regarding `X` or `y`. In this
108
+ case we expect `check_X` or `check_y` to return a boolean.
109
+
110
+ >>> from sklearn.datasets import load_iris
111
+ >>> X, y = load_iris(return_X_y=True)
112
+ >>> clf = CheckingClassifier(check_X=lambda x: x.shape == (150, 4))
113
+ >>> clf.fit(X, y)
114
+ CheckingClassifier(...)
115
+
116
+ We can also provide a check which might raise an error. In this case, we
117
+ expect `check_X` to return `X` and `check_y` to return `y`.
118
+
119
+ >>> from sklearn.utils import check_array
120
+ >>> clf = CheckingClassifier(check_X=check_array)
121
+ >>> clf.fit(X, y)
122
+ CheckingClassifier(...)
123
+ """
124
+
125
+ def __init__(
126
+ self,
127
+ *,
128
+ check_y=None,
129
+ check_y_params=None,
130
+ check_X=None,
131
+ check_X_params=None,
132
+ methods_to_check="all",
133
+ foo_param=0,
134
+ expected_sample_weight=None,
135
+ expected_fit_params=None,
136
+ ):
137
+ self.check_y = check_y
138
+ self.check_y_params = check_y_params
139
+ self.check_X = check_X
140
+ self.check_X_params = check_X_params
141
+ self.methods_to_check = methods_to_check
142
+ self.foo_param = foo_param
143
+ self.expected_sample_weight = expected_sample_weight
144
+ self.expected_fit_params = expected_fit_params
145
+
146
+ def _check_X_y(self, X, y=None, should_be_fitted=True):
147
+ """Validate X and y and make extra check.
148
+
149
+ Parameters
150
+ ----------
151
+ X : array-like of shape (n_samples, n_features)
152
+ The data set.
153
+ `X` is checked only if `check_X` is not `None` (default is None).
154
+ y : array-like of shape (n_samples), default=None
155
+ The corresponding target, by default `None`.
156
+ `y` is checked only if `check_y` is not `None` (default is None).
157
+ should_be_fitted : bool, default=True
158
+ Whether or not the classifier should be already fitted.
159
+ By default True.
160
+
161
+ Returns
162
+ -------
163
+ X, y
164
+ """
165
+ if should_be_fitted:
166
+ check_is_fitted(self)
167
+ if self.check_X is not None:
168
+ params = {} if self.check_X_params is None else self.check_X_params
169
+ checked_X = self.check_X(X, **params)
170
+ if isinstance(checked_X, (bool, np.bool_)):
171
+ assert checked_X
172
+ else:
173
+ X = checked_X
174
+ if y is not None and self.check_y is not None:
175
+ params = {} if self.check_y_params is None else self.check_y_params
176
+ checked_y = self.check_y(y, **params)
177
+ if isinstance(checked_y, (bool, np.bool_)):
178
+ assert checked_y
179
+ else:
180
+ y = checked_y
181
+ return X, y
182
+
183
+ def fit(self, X, y, sample_weight=None, **fit_params):
184
+ """Fit classifier.
185
+
186
+ Parameters
187
+ ----------
188
+ X : array-like of shape (n_samples, n_features)
189
+ Training vector, where `n_samples` is the number of samples and
190
+ `n_features` is the number of features.
191
+
192
+ y : array-like of shape (n_samples, n_outputs) or (n_samples,), \
193
+ default=None
194
+ Target relative to X for classification or regression;
195
+ None for unsupervised learning.
196
+
197
+ sample_weight : array-like of shape (n_samples,), default=None
198
+ Sample weights. If None, then samples are equally weighted.
199
+
200
+ **fit_params : dict of string -> object
201
+ Parameters passed to the ``fit`` method of the estimator
202
+
203
+ Returns
204
+ -------
205
+ self
206
+ """
207
+ assert _num_samples(X) == _num_samples(y)
208
+ if self.methods_to_check == "all" or "fit" in self.methods_to_check:
209
+ X, y = self._check_X_y(X, y, should_be_fitted=False)
210
+ self.n_features_in_ = np.shape(X)[1]
211
+ self.classes_ = np.unique(check_array(y, ensure_2d=False, allow_nd=True))
212
+ if self.expected_fit_params:
213
+ missing = set(self.expected_fit_params) - set(fit_params)
214
+ if missing:
215
+ raise AssertionError(
216
+ f"Expected fit parameter(s) {list(missing)} not seen."
217
+ )
218
+ for key, value in fit_params.items():
219
+ if _num_samples(value) != _num_samples(X):
220
+ raise AssertionError(
221
+ f"Fit parameter {key} has length {_num_samples(value)}"
222
+ f"; expected {_num_samples(X)}."
223
+ )
224
+ if self.expected_sample_weight:
225
+ if sample_weight is None:
226
+ raise AssertionError("Expected sample_weight to be passed")
227
+ _check_sample_weight(sample_weight, X)
228
+
229
+ return self
230
+
231
+ def predict(self, X):
232
+ """Predict the first class seen in `classes_`.
233
+
234
+ Parameters
235
+ ----------
236
+ X : array-like of shape (n_samples, n_features)
237
+ The input data.
238
+
239
+ Returns
240
+ -------
241
+ preds : ndarray of shape (n_samples,)
242
+ Predictions of the first class seens in `classes_`.
243
+ """
244
+ if self.methods_to_check == "all" or "predict" in self.methods_to_check:
245
+ X, y = self._check_X_y(X)
246
+ return self.classes_[np.zeros(_num_samples(X), dtype=int)]
247
+
248
+ def predict_proba(self, X):
249
+ """Predict probabilities for each class.
250
+
251
+ Here, the dummy classifier will provide a probability of 1 for the
252
+ first class of `classes_` and 0 otherwise.
253
+
254
+ Parameters
255
+ ----------
256
+ X : array-like of shape (n_samples, n_features)
257
+ The input data.
258
+
259
+ Returns
260
+ -------
261
+ proba : ndarray of shape (n_samples, n_classes)
262
+ The probabilities for each sample and class.
263
+ """
264
+ if self.methods_to_check == "all" or "predict_proba" in self.methods_to_check:
265
+ X, y = self._check_X_y(X)
266
+ proba = np.zeros((_num_samples(X), len(self.classes_)))
267
+ proba[:, 0] = 1
268
+ return proba
269
+
270
+ def decision_function(self, X):
271
+ """Confidence score.
272
+
273
+ Parameters
274
+ ----------
275
+ X : array-like of shape (n_samples, n_features)
276
+ The input data.
277
+
278
+ Returns
279
+ -------
280
+ decision : ndarray of shape (n_samples,) if n_classes == 2\
281
+ else (n_samples, n_classes)
282
+ Confidence score.
283
+ """
284
+ if (
285
+ self.methods_to_check == "all"
286
+ or "decision_function" in self.methods_to_check
287
+ ):
288
+ X, y = self._check_X_y(X)
289
+ if len(self.classes_) == 2:
290
+ # for binary classifier, the confidence score is related to
291
+ # classes_[1] and therefore should be null.
292
+ return np.zeros(_num_samples(X))
293
+ else:
294
+ decision = np.zeros((_num_samples(X), len(self.classes_)))
295
+ decision[:, 0] = 1
296
+ return decision
297
+
298
+ def score(self, X=None, Y=None):
299
+ """Fake score.
300
+
301
+ Parameters
302
+ ----------
303
+ X : array-like of shape (n_samples, n_features)
304
+ Input data, where `n_samples` is the number of samples and
305
+ `n_features` is the number of features.
306
+
307
+ Y : array-like of shape (n_samples, n_output) or (n_samples,)
308
+ Target relative to X for classification or regression;
309
+ None for unsupervised learning.
310
+
311
+ Returns
312
+ -------
313
+ score : float
314
+ Either 0 or 1 depending of `foo_param` (i.e. `foo_param > 1 =>
315
+ score=1` otherwise `score=0`).
316
+ """
317
+ if self.methods_to_check == "all" or "score" in self.methods_to_check:
318
+ self._check_X_y(X, Y)
319
+ if self.foo_param > 1:
320
+ score = 1.0
321
+ else:
322
+ score = 0.0
323
+ return score
324
+
325
+ def _more_tags(self):
326
+ return {"_skip_test": True, "X_types": ["1dlabel"]}
327
+
328
+
329
+ # Deactivate key validation for CheckingClassifier because we want to be able to
330
+ # call fit with arbitrary fit_params and record them. Without this change, we
331
+ # would get an error because those arbitrary params are not expected.
332
+ CheckingClassifier.set_fit_request = RequestMethod( # type: ignore
333
+ name="fit", keys=[], validate_keys=False
334
+ )
335
+
336
+
337
+ class NoSampleWeightWrapper(BaseEstimator):
338
+ """Wrap estimator which will not expose `sample_weight`.
339
+
340
+ Parameters
341
+ ----------
342
+ est : estimator, default=None
343
+ The estimator to wrap.
344
+ """
345
+
346
+ def __init__(self, est=None):
347
+ self.est = est
348
+
349
+ def fit(self, X, y):
350
+ return self.est.fit(X, y)
351
+
352
+ def predict(self, X):
353
+ return self.est.predict(X)
354
+
355
+ def predict_proba(self, X):
356
+ return self.est.predict_proba(X)
357
+
358
+ def _more_tags(self):
359
+ return {"_skip_test": True}
360
+
361
+
362
+ def _check_response(method):
363
+ def check(self):
364
+ return self.response_methods is not None and method in self.response_methods
365
+
366
+ return check
367
+
368
+
369
+ class _MockEstimatorOnOffPrediction(BaseEstimator):
370
+ """Estimator for which we can turn on/off the prediction methods.
371
+
372
+ Parameters
373
+ ----------
374
+ response_methods: list of \
375
+ {"predict", "predict_proba", "decision_function"}, default=None
376
+ List containing the response implemented by the estimator. When, the
377
+ response is in the list, it will return the name of the response method
378
+ when called. Otherwise, an `AttributeError` is raised. It allows to
379
+ use `getattr` as any conventional estimator. By default, no response
380
+ methods are mocked.
381
+ """
382
+
383
+ def __init__(self, response_methods=None):
384
+ self.response_methods = response_methods
385
+
386
+ def fit(self, X, y):
387
+ self.classes_ = np.unique(y)
388
+ return self
389
+
390
+ @available_if(_check_response("predict"))
391
+ def predict(self, X):
392
+ return "predict"
393
+
394
+ @available_if(_check_response("predict_proba"))
395
+ def predict_proba(self, X):
396
+ return "predict_proba"
397
+
398
+ @available_if(_check_response("decision_function"))
399
+ def decision_function(self, X):
400
+ return "decision_function"
venv/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (80.6 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/_plotting.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from . import check_consistent_length, check_matplotlib_support
4
+ from ._response import _get_response_values_binary
5
+ from .multiclass import type_of_target
6
+ from .validation import _check_pos_label_consistency
7
+
8
+
9
+ class _BinaryClassifierCurveDisplayMixin:
10
+ """Mixin class to be used in Displays requiring a binary classifier.
11
+
12
+ The aim of this class is to centralize some validations regarding the estimator and
13
+ the target and gather the response of the estimator.
14
+ """
15
+
16
+ def _validate_plot_params(self, *, ax=None, name=None):
17
+ check_matplotlib_support(f"{self.__class__.__name__}.plot")
18
+ import matplotlib.pyplot as plt
19
+
20
+ if ax is None:
21
+ _, ax = plt.subplots()
22
+
23
+ name = self.estimator_name if name is None else name
24
+ return ax, ax.figure, name
25
+
26
+ @classmethod
27
+ def _validate_and_get_response_values(
28
+ cls, estimator, X, y, *, response_method="auto", pos_label=None, name=None
29
+ ):
30
+ check_matplotlib_support(f"{cls.__name__}.from_estimator")
31
+
32
+ name = estimator.__class__.__name__ if name is None else name
33
+
34
+ y_pred, pos_label = _get_response_values_binary(
35
+ estimator,
36
+ X,
37
+ response_method=response_method,
38
+ pos_label=pos_label,
39
+ )
40
+
41
+ return y_pred, pos_label, name
42
+
43
+ @classmethod
44
+ def _validate_from_predictions_params(
45
+ cls, y_true, y_pred, *, sample_weight=None, pos_label=None, name=None
46
+ ):
47
+ check_matplotlib_support(f"{cls.__name__}.from_predictions")
48
+
49
+ if type_of_target(y_true) != "binary":
50
+ raise ValueError(
51
+ f"The target y is not binary. Got {type_of_target(y_true)} type of"
52
+ " target."
53
+ )
54
+
55
+ check_consistent_length(y_true, y_pred, sample_weight)
56
+ pos_label = _check_pos_label_consistency(pos_label, y_true)
57
+
58
+ name = name if name is not None else "Classifier"
59
+
60
+ return pos_label, name
61
+
62
+
63
+ def _validate_score_name(score_name, scoring, negate_score):
64
+ """Validate the `score_name` parameter.
65
+
66
+ If `score_name` is provided, we just return it as-is.
67
+ If `score_name` is `None`, we use `Score` if `negate_score` is `False` and
68
+ `Negative score` otherwise.
69
+ If `score_name` is a string or a callable, we infer the name. We replace `_` by
70
+ spaces and capitalize the first letter. We remove `neg_` and replace it by
71
+ `"Negative"` if `negate_score` is `False` or just remove it otherwise.
72
+ """
73
+ if score_name is not None:
74
+ return score_name
75
+ elif scoring is None:
76
+ return "Negative score" if negate_score else "Score"
77
+ else:
78
+ score_name = scoring.__name__ if callable(scoring) else scoring
79
+ if negate_score:
80
+ if score_name.startswith("neg_"):
81
+ score_name = score_name[4:]
82
+ else:
83
+ score_name = f"Negative {score_name}"
84
+ elif score_name.startswith("neg_"):
85
+ score_name = f"Negative {score_name[4:]}"
86
+ score_name = score_name.replace("_", " ")
87
+ return score_name.capitalize()
88
+
89
+
90
+ def _interval_max_min_ratio(data):
91
+ """Compute the ratio between the largest and smallest inter-point distances.
92
+
93
+ A value larger than 5 typically indicates that the parameter range would
94
+ better be displayed with a log scale while a linear scale would be more
95
+ suitable otherwise.
96
+ """
97
+ diff = np.diff(np.sort(data))
98
+ return diff.max() / diff.min()
venv/lib/python3.10/site-packages/sklearn/utils/_random.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (356 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/_response.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities to get the response values of a classifier or a regressor.
2
+
3
+ It allows to make uniform checks and validation.
4
+ """
5
+ import numpy as np
6
+
7
+ from ..base import is_classifier
8
+ from .multiclass import type_of_target
9
+ from .validation import _check_response_method, check_is_fitted
10
+
11
+
12
+ def _process_predict_proba(*, y_pred, target_type, classes, pos_label):
13
+ """Get the response values when the response method is `predict_proba`.
14
+
15
+ This function process the `y_pred` array in the binary and multi-label cases.
16
+ In the binary case, it selects the column corresponding to the positive
17
+ class. In the multi-label case, it stacks the predictions if they are not
18
+ in the "compressed" format `(n_samples, n_outputs)`.
19
+
20
+ Parameters
21
+ ----------
22
+ y_pred : ndarray
23
+ Output of `estimator.predict_proba`. The shape depends on the target type:
24
+
25
+ - for binary classification, it is a 2d array of shape `(n_samples, 2)`;
26
+ - for multiclass classification, it is a 2d array of shape
27
+ `(n_samples, n_classes)`;
28
+ - for multilabel classification, it is either a list of 2d arrays of shape
29
+ `(n_samples, 2)` (e.g. `RandomForestClassifier` or `KNeighborsClassifier`) or
30
+ an array of shape `(n_samples, n_outputs)` (e.g. `MLPClassifier` or
31
+ `RidgeClassifier`).
32
+
33
+ target_type : {"binary", "multiclass", "multilabel-indicator"}
34
+ Type of the target.
35
+
36
+ classes : ndarray of shape (n_classes,) or list of such arrays
37
+ Class labels as reported by `estimator.classes_`.
38
+
39
+ pos_label : int, float, bool or str
40
+ Only used with binary and multiclass targets.
41
+
42
+ Returns
43
+ -------
44
+ y_pred : ndarray of shape (n_samples,), (n_samples, n_classes) or \
45
+ (n_samples, n_output)
46
+ Compressed predictions format as requested by the metrics.
47
+ """
48
+ if target_type == "binary" and y_pred.shape[1] < 2:
49
+ # We don't handle classifiers trained on a single class.
50
+ raise ValueError(
51
+ f"Got predict_proba of shape {y_pred.shape}, but need "
52
+ "classifier with two classes."
53
+ )
54
+
55
+ if target_type == "binary":
56
+ col_idx = np.flatnonzero(classes == pos_label)[0]
57
+ return y_pred[:, col_idx]
58
+ elif target_type == "multilabel-indicator":
59
+ # Use a compress format of shape `(n_samples, n_output)`.
60
+ # Only `MLPClassifier` and `RidgeClassifier` return an array of shape
61
+ # `(n_samples, n_outputs)`.
62
+ if isinstance(y_pred, list):
63
+ # list of arrays of shape `(n_samples, 2)`
64
+ return np.vstack([p[:, -1] for p in y_pred]).T
65
+ else:
66
+ # array of shape `(n_samples, n_outputs)`
67
+ return y_pred
68
+
69
+ return y_pred
70
+
71
+
72
+ def _process_decision_function(*, y_pred, target_type, classes, pos_label):
73
+ """Get the response values when the response method is `decision_function`.
74
+
75
+ This function process the `y_pred` array in the binary and multi-label cases.
76
+ In the binary case, it inverts the sign of the score if the positive label
77
+ is not `classes[1]`. In the multi-label case, it stacks the predictions if
78
+ they are not in the "compressed" format `(n_samples, n_outputs)`.
79
+
80
+ Parameters
81
+ ----------
82
+ y_pred : ndarray
83
+ Output of `estimator.predict_proba`. The shape depends on the target type:
84
+
85
+ - for binary classification, it is a 1d array of shape `(n_samples,)` where the
86
+ sign is assuming that `classes[1]` is the positive class;
87
+ - for multiclass classification, it is a 2d array of shape
88
+ `(n_samples, n_classes)`;
89
+ - for multilabel classification, it is a 2d array of shape `(n_samples,
90
+ n_outputs)`.
91
+
92
+ target_type : {"binary", "multiclass", "multilabel-indicator"}
93
+ Type of the target.
94
+
95
+ classes : ndarray of shape (n_classes,) or list of such arrays
96
+ Class labels as reported by `estimator.classes_`.
97
+
98
+ pos_label : int, float, bool or str
99
+ Only used with binary and multiclass targets.
100
+
101
+ Returns
102
+ -------
103
+ y_pred : ndarray of shape (n_samples,), (n_samples, n_classes) or \
104
+ (n_samples, n_output)
105
+ Compressed predictions format as requested by the metrics.
106
+ """
107
+ if target_type == "binary" and pos_label == classes[0]:
108
+ return -1 * y_pred
109
+ return y_pred
110
+
111
+
112
+ def _get_response_values(
113
+ estimator,
114
+ X,
115
+ response_method,
116
+ pos_label=None,
117
+ return_response_method_used=False,
118
+ ):
119
+ """Compute the response values of a classifier, an outlier detector, or a regressor.
120
+
121
+ The response values are predictions such that it follows the following shape:
122
+
123
+ - for binary classification, it is a 1d array of shape `(n_samples,)`;
124
+ - for multiclass classification, it is a 2d array of shape `(n_samples, n_classes)`;
125
+ - for multilabel classification, it is a 2d array of shape `(n_samples, n_outputs)`;
126
+ - for outlier detection, it is a 1d array of shape `(n_samples,)`;
127
+ - for regression, it is a 1d array of shape `(n_samples,)`.
128
+
129
+ If `estimator` is a binary classifier, also return the label for the
130
+ effective positive class.
131
+
132
+ This utility is used primarily in the displays and the scikit-learn scorers.
133
+
134
+ .. versionadded:: 1.3
135
+
136
+ Parameters
137
+ ----------
138
+ estimator : estimator instance
139
+ Fitted classifier, outlier detector, or regressor or a
140
+ fitted :class:`~sklearn.pipeline.Pipeline` in which the last estimator is a
141
+ classifier, an outlier detector, or a regressor.
142
+
143
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
144
+ Input values.
145
+
146
+ response_method : {"predict_proba", "predict_log_proba", "decision_function", \
147
+ "predict"} or list of such str
148
+ Specifies the response method to use get prediction from an estimator
149
+ (i.e. :term:`predict_proba`, :term:`predict_log_proba`,
150
+ :term:`decision_function` or :term:`predict`). Possible choices are:
151
+
152
+ - if `str`, it corresponds to the name to the method to return;
153
+ - if a list of `str`, it provides the method names in order of
154
+ preference. The method returned corresponds to the first method in
155
+ the list and which is implemented by `estimator`.
156
+
157
+ pos_label : int, float, bool or str, default=None
158
+ The class considered as the positive class when computing
159
+ the metrics. If `None` and target is 'binary', `estimators.classes_[1]` is
160
+ considered as the positive class.
161
+
162
+ return_response_method_used : bool, default=False
163
+ Whether to return the response method used to compute the response
164
+ values.
165
+
166
+ .. versionadded:: 1.4
167
+
168
+ Returns
169
+ -------
170
+ y_pred : ndarray of shape (n_samples,), (n_samples, n_classes) or \
171
+ (n_samples, n_outputs)
172
+ Target scores calculated from the provided `response_method`
173
+ and `pos_label`.
174
+
175
+ pos_label : int, float, bool, str or None
176
+ The class considered as the positive class when computing
177
+ the metrics. Returns `None` if `estimator` is a regressor or an outlier
178
+ detector.
179
+
180
+ response_method_used : str
181
+ The response method used to compute the response values. Only returned
182
+ if `return_response_method_used` is `True`.
183
+
184
+ .. versionadded:: 1.4
185
+
186
+ Raises
187
+ ------
188
+ ValueError
189
+ If `pos_label` is not a valid label.
190
+ If the shape of `y_pred` is not consistent for binary classifier.
191
+ If the response method can be applied to a classifier only and
192
+ `estimator` is a regressor.
193
+ """
194
+ from sklearn.base import is_classifier, is_outlier_detector # noqa
195
+
196
+ if is_classifier(estimator):
197
+ prediction_method = _check_response_method(estimator, response_method)
198
+ classes = estimator.classes_
199
+ target_type = type_of_target(classes)
200
+
201
+ if target_type in ("binary", "multiclass"):
202
+ if pos_label is not None and pos_label not in classes.tolist():
203
+ raise ValueError(
204
+ f"pos_label={pos_label} is not a valid label: It should be "
205
+ f"one of {classes}"
206
+ )
207
+ elif pos_label is None and target_type == "binary":
208
+ pos_label = classes[-1]
209
+
210
+ y_pred = prediction_method(X)
211
+
212
+ if prediction_method.__name__ in ("predict_proba", "predict_log_proba"):
213
+ y_pred = _process_predict_proba(
214
+ y_pred=y_pred,
215
+ target_type=target_type,
216
+ classes=classes,
217
+ pos_label=pos_label,
218
+ )
219
+ elif prediction_method.__name__ == "decision_function":
220
+ y_pred = _process_decision_function(
221
+ y_pred=y_pred,
222
+ target_type=target_type,
223
+ classes=classes,
224
+ pos_label=pos_label,
225
+ )
226
+ elif is_outlier_detector(estimator):
227
+ prediction_method = _check_response_method(estimator, response_method)
228
+ y_pred, pos_label = prediction_method(X), None
229
+ else: # estimator is a regressor
230
+ if response_method != "predict":
231
+ raise ValueError(
232
+ f"{estimator.__class__.__name__} should either be a classifier to be "
233
+ f"used with response_method={response_method} or the response_method "
234
+ "should be 'predict'. Got a regressor with response_method="
235
+ f"{response_method} instead."
236
+ )
237
+ prediction_method = estimator.predict
238
+ y_pred, pos_label = prediction_method(X), None
239
+
240
+ if return_response_method_used:
241
+ return y_pred, pos_label, prediction_method.__name__
242
+ return y_pred, pos_label
243
+
244
+
245
+ def _get_response_values_binary(estimator, X, response_method, pos_label=None):
246
+ """Compute the response values of a binary classifier.
247
+
248
+ Parameters
249
+ ----------
250
+ estimator : estimator instance
251
+ Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline`
252
+ in which the last estimator is a binary classifier.
253
+
254
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
255
+ Input values.
256
+
257
+ response_method : {'auto', 'predict_proba', 'decision_function'}
258
+ Specifies whether to use :term:`predict_proba` or
259
+ :term:`decision_function` as the target response. If set to 'auto',
260
+ :term:`predict_proba` is tried first and if it does not exist
261
+ :term:`decision_function` is tried next.
262
+
263
+ pos_label : int, float, bool or str, default=None
264
+ The class considered as the positive class when computing
265
+ the metrics. By default, `estimators.classes_[1]` is
266
+ considered as the positive class.
267
+
268
+ Returns
269
+ -------
270
+ y_pred : ndarray of shape (n_samples,)
271
+ Target scores calculated from the provided response_method
272
+ and pos_label.
273
+
274
+ pos_label : int, float, bool or str
275
+ The class considered as the positive class when computing
276
+ the metrics.
277
+ """
278
+ classification_error = "Expected 'estimator' to be a binary classifier."
279
+
280
+ check_is_fitted(estimator)
281
+ if not is_classifier(estimator):
282
+ raise ValueError(
283
+ classification_error + f" Got {estimator.__class__.__name__} instead."
284
+ )
285
+ elif len(estimator.classes_) != 2:
286
+ raise ValueError(
287
+ classification_error + f" Got {len(estimator.classes_)} classes instead."
288
+ )
289
+
290
+ if response_method == "auto":
291
+ response_method = ["predict_proba", "decision_function"]
292
+
293
+ return _get_response_values(
294
+ estimator,
295
+ X,
296
+ response_method,
297
+ pos_label=pos_label,
298
+ )
venv/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.pxd ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # WARNING: Do not edit this file directly.
2
+ # It is automatically generated from 'sklearn/utils/_seq_dataset.pxd.tp'.
3
+ # Changes must be made there.
4
+
5
+ """Dataset abstractions for sequential data access."""
6
+
7
+ cimport numpy as cnp
8
+
9
+ # SequentialDataset and its two concrete subclasses are (optionally randomized)
10
+ # iterators over the rows of a matrix X and corresponding target values y.
11
+
12
+ #------------------------------------------------------------------------------
13
+
14
+ cdef class SequentialDataset64:
15
+ cdef int current_index
16
+ cdef int[::1] index
17
+ cdef int *index_data_ptr
18
+ cdef Py_ssize_t n_samples
19
+ cdef cnp.uint32_t seed
20
+
21
+ cdef void shuffle(self, cnp.uint32_t seed) noexcept nogil
22
+ cdef int _get_next_index(self) noexcept nogil
23
+ cdef int _get_random_index(self) noexcept nogil
24
+
25
+ cdef void _sample(self, double **x_data_ptr, int **x_ind_ptr,
26
+ int *nnz, double *y, double *sample_weight,
27
+ int current_index) noexcept nogil
28
+ cdef void next(self, double **x_data_ptr, int **x_ind_ptr,
29
+ int *nnz, double *y, double *sample_weight) noexcept nogil
30
+ cdef int random(self, double **x_data_ptr, int **x_ind_ptr,
31
+ int *nnz, double *y, double *sample_weight) noexcept nogil
32
+
33
+
34
+ cdef class ArrayDataset64(SequentialDataset64):
35
+ cdef const double[:, ::1] X
36
+ cdef const double[::1] Y
37
+ cdef const double[::1] sample_weights
38
+ cdef Py_ssize_t n_features
39
+ cdef cnp.npy_intp X_stride
40
+ cdef double *X_data_ptr
41
+ cdef double *Y_data_ptr
42
+ cdef const int[::1] feature_indices
43
+ cdef int *feature_indices_ptr
44
+ cdef double *sample_weight_data
45
+
46
+
47
+ cdef class CSRDataset64(SequentialDataset64):
48
+ cdef const double[::1] X_data
49
+ cdef const int[::1] X_indptr
50
+ cdef const int[::1] X_indices
51
+ cdef const double[::1] Y
52
+ cdef const double[::1] sample_weights
53
+ cdef double *X_data_ptr
54
+ cdef int *X_indptr_ptr
55
+ cdef int *X_indices_ptr
56
+ cdef double *Y_data_ptr
57
+ cdef double *sample_weight_data
58
+
59
+ #------------------------------------------------------------------------------
60
+
61
+ cdef class SequentialDataset32:
62
+ cdef int current_index
63
+ cdef int[::1] index
64
+ cdef int *index_data_ptr
65
+ cdef Py_ssize_t n_samples
66
+ cdef cnp.uint32_t seed
67
+
68
+ cdef void shuffle(self, cnp.uint32_t seed) noexcept nogil
69
+ cdef int _get_next_index(self) noexcept nogil
70
+ cdef int _get_random_index(self) noexcept nogil
71
+
72
+ cdef void _sample(self, float **x_data_ptr, int **x_ind_ptr,
73
+ int *nnz, float *y, float *sample_weight,
74
+ int current_index) noexcept nogil
75
+ cdef void next(self, float **x_data_ptr, int **x_ind_ptr,
76
+ int *nnz, float *y, float *sample_weight) noexcept nogil
77
+ cdef int random(self, float **x_data_ptr, int **x_ind_ptr,
78
+ int *nnz, float *y, float *sample_weight) noexcept nogil
79
+
80
+
81
+ cdef class ArrayDataset32(SequentialDataset32):
82
+ cdef const float[:, ::1] X
83
+ cdef const float[::1] Y
84
+ cdef const float[::1] sample_weights
85
+ cdef Py_ssize_t n_features
86
+ cdef cnp.npy_intp X_stride
87
+ cdef float *X_data_ptr
88
+ cdef float *Y_data_ptr
89
+ cdef const int[::1] feature_indices
90
+ cdef int *feature_indices_ptr
91
+ cdef float *sample_weight_data
92
+
93
+
94
+ cdef class CSRDataset32(SequentialDataset32):
95
+ cdef const float[::1] X_data
96
+ cdef const int[::1] X_indptr
97
+ cdef const int[::1] X_indices
98
+ cdef const float[::1] Y
99
+ cdef const float[::1] sample_weights
100
+ cdef float *X_data_ptr
101
+ cdef int *X_indptr_ptr
102
+ cdef int *X_indices_ptr
103
+ cdef float *Y_data_ptr
104
+ cdef float *sample_weight_data
venv/lib/python3.10/site-packages/sklearn/utils/_set_output.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ from functools import wraps
3
+ from typing import Protocol, runtime_checkable
4
+
5
+ import numpy as np
6
+ from scipy.sparse import issparse
7
+
8
+ from .._config import get_config
9
+ from ._available_if import available_if
10
+
11
+
12
+ def check_library_installed(library):
13
+ """Check library is installed."""
14
+ try:
15
+ return importlib.import_module(library)
16
+ except ImportError as exc:
17
+ raise ImportError(
18
+ f"Setting output container to '{library}' requires {library} to be"
19
+ " installed"
20
+ ) from exc
21
+
22
+
23
+ def get_columns(columns):
24
+ if callable(columns):
25
+ try:
26
+ return columns()
27
+ except Exception:
28
+ return None
29
+ return columns
30
+
31
+
32
+ @runtime_checkable
33
+ class ContainerAdapterProtocol(Protocol):
34
+ container_lib: str
35
+
36
+ def create_container(self, X_output, X_original, columns, inplace=False):
37
+ """Create container from `X_output` with additional metadata.
38
+
39
+ Parameters
40
+ ----------
41
+ X_output : {ndarray, dataframe}
42
+ Data to wrap.
43
+
44
+ X_original : {ndarray, dataframe}
45
+ Original input dataframe. This is used to extract the metadata that should
46
+ be passed to `X_output`, e.g. pandas row index.
47
+
48
+ columns : callable, ndarray, or None
49
+ The column names or a callable that returns the column names. The
50
+ callable is useful if the column names require some computation. If `None`,
51
+ then no columns are passed to the container's constructor.
52
+
53
+ inplace : bool, default=False
54
+ Whether or not we intend to modify `X_output` in-place. However, it does
55
+ not guarantee that we return the same object if the in-place operation
56
+ is not possible.
57
+
58
+ Returns
59
+ -------
60
+ wrapped_output : container_type
61
+ `X_output` wrapped into the container type.
62
+ """
63
+
64
+ def is_supported_container(self, X):
65
+ """Return True if X is a supported container.
66
+
67
+ Parameters
68
+ ----------
69
+ Xs: container
70
+ Containers to be checked.
71
+
72
+ Returns
73
+ -------
74
+ is_supported_container : bool
75
+ True if X is a supported container.
76
+ """
77
+
78
+ def rename_columns(self, X, columns):
79
+ """Rename columns in `X`.
80
+
81
+ Parameters
82
+ ----------
83
+ X : container
84
+ Container which columns is updated.
85
+
86
+ columns : ndarray of str
87
+ Columns to update the `X`'s columns with.
88
+
89
+ Returns
90
+ -------
91
+ updated_container : container
92
+ Container with new names.
93
+ """
94
+
95
+ def hstack(self, Xs):
96
+ """Stack containers horizontally (column-wise).
97
+
98
+ Parameters
99
+ ----------
100
+ Xs : list of containers
101
+ List of containers to stack.
102
+
103
+ Returns
104
+ -------
105
+ stacked_Xs : container
106
+ Stacked containers.
107
+ """
108
+
109
+
110
+ class PandasAdapter:
111
+ container_lib = "pandas"
112
+
113
+ def create_container(self, X_output, X_original, columns, inplace=True):
114
+ pd = check_library_installed("pandas")
115
+ columns = get_columns(columns)
116
+
117
+ if not inplace or not isinstance(X_output, pd.DataFrame):
118
+ # In all these cases, we need to create a new DataFrame
119
+
120
+ # Unfortunately, we cannot use `getattr(container, "index")`
121
+ # because `list` exposes an `index` attribute.
122
+ if isinstance(X_output, pd.DataFrame):
123
+ index = X_output.index
124
+ elif isinstance(X_original, pd.DataFrame):
125
+ index = X_original.index
126
+ else:
127
+ index = None
128
+
129
+ # We don't pass columns here because it would intend columns selection
130
+ # instead of renaming.
131
+ X_output = pd.DataFrame(X_output, index=index, copy=not inplace)
132
+
133
+ if columns is not None:
134
+ return self.rename_columns(X_output, columns)
135
+ return X_output
136
+
137
+ def is_supported_container(self, X):
138
+ pd = check_library_installed("pandas")
139
+ return isinstance(X, pd.DataFrame)
140
+
141
+ def rename_columns(self, X, columns):
142
+ # we cannot use `rename` since it takes a dictionary and at this stage we have
143
+ # potentially duplicate column names in `X`
144
+ X.columns = columns
145
+ return X
146
+
147
+ def hstack(self, Xs):
148
+ pd = check_library_installed("pandas")
149
+ return pd.concat(Xs, axis=1)
150
+
151
+
152
+ class PolarsAdapter:
153
+ container_lib = "polars"
154
+
155
+ def create_container(self, X_output, X_original, columns, inplace=True):
156
+ pl = check_library_installed("polars")
157
+ columns = get_columns(columns)
158
+ columns = columns.tolist() if isinstance(columns, np.ndarray) else columns
159
+
160
+ if not inplace or not isinstance(X_output, pl.DataFrame):
161
+ # In all these cases, we need to create a new DataFrame
162
+ return pl.DataFrame(X_output, schema=columns, orient="row")
163
+
164
+ if columns is not None:
165
+ return self.rename_columns(X_output, columns)
166
+ return X_output
167
+
168
+ def is_supported_container(self, X):
169
+ pl = check_library_installed("polars")
170
+ return isinstance(X, pl.DataFrame)
171
+
172
+ def rename_columns(self, X, columns):
173
+ # we cannot use `rename` since it takes a dictionary and at this stage we have
174
+ # potentially duplicate column names in `X`
175
+ X.columns = columns
176
+ return X
177
+
178
+ def hstack(self, Xs):
179
+ pl = check_library_installed("polars")
180
+ return pl.concat(Xs, how="horizontal")
181
+
182
+
183
+ class ContainerAdaptersManager:
184
+ def __init__(self):
185
+ self.adapters = {}
186
+
187
+ @property
188
+ def supported_outputs(self):
189
+ return {"default"} | set(self.adapters)
190
+
191
+ def register(self, adapter):
192
+ self.adapters[adapter.container_lib] = adapter
193
+
194
+
195
+ ADAPTERS_MANAGER = ContainerAdaptersManager()
196
+ ADAPTERS_MANAGER.register(PandasAdapter())
197
+ ADAPTERS_MANAGER.register(PolarsAdapter())
198
+
199
+
200
+ def _get_container_adapter(method, estimator=None):
201
+ """Get container adapter."""
202
+ dense_config = _get_output_config(method, estimator)["dense"]
203
+ try:
204
+ return ADAPTERS_MANAGER.adapters[dense_config]
205
+ except KeyError:
206
+ return None
207
+
208
+
209
+ def _get_output_config(method, estimator=None):
210
+ """Get output config based on estimator and global configuration.
211
+
212
+ Parameters
213
+ ----------
214
+ method : {"transform"}
215
+ Estimator's method for which the output container is looked up.
216
+
217
+ estimator : estimator instance or None
218
+ Estimator to get the output configuration from. If `None`, check global
219
+ configuration is used.
220
+
221
+ Returns
222
+ -------
223
+ config : dict
224
+ Dictionary with keys:
225
+
226
+ - "dense": specifies the dense container for `method`. This can be
227
+ `"default"` or `"pandas"`.
228
+ """
229
+ est_sklearn_output_config = getattr(estimator, "_sklearn_output_config", {})
230
+ if method in est_sklearn_output_config:
231
+ dense_config = est_sklearn_output_config[method]
232
+ else:
233
+ dense_config = get_config()[f"{method}_output"]
234
+
235
+ supported_outputs = ADAPTERS_MANAGER.supported_outputs
236
+ if dense_config not in supported_outputs:
237
+ raise ValueError(
238
+ f"output config must be in {sorted(supported_outputs)}, got {dense_config}"
239
+ )
240
+
241
+ return {"dense": dense_config}
242
+
243
+
244
+ def _wrap_data_with_container(method, data_to_wrap, original_input, estimator):
245
+ """Wrap output with container based on an estimator's or global config.
246
+
247
+ Parameters
248
+ ----------
249
+ method : {"transform"}
250
+ Estimator's method to get container output for.
251
+
252
+ data_to_wrap : {ndarray, dataframe}
253
+ Data to wrap with container.
254
+
255
+ original_input : {ndarray, dataframe}
256
+ Original input of function.
257
+
258
+ estimator : estimator instance
259
+ Estimator with to get the output configuration from.
260
+
261
+ Returns
262
+ -------
263
+ output : {ndarray, dataframe}
264
+ If the output config is "default" or the estimator is not configured
265
+ for wrapping return `data_to_wrap` unchanged.
266
+ If the output config is "pandas", return `data_to_wrap` as a pandas
267
+ DataFrame.
268
+ """
269
+ output_config = _get_output_config(method, estimator)
270
+
271
+ if output_config["dense"] == "default" or not _auto_wrap_is_configured(estimator):
272
+ return data_to_wrap
273
+
274
+ dense_config = output_config["dense"]
275
+ if issparse(data_to_wrap):
276
+ raise ValueError(
277
+ "The transformer outputs a scipy sparse matrix. "
278
+ "Try to set the transformer output to a dense array or disable "
279
+ f"{dense_config.capitalize()} output with set_output(transform='default')."
280
+ )
281
+
282
+ adapter = ADAPTERS_MANAGER.adapters[dense_config]
283
+ return adapter.create_container(
284
+ data_to_wrap,
285
+ original_input,
286
+ columns=estimator.get_feature_names_out,
287
+ )
288
+
289
+
290
+ def _wrap_method_output(f, method):
291
+ """Wrapper used by `_SetOutputMixin` to automatically wrap methods."""
292
+
293
+ @wraps(f)
294
+ def wrapped(self, X, *args, **kwargs):
295
+ data_to_wrap = f(self, X, *args, **kwargs)
296
+ if isinstance(data_to_wrap, tuple):
297
+ # only wrap the first output for cross decomposition
298
+ return_tuple = (
299
+ _wrap_data_with_container(method, data_to_wrap[0], X, self),
300
+ *data_to_wrap[1:],
301
+ )
302
+ # Support for namedtuples `_make` is a documented API for namedtuples:
303
+ # https://docs.python.org/3/library/collections.html#collections.somenamedtuple._make
304
+ if hasattr(type(data_to_wrap), "_make"):
305
+ return type(data_to_wrap)._make(return_tuple)
306
+ return return_tuple
307
+
308
+ return _wrap_data_with_container(method, data_to_wrap, X, self)
309
+
310
+ return wrapped
311
+
312
+
313
+ def _auto_wrap_is_configured(estimator):
314
+ """Return True if estimator is configured for auto-wrapping the transform method.
315
+
316
+ `_SetOutputMixin` sets `_sklearn_auto_wrap_output_keys` to `set()` if auto wrapping
317
+ is manually disabled.
318
+ """
319
+ auto_wrap_output_keys = getattr(estimator, "_sklearn_auto_wrap_output_keys", set())
320
+ return (
321
+ hasattr(estimator, "get_feature_names_out")
322
+ and "transform" in auto_wrap_output_keys
323
+ )
324
+
325
+
326
+ class _SetOutputMixin:
327
+ """Mixin that dynamically wraps methods to return container based on config.
328
+
329
+ Currently `_SetOutputMixin` wraps `transform` and `fit_transform` and configures
330
+ it based on `set_output` of the global configuration.
331
+
332
+ `set_output` is only defined if `get_feature_names_out` is defined and
333
+ `auto_wrap_output_keys` is the default value.
334
+ """
335
+
336
+ def __init_subclass__(cls, auto_wrap_output_keys=("transform",), **kwargs):
337
+ super().__init_subclass__(**kwargs)
338
+
339
+ # Dynamically wraps `transform` and `fit_transform` and configure it's
340
+ # output based on `set_output`.
341
+ if not (
342
+ isinstance(auto_wrap_output_keys, tuple) or auto_wrap_output_keys is None
343
+ ):
344
+ raise ValueError("auto_wrap_output_keys must be None or a tuple of keys.")
345
+
346
+ if auto_wrap_output_keys is None:
347
+ cls._sklearn_auto_wrap_output_keys = set()
348
+ return
349
+
350
+ # Mapping from method to key in configurations
351
+ method_to_key = {
352
+ "transform": "transform",
353
+ "fit_transform": "transform",
354
+ }
355
+ cls._sklearn_auto_wrap_output_keys = set()
356
+
357
+ for method, key in method_to_key.items():
358
+ if not hasattr(cls, method) or key not in auto_wrap_output_keys:
359
+ continue
360
+ cls._sklearn_auto_wrap_output_keys.add(key)
361
+
362
+ # Only wrap methods defined by cls itself
363
+ if method not in cls.__dict__:
364
+ continue
365
+ wrapped_method = _wrap_method_output(getattr(cls, method), key)
366
+ setattr(cls, method, wrapped_method)
367
+
368
+ @available_if(_auto_wrap_is_configured)
369
+ def set_output(self, *, transform=None):
370
+ """Set output container.
371
+
372
+ See :ref:`sphx_glr_auto_examples_miscellaneous_plot_set_output.py`
373
+ for an example on how to use the API.
374
+
375
+ Parameters
376
+ ----------
377
+ transform : {"default", "pandas"}, default=None
378
+ Configure output of `transform` and `fit_transform`.
379
+
380
+ - `"default"`: Default output format of a transformer
381
+ - `"pandas"`: DataFrame output
382
+ - `"polars"`: Polars output
383
+ - `None`: Transform configuration is unchanged
384
+
385
+ .. versionadded:: 1.4
386
+ `"polars"` option was added.
387
+
388
+ Returns
389
+ -------
390
+ self : estimator instance
391
+ Estimator instance.
392
+ """
393
+ if transform is None:
394
+ return self
395
+
396
+ if not hasattr(self, "_sklearn_output_config"):
397
+ self._sklearn_output_config = {}
398
+
399
+ self._sklearn_output_config["transform"] = transform
400
+ return self
401
+
402
+
403
+ def _safe_set_output(estimator, *, transform=None):
404
+ """Safely call estimator.set_output and error if it not available.
405
+
406
+ This is used by meta-estimators to set the output for child estimators.
407
+
408
+ Parameters
409
+ ----------
410
+ estimator : estimator instance
411
+ Estimator instance.
412
+
413
+ transform : {"default", "pandas"}, default=None
414
+ Configure output of the following estimator's methods:
415
+
416
+ - `"transform"`
417
+ - `"fit_transform"`
418
+
419
+ If `None`, this operation is a no-op.
420
+
421
+ Returns
422
+ -------
423
+ estimator : estimator instance
424
+ Estimator instance.
425
+ """
426
+ set_output_for_transform = (
427
+ hasattr(estimator, "transform")
428
+ or hasattr(estimator, "fit_transform")
429
+ and transform is not None
430
+ )
431
+ if not set_output_for_transform:
432
+ # If estimator can not transform, then `set_output` does not need to be
433
+ # called.
434
+ return
435
+
436
+ if not hasattr(estimator, "set_output"):
437
+ raise ValueError(
438
+ f"Unable to configure output for {estimator} because `set_output` "
439
+ "is not available."
440
+ )
441
+ return estimator.set_output(transform=transform)
venv/lib/python3.10/site-packages/sklearn/utils/_sorting.pxd ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from ._typedefs cimport intp_t
2
+
3
+ from cython cimport floating
4
+
5
+ cdef int simultaneous_sort(
6
+ floating *dist,
7
+ intp_t *idx,
8
+ intp_t size,
9
+ ) noexcept nogil
venv/lib/python3.10/site-packages/sklearn/utils/_tags.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ _DEFAULT_TAGS = {
4
+ "array_api_support": False,
5
+ "non_deterministic": False,
6
+ "requires_positive_X": False,
7
+ "requires_positive_y": False,
8
+ "X_types": ["2darray"],
9
+ "poor_score": False,
10
+ "no_validation": False,
11
+ "multioutput": False,
12
+ "allow_nan": False,
13
+ "stateless": False,
14
+ "multilabel": False,
15
+ "_skip_test": False,
16
+ "_xfail_checks": False,
17
+ "multioutput_only": False,
18
+ "binary_only": False,
19
+ "requires_fit": True,
20
+ "preserves_dtype": [np.float64],
21
+ "requires_y": False,
22
+ "pairwise": False,
23
+ }
24
+
25
+
26
+ def _safe_tags(estimator, key=None):
27
+ """Safely get estimator tags.
28
+
29
+ :class:`~sklearn.BaseEstimator` provides the estimator tags machinery.
30
+ However, if an estimator does not inherit from this base class, we should
31
+ fall-back to the default tags.
32
+
33
+ For scikit-learn built-in estimators, we should still rely on
34
+ `self._get_tags()`. `_safe_tags(est)` should be used when we are not sure
35
+ where `est` comes from: typically `_safe_tags(self.base_estimator)` where
36
+ `self` is a meta-estimator, or in the common checks.
37
+
38
+ Parameters
39
+ ----------
40
+ estimator : estimator object
41
+ The estimator from which to get the tag.
42
+
43
+ key : str, default=None
44
+ Tag name to get. By default (`None`), all tags are returned.
45
+
46
+ Returns
47
+ -------
48
+ tags : dict or tag value
49
+ The estimator tags. A single value is returned if `key` is not None.
50
+ """
51
+ if hasattr(estimator, "_get_tags"):
52
+ tags_provider = "_get_tags()"
53
+ tags = estimator._get_tags()
54
+ elif hasattr(estimator, "_more_tags"):
55
+ tags_provider = "_more_tags()"
56
+ tags = {**_DEFAULT_TAGS, **estimator._more_tags()}
57
+ else:
58
+ tags_provider = "_DEFAULT_TAGS"
59
+ tags = _DEFAULT_TAGS
60
+
61
+ if key is not None:
62
+ if key not in tags:
63
+ raise ValueError(
64
+ f"The key {key} is not defined in {tags_provider} for the "
65
+ f"class {estimator.__class__.__name__}."
66
+ )
67
+ return tags[key]
68
+ return tags
venv/lib/python3.10/site-packages/sklearn/utils/_testing.py ADDED
@@ -0,0 +1,1169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Testing utilities."""
2
+
3
+ # Copyright (c) 2011, 2012
4
+ # Authors: Pietro Berkes,
5
+ # Andreas Muller
6
+ # Mathieu Blondel
7
+ # Olivier Grisel
8
+ # Arnaud Joly
9
+ # Denis Engemann
10
+ # Giorgio Patrini
11
+ # Thierry Guillemot
12
+ # License: BSD 3 clause
13
+ import atexit
14
+ import contextlib
15
+ import functools
16
+ import importlib
17
+ import inspect
18
+ import os
19
+ import os.path as op
20
+ import re
21
+ import shutil
22
+ import sys
23
+ import tempfile
24
+ import unittest
25
+ import warnings
26
+ from collections.abc import Iterable
27
+ from dataclasses import dataclass
28
+ from functools import wraps
29
+ from inspect import signature
30
+ from subprocess import STDOUT, CalledProcessError, TimeoutExpired, check_output
31
+ from unittest import TestCase
32
+
33
+ import joblib
34
+ import numpy as np
35
+ import scipy as sp
36
+ from numpy.testing import assert_allclose as np_assert_allclose
37
+ from numpy.testing import (
38
+ assert_almost_equal,
39
+ assert_approx_equal,
40
+ assert_array_almost_equal,
41
+ assert_array_equal,
42
+ assert_array_less,
43
+ assert_no_warnings,
44
+ )
45
+
46
+ import sklearn
47
+ from sklearn.utils import (
48
+ _IS_32BIT,
49
+ IS_PYPY,
50
+ _in_unstable_openblas_configuration,
51
+ )
52
+ from sklearn.utils._array_api import _check_array_api_dispatch
53
+ from sklearn.utils.fixes import VisibleDeprecationWarning, parse_version, sp_version
54
+ from sklearn.utils.multiclass import check_classification_targets
55
+ from sklearn.utils.validation import (
56
+ check_array,
57
+ check_is_fitted,
58
+ check_X_y,
59
+ )
60
+
61
+ __all__ = [
62
+ "assert_raises",
63
+ "assert_raises_regexp",
64
+ "assert_array_equal",
65
+ "assert_almost_equal",
66
+ "assert_array_almost_equal",
67
+ "assert_array_less",
68
+ "assert_approx_equal",
69
+ "assert_allclose",
70
+ "assert_run_python_script_without_output",
71
+ "assert_no_warnings",
72
+ "SkipTest",
73
+ ]
74
+
75
+ _dummy = TestCase("__init__")
76
+ assert_raises = _dummy.assertRaises
77
+ SkipTest = unittest.case.SkipTest
78
+ assert_dict_equal = _dummy.assertDictEqual
79
+
80
+ assert_raises_regex = _dummy.assertRaisesRegex
81
+ # assert_raises_regexp is deprecated in Python 3.4 in favor of
82
+ # assert_raises_regex but lets keep the backward compat in scikit-learn with
83
+ # the old name for now
84
+ assert_raises_regexp = assert_raises_regex
85
+
86
+
87
+ def ignore_warnings(obj=None, category=Warning):
88
+ """Context manager and decorator to ignore warnings.
89
+
90
+ Note: Using this (in both variants) will clear all warnings
91
+ from all python modules loaded. In case you need to test
92
+ cross-module-warning-logging, this is not your tool of choice.
93
+
94
+ Parameters
95
+ ----------
96
+ obj : callable, default=None
97
+ callable where you want to ignore the warnings.
98
+ category : warning class, default=Warning
99
+ The category to filter. If Warning, all categories will be muted.
100
+
101
+ Examples
102
+ --------
103
+ >>> import warnings
104
+ >>> from sklearn.utils._testing import ignore_warnings
105
+ >>> with ignore_warnings():
106
+ ... warnings.warn('buhuhuhu')
107
+
108
+ >>> def nasty_warn():
109
+ ... warnings.warn('buhuhuhu')
110
+ ... print(42)
111
+
112
+ >>> ignore_warnings(nasty_warn)()
113
+ 42
114
+ """
115
+ if isinstance(obj, type) and issubclass(obj, Warning):
116
+ # Avoid common pitfall of passing category as the first positional
117
+ # argument which result in the test not being run
118
+ warning_name = obj.__name__
119
+ raise ValueError(
120
+ "'obj' should be a callable where you want to ignore warnings. "
121
+ "You passed a warning class instead: 'obj={warning_name}'. "
122
+ "If you want to pass a warning class to ignore_warnings, "
123
+ "you should use 'category={warning_name}'".format(warning_name=warning_name)
124
+ )
125
+ elif callable(obj):
126
+ return _IgnoreWarnings(category=category)(obj)
127
+ else:
128
+ return _IgnoreWarnings(category=category)
129
+
130
+
131
+ class _IgnoreWarnings:
132
+ """Improved and simplified Python warnings context manager and decorator.
133
+
134
+ This class allows the user to ignore the warnings raised by a function.
135
+ Copied from Python 2.7.5 and modified as required.
136
+
137
+ Parameters
138
+ ----------
139
+ category : tuple of warning class, default=Warning
140
+ The category to filter. By default, all the categories will be muted.
141
+
142
+ """
143
+
144
+ def __init__(self, category):
145
+ self._record = True
146
+ self._module = sys.modules["warnings"]
147
+ self._entered = False
148
+ self.log = []
149
+ self.category = category
150
+
151
+ def __call__(self, fn):
152
+ """Decorator to catch and hide warnings without visual nesting."""
153
+
154
+ @wraps(fn)
155
+ def wrapper(*args, **kwargs):
156
+ with warnings.catch_warnings():
157
+ warnings.simplefilter("ignore", self.category)
158
+ return fn(*args, **kwargs)
159
+
160
+ return wrapper
161
+
162
+ def __repr__(self):
163
+ args = []
164
+ if self._record:
165
+ args.append("record=True")
166
+ if self._module is not sys.modules["warnings"]:
167
+ args.append("module=%r" % self._module)
168
+ name = type(self).__name__
169
+ return "%s(%s)" % (name, ", ".join(args))
170
+
171
+ def __enter__(self):
172
+ if self._entered:
173
+ raise RuntimeError("Cannot enter %r twice" % self)
174
+ self._entered = True
175
+ self._filters = self._module.filters
176
+ self._module.filters = self._filters[:]
177
+ self._showwarning = self._module.showwarning
178
+ warnings.simplefilter("ignore", self.category)
179
+
180
+ def __exit__(self, *exc_info):
181
+ if not self._entered:
182
+ raise RuntimeError("Cannot exit %r without entering first" % self)
183
+ self._module.filters = self._filters
184
+ self._module.showwarning = self._showwarning
185
+ self.log[:] = []
186
+
187
+
188
+ def assert_raise_message(exceptions, message, function, *args, **kwargs):
189
+ """Helper function to test the message raised in an exception.
190
+
191
+ Given an exception, a callable to raise the exception, and
192
+ a message string, tests that the correct exception is raised and
193
+ that the message is a substring of the error thrown. Used to test
194
+ that the specific message thrown during an exception is correct.
195
+
196
+ Parameters
197
+ ----------
198
+ exceptions : exception or tuple of exception
199
+ An Exception object.
200
+
201
+ message : str
202
+ The error message or a substring of the error message.
203
+
204
+ function : callable
205
+ Callable object to raise error.
206
+
207
+ *args : the positional arguments to `function`.
208
+
209
+ **kwargs : the keyword arguments to `function`.
210
+ """
211
+ try:
212
+ function(*args, **kwargs)
213
+ except exceptions as e:
214
+ error_message = str(e)
215
+ if message not in error_message:
216
+ raise AssertionError(
217
+ "Error message does not include the expected"
218
+ " string: %r. Observed error message: %r" % (message, error_message)
219
+ )
220
+ else:
221
+ # concatenate exception names
222
+ if isinstance(exceptions, tuple):
223
+ names = " or ".join(e.__name__ for e in exceptions)
224
+ else:
225
+ names = exceptions.__name__
226
+
227
+ raise AssertionError("%s not raised by %s" % (names, function.__name__))
228
+
229
+
230
+ def assert_allclose(
231
+ actual, desired, rtol=None, atol=0.0, equal_nan=True, err_msg="", verbose=True
232
+ ):
233
+ """dtype-aware variant of numpy.testing.assert_allclose
234
+
235
+ This variant introspects the least precise floating point dtype
236
+ in the input argument and automatically sets the relative tolerance
237
+ parameter to 1e-4 float32 and use 1e-7 otherwise (typically float64
238
+ in scikit-learn).
239
+
240
+ `atol` is always left to 0. by default. It should be adjusted manually
241
+ to an assertion-specific value in case there are null values expected
242
+ in `desired`.
243
+
244
+ The aggregate tolerance is `atol + rtol * abs(desired)`.
245
+
246
+ Parameters
247
+ ----------
248
+ actual : array_like
249
+ Array obtained.
250
+ desired : array_like
251
+ Array desired.
252
+ rtol : float, optional, default=None
253
+ Relative tolerance.
254
+ If None, it is set based on the provided arrays' dtypes.
255
+ atol : float, optional, default=0.
256
+ Absolute tolerance.
257
+ equal_nan : bool, optional, default=True
258
+ If True, NaNs will compare equal.
259
+ err_msg : str, optional, default=''
260
+ The error message to be printed in case of failure.
261
+ verbose : bool, optional, default=True
262
+ If True, the conflicting values are appended to the error message.
263
+
264
+ Raises
265
+ ------
266
+ AssertionError
267
+ If actual and desired are not equal up to specified precision.
268
+
269
+ See Also
270
+ --------
271
+ numpy.testing.assert_allclose
272
+
273
+ Examples
274
+ --------
275
+ >>> import numpy as np
276
+ >>> from sklearn.utils._testing import assert_allclose
277
+ >>> x = [1e-5, 1e-3, 1e-1]
278
+ >>> y = np.arccos(np.cos(x))
279
+ >>> assert_allclose(x, y, rtol=1e-5, atol=0)
280
+ >>> a = np.full(shape=10, fill_value=1e-5, dtype=np.float32)
281
+ >>> assert_allclose(a, 1e-5)
282
+ """
283
+ dtypes = []
284
+
285
+ actual, desired = np.asanyarray(actual), np.asanyarray(desired)
286
+ dtypes = [actual.dtype, desired.dtype]
287
+
288
+ if rtol is None:
289
+ rtols = [1e-4 if dtype == np.float32 else 1e-7 for dtype in dtypes]
290
+ rtol = max(rtols)
291
+
292
+ np_assert_allclose(
293
+ actual,
294
+ desired,
295
+ rtol=rtol,
296
+ atol=atol,
297
+ equal_nan=equal_nan,
298
+ err_msg=err_msg,
299
+ verbose=verbose,
300
+ )
301
+
302
+
303
+ def assert_allclose_dense_sparse(x, y, rtol=1e-07, atol=1e-9, err_msg=""):
304
+ """Assert allclose for sparse and dense data.
305
+
306
+ Both x and y need to be either sparse or dense, they
307
+ can't be mixed.
308
+
309
+ Parameters
310
+ ----------
311
+ x : {array-like, sparse matrix}
312
+ First array to compare.
313
+
314
+ y : {array-like, sparse matrix}
315
+ Second array to compare.
316
+
317
+ rtol : float, default=1e-07
318
+ relative tolerance; see numpy.allclose.
319
+
320
+ atol : float, default=1e-9
321
+ absolute tolerance; see numpy.allclose. Note that the default here is
322
+ more tolerant than the default for numpy.testing.assert_allclose, where
323
+ atol=0.
324
+
325
+ err_msg : str, default=''
326
+ Error message to raise.
327
+ """
328
+ if sp.sparse.issparse(x) and sp.sparse.issparse(y):
329
+ x = x.tocsr()
330
+ y = y.tocsr()
331
+ x.sum_duplicates()
332
+ y.sum_duplicates()
333
+ assert_array_equal(x.indices, y.indices, err_msg=err_msg)
334
+ assert_array_equal(x.indptr, y.indptr, err_msg=err_msg)
335
+ assert_allclose(x.data, y.data, rtol=rtol, atol=atol, err_msg=err_msg)
336
+ elif not sp.sparse.issparse(x) and not sp.sparse.issparse(y):
337
+ # both dense
338
+ assert_allclose(x, y, rtol=rtol, atol=atol, err_msg=err_msg)
339
+ else:
340
+ raise ValueError(
341
+ "Can only compare two sparse matrices, not a sparse matrix and an array."
342
+ )
343
+
344
+
345
+ def set_random_state(estimator, random_state=0):
346
+ """Set random state of an estimator if it has the `random_state` param.
347
+
348
+ Parameters
349
+ ----------
350
+ estimator : object
351
+ The estimator.
352
+ random_state : int, RandomState instance or None, default=0
353
+ Pseudo random number generator state.
354
+ Pass an int for reproducible results across multiple function calls.
355
+ See :term:`Glossary <random_state>`.
356
+ """
357
+ if "random_state" in estimator.get_params():
358
+ estimator.set_params(random_state=random_state)
359
+
360
+
361
+ try:
362
+ _check_array_api_dispatch(True)
363
+ ARRAY_API_COMPAT_FUNCTIONAL = True
364
+ except ImportError:
365
+ ARRAY_API_COMPAT_FUNCTIONAL = False
366
+
367
+ try:
368
+ import pytest
369
+
370
+ skip_if_32bit = pytest.mark.skipif(_IS_32BIT, reason="skipped on 32bit platforms")
371
+ fails_if_pypy = pytest.mark.xfail(IS_PYPY, reason="not compatible with PyPy")
372
+ fails_if_unstable_openblas = pytest.mark.xfail(
373
+ _in_unstable_openblas_configuration(),
374
+ reason="OpenBLAS is unstable for this configuration",
375
+ )
376
+ skip_if_no_parallel = pytest.mark.skipif(
377
+ not joblib.parallel.mp, reason="joblib is in serial mode"
378
+ )
379
+ skip_if_array_api_compat_not_configured = pytest.mark.skipif(
380
+ not ARRAY_API_COMPAT_FUNCTIONAL,
381
+ reason="requires array_api_compat installed and a new enough version of NumPy",
382
+ )
383
+
384
+ # Decorator for tests involving both BLAS calls and multiprocessing.
385
+ #
386
+ # Under POSIX (e.g. Linux or OSX), using multiprocessing in conjunction
387
+ # with some implementation of BLAS (or other libraries that manage an
388
+ # internal posix thread pool) can cause a crash or a freeze of the Python
389
+ # process.
390
+ #
391
+ # In practice all known packaged distributions (from Linux distros or
392
+ # Anaconda) of BLAS under Linux seems to be safe. So we this problem seems
393
+ # to only impact OSX users.
394
+ #
395
+ # This wrapper makes it possible to skip tests that can possibly cause
396
+ # this crash under OS X with.
397
+ #
398
+ # Under Python 3.4+ it is possible to use the `forkserver` start method
399
+ # for multiprocessing to avoid this issue. However it can cause pickling
400
+ # errors on interactively defined functions. It therefore not enabled by
401
+ # default.
402
+
403
+ if_safe_multiprocessing_with_blas = pytest.mark.skipif(
404
+ sys.platform == "darwin", reason="Possible multi-process bug with some BLAS"
405
+ )
406
+ except ImportError:
407
+ pass
408
+
409
+
410
+ def check_skip_network():
411
+ if int(os.environ.get("SKLEARN_SKIP_NETWORK_TESTS", 0)):
412
+ raise SkipTest("Text tutorial requires large dataset download")
413
+
414
+
415
+ def _delete_folder(folder_path, warn=False):
416
+ """Utility function to cleanup a temporary folder if still existing.
417
+
418
+ Copy from joblib.pool (for independence).
419
+ """
420
+ try:
421
+ if os.path.exists(folder_path):
422
+ # This can fail under windows,
423
+ # but will succeed when called by atexit
424
+ shutil.rmtree(folder_path)
425
+ except OSError:
426
+ if warn:
427
+ warnings.warn("Could not delete temporary folder %s" % folder_path)
428
+
429
+
430
+ class TempMemmap:
431
+ """
432
+ Parameters
433
+ ----------
434
+ data
435
+ mmap_mode : str, default='r'
436
+ """
437
+
438
+ def __init__(self, data, mmap_mode="r"):
439
+ self.mmap_mode = mmap_mode
440
+ self.data = data
441
+
442
+ def __enter__(self):
443
+ data_read_only, self.temp_folder = create_memmap_backed_data(
444
+ self.data, mmap_mode=self.mmap_mode, return_folder=True
445
+ )
446
+ return data_read_only
447
+
448
+ def __exit__(self, exc_type, exc_val, exc_tb):
449
+ _delete_folder(self.temp_folder)
450
+
451
+
452
+ def create_memmap_backed_data(data, mmap_mode="r", return_folder=False):
453
+ """
454
+ Parameters
455
+ ----------
456
+ data
457
+ mmap_mode : str, default='r'
458
+ return_folder : bool, default=False
459
+ """
460
+ temp_folder = tempfile.mkdtemp(prefix="sklearn_testing_")
461
+ atexit.register(functools.partial(_delete_folder, temp_folder, warn=True))
462
+ filename = op.join(temp_folder, "data.pkl")
463
+ joblib.dump(data, filename)
464
+ memmap_backed_data = joblib.load(filename, mmap_mode=mmap_mode)
465
+ result = (
466
+ memmap_backed_data if not return_folder else (memmap_backed_data, temp_folder)
467
+ )
468
+ return result
469
+
470
+
471
+ # Utils to test docstrings
472
+
473
+
474
+ def _get_args(function, varargs=False):
475
+ """Helper to get function arguments."""
476
+
477
+ try:
478
+ params = signature(function).parameters
479
+ except ValueError:
480
+ # Error on builtin C function
481
+ return []
482
+ args = [
483
+ key
484
+ for key, param in params.items()
485
+ if param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)
486
+ ]
487
+ if varargs:
488
+ varargs = [
489
+ param.name
490
+ for param in params.values()
491
+ if param.kind == param.VAR_POSITIONAL
492
+ ]
493
+ if len(varargs) == 0:
494
+ varargs = None
495
+ return args, varargs
496
+ else:
497
+ return args
498
+
499
+
500
+ def _get_func_name(func):
501
+ """Get function full name.
502
+
503
+ Parameters
504
+ ----------
505
+ func : callable
506
+ The function object.
507
+
508
+ Returns
509
+ -------
510
+ name : str
511
+ The function name.
512
+ """
513
+ parts = []
514
+ module = inspect.getmodule(func)
515
+ if module:
516
+ parts.append(module.__name__)
517
+
518
+ qualname = func.__qualname__
519
+ if qualname != func.__name__:
520
+ parts.append(qualname[: qualname.find(".")])
521
+
522
+ parts.append(func.__name__)
523
+ return ".".join(parts)
524
+
525
+
526
+ def check_docstring_parameters(func, doc=None, ignore=None):
527
+ """Helper to check docstring.
528
+
529
+ Parameters
530
+ ----------
531
+ func : callable
532
+ The function object to test.
533
+ doc : str, default=None
534
+ Docstring if it is passed manually to the test.
535
+ ignore : list, default=None
536
+ Parameters to ignore.
537
+
538
+ Returns
539
+ -------
540
+ incorrect : list
541
+ A list of string describing the incorrect results.
542
+ """
543
+ from numpydoc import docscrape
544
+
545
+ incorrect = []
546
+ ignore = [] if ignore is None else ignore
547
+
548
+ func_name = _get_func_name(func)
549
+ if not func_name.startswith("sklearn.") or func_name.startswith(
550
+ "sklearn.externals"
551
+ ):
552
+ return incorrect
553
+ # Don't check docstring for property-functions
554
+ if inspect.isdatadescriptor(func):
555
+ return incorrect
556
+ # Don't check docstring for setup / teardown pytest functions
557
+ if func_name.split(".")[-1] in ("setup_module", "teardown_module"):
558
+ return incorrect
559
+ # Dont check estimator_checks module
560
+ if func_name.split(".")[2] == "estimator_checks":
561
+ return incorrect
562
+ # Get the arguments from the function signature
563
+ param_signature = list(filter(lambda x: x not in ignore, _get_args(func)))
564
+ # drop self
565
+ if len(param_signature) > 0 and param_signature[0] == "self":
566
+ param_signature.remove("self")
567
+
568
+ # Analyze function's docstring
569
+ if doc is None:
570
+ records = []
571
+ with warnings.catch_warnings(record=True):
572
+ warnings.simplefilter("error", UserWarning)
573
+ try:
574
+ doc = docscrape.FunctionDoc(func)
575
+ except UserWarning as exp:
576
+ if "potentially wrong underline length" in str(exp):
577
+ # Catch warning raised as of numpydoc 1.2 when
578
+ # the underline length for a section of a docstring
579
+ # is not consistent.
580
+ message = str(exp).split("\n")[:3]
581
+ incorrect += [f"In function: {func_name}"] + message
582
+ return incorrect
583
+ records.append(str(exp))
584
+ except Exception as exp:
585
+ incorrect += [func_name + " parsing error: " + str(exp)]
586
+ return incorrect
587
+ if len(records):
588
+ raise RuntimeError("Error for %s:\n%s" % (func_name, records[0]))
589
+
590
+ param_docs = []
591
+ for name, type_definition, param_doc in doc["Parameters"]:
592
+ # Type hints are empty only if parameter name ended with :
593
+ if not type_definition.strip():
594
+ if ":" in name and name[: name.index(":")][-1:].strip():
595
+ incorrect += [
596
+ func_name
597
+ + " There was no space between the param name and colon (%r)" % name
598
+ ]
599
+ elif name.rstrip().endswith(":"):
600
+ incorrect += [
601
+ func_name
602
+ + " Parameter %r has an empty type spec. Remove the colon"
603
+ % (name.lstrip())
604
+ ]
605
+
606
+ # Create a list of parameters to compare with the parameters gotten
607
+ # from the func signature
608
+ if "*" not in name:
609
+ param_docs.append(name.split(":")[0].strip("` "))
610
+
611
+ # If one of the docstring's parameters had an error then return that
612
+ # incorrect message
613
+ if len(incorrect) > 0:
614
+ return incorrect
615
+
616
+ # Remove the parameters that should be ignored from list
617
+ param_docs = list(filter(lambda x: x not in ignore, param_docs))
618
+
619
+ # The following is derived from pytest, Copyright (c) 2004-2017 Holger
620
+ # Krekel and others, Licensed under MIT License. See
621
+ # https://github.com/pytest-dev/pytest
622
+
623
+ message = []
624
+ for i in range(min(len(param_docs), len(param_signature))):
625
+ if param_signature[i] != param_docs[i]:
626
+ message += [
627
+ "There's a parameter name mismatch in function"
628
+ " docstring w.r.t. function signature, at index %s"
629
+ " diff: %r != %r" % (i, param_signature[i], param_docs[i])
630
+ ]
631
+ break
632
+ if len(param_signature) > len(param_docs):
633
+ message += [
634
+ "Parameters in function docstring have less items w.r.t."
635
+ " function signature, first missing item: %s"
636
+ % param_signature[len(param_docs)]
637
+ ]
638
+
639
+ elif len(param_signature) < len(param_docs):
640
+ message += [
641
+ "Parameters in function docstring have more items w.r.t."
642
+ " function signature, first extra item: %s"
643
+ % param_docs[len(param_signature)]
644
+ ]
645
+
646
+ # If there wasn't any difference in the parameters themselves between
647
+ # docstring and signature including having the same length then return
648
+ # empty list
649
+ if len(message) == 0:
650
+ return []
651
+
652
+ import difflib
653
+ import pprint
654
+
655
+ param_docs_formatted = pprint.pformat(param_docs).splitlines()
656
+ param_signature_formatted = pprint.pformat(param_signature).splitlines()
657
+
658
+ message += ["Full diff:"]
659
+
660
+ message.extend(
661
+ line.strip()
662
+ for line in difflib.ndiff(param_signature_formatted, param_docs_formatted)
663
+ )
664
+
665
+ incorrect.extend(message)
666
+
667
+ # Prepend function name
668
+ incorrect = ["In function: " + func_name] + incorrect
669
+
670
+ return incorrect
671
+
672
+
673
+ def assert_run_python_script_without_output(source_code, pattern=".+", timeout=60):
674
+ """Utility to check assertions in an independent Python subprocess.
675
+
676
+ The script provided in the source code should return 0 and the stdtout +
677
+ stderr should not match the pattern `pattern`.
678
+
679
+ This is a port from cloudpickle https://github.com/cloudpipe/cloudpickle
680
+
681
+ Parameters
682
+ ----------
683
+ source_code : str
684
+ The Python source code to execute.
685
+ pattern : str
686
+ Pattern that the stdout + stderr should not match. By default, unless
687
+ stdout + stderr are both empty, an error will be raised.
688
+ timeout : int, default=60
689
+ Time in seconds before timeout.
690
+ """
691
+ fd, source_file = tempfile.mkstemp(suffix="_src_test_sklearn.py")
692
+ os.close(fd)
693
+ try:
694
+ with open(source_file, "wb") as f:
695
+ f.write(source_code.encode("utf-8"))
696
+ cmd = [sys.executable, source_file]
697
+ cwd = op.normpath(op.join(op.dirname(sklearn.__file__), ".."))
698
+ env = os.environ.copy()
699
+ try:
700
+ env["PYTHONPATH"] = os.pathsep.join([cwd, env["PYTHONPATH"]])
701
+ except KeyError:
702
+ env["PYTHONPATH"] = cwd
703
+ kwargs = {"cwd": cwd, "stderr": STDOUT, "env": env}
704
+ # If coverage is running, pass the config file to the subprocess
705
+ coverage_rc = os.environ.get("COVERAGE_PROCESS_START")
706
+ if coverage_rc:
707
+ kwargs["env"]["COVERAGE_PROCESS_START"] = coverage_rc
708
+
709
+ kwargs["timeout"] = timeout
710
+ try:
711
+ try:
712
+ out = check_output(cmd, **kwargs)
713
+ except CalledProcessError as e:
714
+ raise RuntimeError(
715
+ "script errored with output:\n%s" % e.output.decode("utf-8")
716
+ )
717
+
718
+ out = out.decode("utf-8")
719
+ if re.search(pattern, out):
720
+ if pattern == ".+":
721
+ expectation = "Expected no output"
722
+ else:
723
+ expectation = f"The output was not supposed to match {pattern!r}"
724
+
725
+ message = f"{expectation}, got the following output instead: {out!r}"
726
+ raise AssertionError(message)
727
+ except TimeoutExpired as e:
728
+ raise RuntimeError(
729
+ "script timeout, output so far:\n%s" % e.output.decode("utf-8")
730
+ )
731
+ finally:
732
+ os.unlink(source_file)
733
+
734
+
735
+ def _convert_container(
736
+ container,
737
+ constructor_name,
738
+ columns_name=None,
739
+ dtype=None,
740
+ minversion=None,
741
+ categorical_feature_names=None,
742
+ ):
743
+ """Convert a given container to a specific array-like with a dtype.
744
+
745
+ Parameters
746
+ ----------
747
+ container : array-like
748
+ The container to convert.
749
+ constructor_name : {"list", "tuple", "array", "sparse", "dataframe", \
750
+ "series", "index", "slice", "sparse_csr", "sparse_csc"}
751
+ The type of the returned container.
752
+ columns_name : index or array-like, default=None
753
+ For pandas container supporting `columns_names`, it will affect
754
+ specific names.
755
+ dtype : dtype, default=None
756
+ Force the dtype of the container. Does not apply to `"slice"`
757
+ container.
758
+ minversion : str, default=None
759
+ Minimum version for package to install.
760
+ categorical_feature_names : list of str, default=None
761
+ List of column names to cast to categorical dtype.
762
+
763
+ Returns
764
+ -------
765
+ converted_container
766
+ """
767
+ if constructor_name == "list":
768
+ if dtype is None:
769
+ return list(container)
770
+ else:
771
+ return np.asarray(container, dtype=dtype).tolist()
772
+ elif constructor_name == "tuple":
773
+ if dtype is None:
774
+ return tuple(container)
775
+ else:
776
+ return tuple(np.asarray(container, dtype=dtype).tolist())
777
+ elif constructor_name == "array":
778
+ return np.asarray(container, dtype=dtype)
779
+ elif constructor_name in ("pandas", "dataframe"):
780
+ pd = pytest.importorskip("pandas", minversion=minversion)
781
+ result = pd.DataFrame(container, columns=columns_name, dtype=dtype, copy=False)
782
+ if categorical_feature_names is not None:
783
+ for col_name in categorical_feature_names:
784
+ result[col_name] = result[col_name].astype("category")
785
+ return result
786
+ elif constructor_name == "pyarrow":
787
+ pa = pytest.importorskip("pyarrow", minversion=minversion)
788
+ array = np.asarray(container)
789
+ if columns_name is None:
790
+ columns_name = [f"col{i}" for i in range(array.shape[1])]
791
+ data = {name: array[:, i] for i, name in enumerate(columns_name)}
792
+ result = pa.Table.from_pydict(data)
793
+ if categorical_feature_names is not None:
794
+ for col_idx, col_name in enumerate(result.column_names):
795
+ if col_name in categorical_feature_names:
796
+ result = result.set_column(
797
+ col_idx, col_name, result.column(col_name).dictionary_encode()
798
+ )
799
+ return result
800
+ elif constructor_name == "polars":
801
+ pl = pytest.importorskip("polars", minversion=minversion)
802
+ result = pl.DataFrame(container, schema=columns_name, orient="row")
803
+ if categorical_feature_names is not None:
804
+ for col_name in categorical_feature_names:
805
+ result = result.with_columns(pl.col(col_name).cast(pl.Categorical))
806
+ return result
807
+ elif constructor_name == "series":
808
+ pd = pytest.importorskip("pandas", minversion=minversion)
809
+ return pd.Series(container, dtype=dtype)
810
+ elif constructor_name == "index":
811
+ pd = pytest.importorskip("pandas", minversion=minversion)
812
+ return pd.Index(container, dtype=dtype)
813
+ elif constructor_name == "slice":
814
+ return slice(container[0], container[1])
815
+ elif "sparse" in constructor_name:
816
+ if not sp.sparse.issparse(container):
817
+ # For scipy >= 1.13, sparse array constructed from 1d array may be
818
+ # 1d or raise an exception. To avoid this, we make sure that the
819
+ # input container is 2d. For more details, see
820
+ # https://github.com/scipy/scipy/pull/18530#issuecomment-1878005149
821
+ container = np.atleast_2d(container)
822
+
823
+ if "array" in constructor_name and sp_version < parse_version("1.8"):
824
+ raise ValueError(
825
+ f"{constructor_name} is only available with scipy>=1.8.0, got "
826
+ f"{sp_version}"
827
+ )
828
+ if constructor_name in ("sparse", "sparse_csr"):
829
+ # sparse and sparse_csr are equivalent for legacy reasons
830
+ return sp.sparse.csr_matrix(container, dtype=dtype)
831
+ elif constructor_name == "sparse_csr_array":
832
+ return sp.sparse.csr_array(container, dtype=dtype)
833
+ elif constructor_name == "sparse_csc":
834
+ return sp.sparse.csc_matrix(container, dtype=dtype)
835
+ elif constructor_name == "sparse_csc_array":
836
+ return sp.sparse.csc_array(container, dtype=dtype)
837
+
838
+
839
+ def raises(expected_exc_type, match=None, may_pass=False, err_msg=None):
840
+ """Context manager to ensure exceptions are raised within a code block.
841
+
842
+ This is similar to and inspired from pytest.raises, but supports a few
843
+ other cases.
844
+
845
+ This is only intended to be used in estimator_checks.py where we don't
846
+ want to use pytest. In the rest of the code base, just use pytest.raises
847
+ instead.
848
+
849
+ Parameters
850
+ ----------
851
+ excepted_exc_type : Exception or list of Exception
852
+ The exception that should be raised by the block. If a list, the block
853
+ should raise one of the exceptions.
854
+ match : str or list of str, default=None
855
+ A regex that the exception message should match. If a list, one of
856
+ the entries must match. If None, match isn't enforced.
857
+ may_pass : bool, default=False
858
+ If True, the block is allowed to not raise an exception. Useful in
859
+ cases where some estimators may support a feature but others must
860
+ fail with an appropriate error message. By default, the context
861
+ manager will raise an exception if the block does not raise an
862
+ exception.
863
+ err_msg : str, default=None
864
+ If the context manager fails (e.g. the block fails to raise the
865
+ proper exception, or fails to match), then an AssertionError is
866
+ raised with this message. By default, an AssertionError is raised
867
+ with a default error message (depends on the kind of failure). Use
868
+ this to indicate how users should fix their estimators to pass the
869
+ checks.
870
+
871
+ Attributes
872
+ ----------
873
+ raised_and_matched : bool
874
+ True if an exception was raised and a match was found, False otherwise.
875
+ """
876
+ return _Raises(expected_exc_type, match, may_pass, err_msg)
877
+
878
+
879
+ class _Raises(contextlib.AbstractContextManager):
880
+ # see raises() for parameters
881
+ def __init__(self, expected_exc_type, match, may_pass, err_msg):
882
+ self.expected_exc_types = (
883
+ expected_exc_type
884
+ if isinstance(expected_exc_type, Iterable)
885
+ else [expected_exc_type]
886
+ )
887
+ self.matches = [match] if isinstance(match, str) else match
888
+ self.may_pass = may_pass
889
+ self.err_msg = err_msg
890
+ self.raised_and_matched = False
891
+
892
+ def __exit__(self, exc_type, exc_value, _):
893
+ # see
894
+ # https://docs.python.org/2.5/whatsnew/pep-343.html#SECTION000910000000000000000
895
+
896
+ if exc_type is None: # No exception was raised in the block
897
+ if self.may_pass:
898
+ return True # CM is happy
899
+ else:
900
+ err_msg = self.err_msg or f"Did not raise: {self.expected_exc_types}"
901
+ raise AssertionError(err_msg)
902
+
903
+ if not any(
904
+ issubclass(exc_type, expected_type)
905
+ for expected_type in self.expected_exc_types
906
+ ):
907
+ if self.err_msg is not None:
908
+ raise AssertionError(self.err_msg) from exc_value
909
+ else:
910
+ return False # will re-raise the original exception
911
+
912
+ if self.matches is not None:
913
+ err_msg = self.err_msg or (
914
+ "The error message should contain one of the following "
915
+ "patterns:\n{}\nGot {}".format("\n".join(self.matches), str(exc_value))
916
+ )
917
+ if not any(re.search(match, str(exc_value)) for match in self.matches):
918
+ raise AssertionError(err_msg) from exc_value
919
+ self.raised_and_matched = True
920
+
921
+ return True
922
+
923
+
924
+ class MinimalClassifier:
925
+ """Minimal classifier implementation with inheriting from BaseEstimator.
926
+
927
+ This estimator should be tested with:
928
+
929
+ * `check_estimator` in `test_estimator_checks.py`;
930
+ * within a `Pipeline` in `test_pipeline.py`;
931
+ * within a `SearchCV` in `test_search.py`.
932
+ """
933
+
934
+ _estimator_type = "classifier"
935
+
936
+ def __init__(self, param=None):
937
+ self.param = param
938
+
939
+ def get_params(self, deep=True):
940
+ return {"param": self.param}
941
+
942
+ def set_params(self, **params):
943
+ for key, value in params.items():
944
+ setattr(self, key, value)
945
+ return self
946
+
947
+ def fit(self, X, y):
948
+ X, y = check_X_y(X, y)
949
+ check_classification_targets(y)
950
+ self.classes_, counts = np.unique(y, return_counts=True)
951
+ self._most_frequent_class_idx = counts.argmax()
952
+ return self
953
+
954
+ def predict_proba(self, X):
955
+ check_is_fitted(self)
956
+ X = check_array(X)
957
+ proba_shape = (X.shape[0], self.classes_.size)
958
+ y_proba = np.zeros(shape=proba_shape, dtype=np.float64)
959
+ y_proba[:, self._most_frequent_class_idx] = 1.0
960
+ return y_proba
961
+
962
+ def predict(self, X):
963
+ y_proba = self.predict_proba(X)
964
+ y_pred = y_proba.argmax(axis=1)
965
+ return self.classes_[y_pred]
966
+
967
+ def score(self, X, y):
968
+ from sklearn.metrics import accuracy_score
969
+
970
+ return accuracy_score(y, self.predict(X))
971
+
972
+
973
+ class MinimalRegressor:
974
+ """Minimal regressor implementation with inheriting from BaseEstimator.
975
+
976
+ This estimator should be tested with:
977
+
978
+ * `check_estimator` in `test_estimator_checks.py`;
979
+ * within a `Pipeline` in `test_pipeline.py`;
980
+ * within a `SearchCV` in `test_search.py`.
981
+ """
982
+
983
+ _estimator_type = "regressor"
984
+
985
+ def __init__(self, param=None):
986
+ self.param = param
987
+
988
+ def get_params(self, deep=True):
989
+ return {"param": self.param}
990
+
991
+ def set_params(self, **params):
992
+ for key, value in params.items():
993
+ setattr(self, key, value)
994
+ return self
995
+
996
+ def fit(self, X, y):
997
+ X, y = check_X_y(X, y)
998
+ self.is_fitted_ = True
999
+ self._mean = np.mean(y)
1000
+ return self
1001
+
1002
+ def predict(self, X):
1003
+ check_is_fitted(self)
1004
+ X = check_array(X)
1005
+ return np.ones(shape=(X.shape[0],)) * self._mean
1006
+
1007
+ def score(self, X, y):
1008
+ from sklearn.metrics import r2_score
1009
+
1010
+ return r2_score(y, self.predict(X))
1011
+
1012
+
1013
+ class MinimalTransformer:
1014
+ """Minimal transformer implementation with inheriting from
1015
+ BaseEstimator.
1016
+
1017
+ This estimator should be tested with:
1018
+
1019
+ * `check_estimator` in `test_estimator_checks.py`;
1020
+ * within a `Pipeline` in `test_pipeline.py`;
1021
+ * within a `SearchCV` in `test_search.py`.
1022
+ """
1023
+
1024
+ def __init__(self, param=None):
1025
+ self.param = param
1026
+
1027
+ def get_params(self, deep=True):
1028
+ return {"param": self.param}
1029
+
1030
+ def set_params(self, **params):
1031
+ for key, value in params.items():
1032
+ setattr(self, key, value)
1033
+ return self
1034
+
1035
+ def fit(self, X, y=None):
1036
+ check_array(X)
1037
+ self.is_fitted_ = True
1038
+ return self
1039
+
1040
+ def transform(self, X, y=None):
1041
+ check_is_fitted(self)
1042
+ X = check_array(X)
1043
+ return X
1044
+
1045
+ def fit_transform(self, X, y=None):
1046
+ return self.fit(X, y).transform(X, y)
1047
+
1048
+
1049
+ def _array_api_for_tests(array_namespace, device):
1050
+ try:
1051
+ if array_namespace == "numpy.array_api":
1052
+ # FIXME: once it is not experimental anymore
1053
+ with ignore_warnings(category=UserWarning):
1054
+ # UserWarning: numpy.array_api submodule is still experimental.
1055
+ array_mod = importlib.import_module(array_namespace)
1056
+ else:
1057
+ array_mod = importlib.import_module(array_namespace)
1058
+ except ModuleNotFoundError:
1059
+ raise SkipTest(
1060
+ f"{array_namespace} is not installed: not checking array_api input"
1061
+ )
1062
+ try:
1063
+ import array_api_compat # noqa
1064
+ except ImportError:
1065
+ raise SkipTest(
1066
+ "array_api_compat is not installed: not checking array_api input"
1067
+ )
1068
+
1069
+ # First create an array using the chosen array module and then get the
1070
+ # corresponding (compatibility wrapped) array namespace based on it.
1071
+ # This is because `cupy` is not the same as the compatibility wrapped
1072
+ # namespace of a CuPy array.
1073
+ xp = array_api_compat.get_namespace(array_mod.asarray(1))
1074
+ if (
1075
+ array_namespace == "torch"
1076
+ and device == "cuda"
1077
+ and not xp.backends.cuda.is_built()
1078
+ ):
1079
+ raise SkipTest("PyTorch test requires cuda, which is not available")
1080
+ elif array_namespace == "torch" and device == "mps":
1081
+ if os.getenv("PYTORCH_ENABLE_MPS_FALLBACK") != "1":
1082
+ # For now we need PYTORCH_ENABLE_MPS_FALLBACK=1 for all estimators to work
1083
+ # when using the MPS device.
1084
+ raise SkipTest(
1085
+ "Skipping MPS device test because PYTORCH_ENABLE_MPS_FALLBACK is not "
1086
+ "set."
1087
+ )
1088
+ if not xp.backends.mps.is_built():
1089
+ raise SkipTest(
1090
+ "MPS is not available because the current PyTorch install was not "
1091
+ "built with MPS enabled."
1092
+ )
1093
+ elif array_namespace in {"cupy", "cupy.array_api"}: # pragma: nocover
1094
+ import cupy
1095
+
1096
+ if cupy.cuda.runtime.getDeviceCount() == 0:
1097
+ raise SkipTest("CuPy test requires cuda, which is not available")
1098
+ return xp
1099
+
1100
+
1101
+ def _get_warnings_filters_info_list():
1102
+ @dataclass
1103
+ class WarningInfo:
1104
+ action: "warnings._ActionKind"
1105
+ message: str = ""
1106
+ category: type[Warning] = Warning
1107
+
1108
+ def to_filterwarning_str(self):
1109
+ if self.category.__module__ == "builtins":
1110
+ category = self.category.__name__
1111
+ else:
1112
+ category = f"{self.category.__module__}.{self.category.__name__}"
1113
+
1114
+ return f"{self.action}:{self.message}:{category}"
1115
+
1116
+ return [
1117
+ WarningInfo("error", category=DeprecationWarning),
1118
+ WarningInfo("error", category=FutureWarning),
1119
+ WarningInfo("error", category=VisibleDeprecationWarning),
1120
+ # TODO: remove when pyamg > 5.0.1
1121
+ # Avoid a deprecation warning due pkg_resources usage in pyamg.
1122
+ WarningInfo(
1123
+ "ignore",
1124
+ message="pkg_resources is deprecated as an API",
1125
+ category=DeprecationWarning,
1126
+ ),
1127
+ WarningInfo(
1128
+ "ignore",
1129
+ message="Deprecated call to `pkg_resources",
1130
+ category=DeprecationWarning,
1131
+ ),
1132
+ # pytest-cov issue https://github.com/pytest-dev/pytest-cov/issues/557 not
1133
+ # fixed although it has been closed. https://github.com/pytest-dev/pytest-cov/pull/623
1134
+ # would probably fix it.
1135
+ WarningInfo(
1136
+ "ignore",
1137
+ message=(
1138
+ "The --rsyncdir command line argument and rsyncdirs config variable are"
1139
+ " deprecated"
1140
+ ),
1141
+ category=DeprecationWarning,
1142
+ ),
1143
+ # XXX: Easiest way to ignore pandas Pyarrow DeprecationWarning in the
1144
+ # short-term. See https://github.com/pandas-dev/pandas/issues/54466 for
1145
+ # more details.
1146
+ WarningInfo(
1147
+ "ignore",
1148
+ message=r"\s*Pyarrow will become a required dependency",
1149
+ category=DeprecationWarning,
1150
+ ),
1151
+ ]
1152
+
1153
+
1154
+ def get_pytest_filterwarning_lines():
1155
+ warning_filters_info_list = _get_warnings_filters_info_list()
1156
+ return [
1157
+ warning_info.to_filterwarning_str()
1158
+ for warning_info in warning_filters_info_list
1159
+ ]
1160
+
1161
+
1162
+ def turn_warnings_into_errors():
1163
+ warnings_filters_info_list = _get_warnings_filters_info_list()
1164
+ for warning_info in warnings_filters_info_list:
1165
+ warnings.filterwarnings(
1166
+ warning_info.action,
1167
+ message=warning_info.message,
1168
+ category=warning_info.category,
1169
+ )
venv/lib/python3.10/site-packages/sklearn/utils/_typedefs.pxd ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Commonly used types
2
+ # These are redefinitions of the ones defined by numpy in
3
+ # https://github.com/numpy/numpy/blob/main/numpy/__init__.pxd
4
+ # and exposed by cython in
5
+ # https://github.com/cython/cython/blob/master/Cython/Includes/numpy/__init__.pxd.
6
+ # It will eventually avoid having to always include the numpy headers even when we
7
+ # would only use it for the types.
8
+ #
9
+ # When used to declare variables that will receive values from numpy arrays, it
10
+ # should match the dtype of the array. For example, to declare a variable that will
11
+ # receive values from a numpy array of dtype np.float64, the type float64_t must be
12
+ # used.
13
+ #
14
+ # TODO: Stop defining custom types locally or globally like DTYPE_t and friends and
15
+ # use these consistently throughout the codebase.
16
+ # NOTE: Extend this list as needed when converting more cython extensions.
17
+ ctypedef unsigned char uint8_t
18
+ ctypedef unsigned int uint32_t
19
+ ctypedef unsigned long long uint64_t
20
+ ctypedef Py_ssize_t intp_t
21
+ ctypedef float float32_t
22
+ ctypedef double float64_t
23
+ # Sparse matrices indices and indices' pointers arrays must use int32_t over
24
+ # intp_t because intp_t is platform dependent.
25
+ # When large sparse matrices are supported, indexing must use int64_t.
26
+ # See https://github.com/scikit-learn/scikit-learn/issues/23653 which tracks the
27
+ # ongoing work to support large sparse matrices.
28
+ ctypedef signed int int32_t
29
+ ctypedef signed long long int64_t
venv/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (176 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/_weight_vector.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (208 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/_weight_vector.pxd ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # WARNING: Do not edit this file directly.
2
+ # It is automatically generated from 'sklearn/utils/_weight_vector.pxd.tp'.
3
+ # Changes must be made there.
4
+
5
+
6
+ cdef class WeightVector64(object):
7
+ cdef readonly double[::1] w
8
+ cdef readonly double[::1] aw
9
+ cdef double *w_data_ptr
10
+ cdef double *aw_data_ptr
11
+
12
+ cdef double wscale
13
+ cdef double average_a
14
+ cdef double average_b
15
+ cdef int n_features
16
+ cdef double sq_norm
17
+
18
+ cdef void add(self, double *x_data_ptr, int *x_ind_ptr,
19
+ int xnnz, double c) noexcept nogil
20
+ cdef void add_average(self, double *x_data_ptr, int *x_ind_ptr,
21
+ int xnnz, double c, double num_iter) noexcept nogil
22
+ cdef double dot(self, double *x_data_ptr, int *x_ind_ptr,
23
+ int xnnz) noexcept nogil
24
+ cdef void scale(self, double c) noexcept nogil
25
+ cdef void reset_wscale(self) noexcept nogil
26
+ cdef double norm(self) noexcept nogil
27
+
28
+ cdef class WeightVector32(object):
29
+ cdef readonly float[::1] w
30
+ cdef readonly float[::1] aw
31
+ cdef float *w_data_ptr
32
+ cdef float *aw_data_ptr
33
+
34
+ cdef double wscale
35
+ cdef double average_a
36
+ cdef double average_b
37
+ cdef int n_features
38
+ cdef double sq_norm
39
+
40
+ cdef void add(self, float *x_data_ptr, int *x_ind_ptr,
41
+ int xnnz, float c) noexcept nogil
42
+ cdef void add_average(self, float *x_data_ptr, int *x_ind_ptr,
43
+ int xnnz, float c, float num_iter) noexcept nogil
44
+ cdef float dot(self, float *x_data_ptr, int *x_ind_ptr,
45
+ int xnnz) noexcept nogil
46
+ cdef void scale(self, float c) noexcept nogil
47
+ cdef void reset_wscale(self) noexcept nogil
48
+ cdef float norm(self) noexcept nogil
venv/lib/python3.10/site-packages/sklearn/utils/class_weight.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The :mod:`sklearn.utils.class_weight` module includes utilities for handling
3
+ weights based on class labels.
4
+ """
5
+
6
+ # Authors: Andreas Mueller
7
+ # Manoj Kumar
8
+ # License: BSD 3 clause
9
+
10
+ import numpy as np
11
+ from scipy import sparse
12
+
13
+ from ._param_validation import StrOptions, validate_params
14
+
15
+
16
+ @validate_params(
17
+ {
18
+ "class_weight": [dict, StrOptions({"balanced"}), None],
19
+ "classes": [np.ndarray],
20
+ "y": ["array-like"],
21
+ },
22
+ prefer_skip_nested_validation=True,
23
+ )
24
+ def compute_class_weight(class_weight, *, classes, y):
25
+ """Estimate class weights for unbalanced datasets.
26
+
27
+ Parameters
28
+ ----------
29
+ class_weight : dict, "balanced" or None
30
+ If "balanced", class weights will be given by
31
+ `n_samples / (n_classes * np.bincount(y))`.
32
+ If a dictionary is given, keys are classes and values are corresponding class
33
+ weights.
34
+ If `None` is given, the class weights will be uniform.
35
+
36
+ classes : ndarray
37
+ Array of the classes occurring in the data, as given by
38
+ `np.unique(y_org)` with `y_org` the original class labels.
39
+
40
+ y : array-like of shape (n_samples,)
41
+ Array of original class labels per sample.
42
+
43
+ Returns
44
+ -------
45
+ class_weight_vect : ndarray of shape (n_classes,)
46
+ Array with `class_weight_vect[i]` the weight for i-th class.
47
+
48
+ References
49
+ ----------
50
+ The "balanced" heuristic is inspired by
51
+ Logistic Regression in Rare Events Data, King, Zen, 2001.
52
+
53
+ Examples
54
+ --------
55
+ >>> import numpy as np
56
+ >>> from sklearn.utils.class_weight import compute_class_weight
57
+ >>> y = [1, 1, 1, 1, 0, 0]
58
+ >>> compute_class_weight(class_weight="balanced", classes=np.unique(y), y=y)
59
+ array([1.5 , 0.75])
60
+ """
61
+ # Import error caused by circular imports.
62
+ from ..preprocessing import LabelEncoder
63
+
64
+ if set(y) - set(classes):
65
+ raise ValueError("classes should include all valid labels that can be in y")
66
+ if class_weight is None or len(class_weight) == 0:
67
+ # uniform class weights
68
+ weight = np.ones(classes.shape[0], dtype=np.float64, order="C")
69
+ elif class_weight == "balanced":
70
+ # Find the weight of each class as present in y.
71
+ le = LabelEncoder()
72
+ y_ind = le.fit_transform(y)
73
+ if not all(np.isin(classes, le.classes_)):
74
+ raise ValueError("classes should have valid labels that are in y")
75
+
76
+ recip_freq = len(y) / (len(le.classes_) * np.bincount(y_ind).astype(np.float64))
77
+ weight = recip_freq[le.transform(classes)]
78
+ else:
79
+ # user-defined dictionary
80
+ weight = np.ones(classes.shape[0], dtype=np.float64, order="C")
81
+ unweighted_classes = []
82
+ for i, c in enumerate(classes):
83
+ if c in class_weight:
84
+ weight[i] = class_weight[c]
85
+ else:
86
+ unweighted_classes.append(c)
87
+
88
+ n_weighted_classes = len(classes) - len(unweighted_classes)
89
+ if unweighted_classes and n_weighted_classes != len(class_weight):
90
+ unweighted_classes_user_friendly_str = np.array(unweighted_classes).tolist()
91
+ raise ValueError(
92
+ f"The classes, {unweighted_classes_user_friendly_str}, are not in"
93
+ " class_weight"
94
+ )
95
+
96
+ return weight
97
+
98
+
99
+ @validate_params(
100
+ {
101
+ "class_weight": [dict, list, StrOptions({"balanced"}), None],
102
+ "y": ["array-like", "sparse matrix"],
103
+ "indices": ["array-like", None],
104
+ },
105
+ prefer_skip_nested_validation=True,
106
+ )
107
+ def compute_sample_weight(class_weight, y, *, indices=None):
108
+ """Estimate sample weights by class for unbalanced datasets.
109
+
110
+ Parameters
111
+ ----------
112
+ class_weight : dict, list of dicts, "balanced", or None
113
+ Weights associated with classes in the form `{class_label: weight}`.
114
+ If not given, all classes are supposed to have weight one. For
115
+ multi-output problems, a list of dicts can be provided in the same
116
+ order as the columns of y.
117
+
118
+ Note that for multioutput (including multilabel) weights should be
119
+ defined for each class of every column in its own dict. For example,
120
+ for four-class multilabel classification weights should be
121
+ `[{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}]` instead of
122
+ `[{1:1}, {2:5}, {3:1}, {4:1}]`.
123
+
124
+ The `"balanced"` mode uses the values of y to automatically adjust
125
+ weights inversely proportional to class frequencies in the input data:
126
+ `n_samples / (n_classes * np.bincount(y))`.
127
+
128
+ For multi-output, the weights of each column of y will be multiplied.
129
+
130
+ y : {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs)
131
+ Array of original class labels per sample.
132
+
133
+ indices : array-like of shape (n_subsample,), default=None
134
+ Array of indices to be used in a subsample. Can be of length less than
135
+ `n_samples` in the case of a subsample, or equal to `n_samples` in the
136
+ case of a bootstrap subsample with repeated indices. If `None`, the
137
+ sample weight will be calculated over the full sample. Only `"balanced"`
138
+ is supported for `class_weight` if this is provided.
139
+
140
+ Returns
141
+ -------
142
+ sample_weight_vect : ndarray of shape (n_samples,)
143
+ Array with sample weights as applied to the original `y`.
144
+
145
+ Examples
146
+ --------
147
+ >>> from sklearn.utils.class_weight import compute_sample_weight
148
+ >>> y = [1, 1, 1, 1, 0, 0]
149
+ >>> compute_sample_weight(class_weight="balanced", y=y)
150
+ array([0.75, 0.75, 0.75, 0.75, 1.5 , 1.5 ])
151
+ """
152
+
153
+ # Ensure y is 2D. Sparse matrices are already 2D.
154
+ if not sparse.issparse(y):
155
+ y = np.atleast_1d(y)
156
+ if y.ndim == 1:
157
+ y = np.reshape(y, (-1, 1))
158
+ n_outputs = y.shape[1]
159
+
160
+ if indices is not None and class_weight != "balanced":
161
+ raise ValueError(
162
+ "The only valid class_weight for subsampling is 'balanced'. "
163
+ f"Given {class_weight}."
164
+ )
165
+ elif n_outputs > 1:
166
+ if class_weight is None or isinstance(class_weight, dict):
167
+ raise ValueError(
168
+ "For multi-output, class_weight should be a list of dicts, or the "
169
+ "string 'balanced'."
170
+ )
171
+ elif isinstance(class_weight, list) and len(class_weight) != n_outputs:
172
+ raise ValueError(
173
+ "For multi-output, number of elements in class_weight should match "
174
+ f"number of outputs. Got {len(class_weight)} element(s) while having "
175
+ f"{n_outputs} outputs."
176
+ )
177
+
178
+ expanded_class_weight = []
179
+ for k in range(n_outputs):
180
+ if sparse.issparse(y):
181
+ # Ok to densify a single column at a time
182
+ y_full = y[:, [k]].toarray().flatten()
183
+ else:
184
+ y_full = y[:, k]
185
+ classes_full = np.unique(y_full)
186
+ classes_missing = None
187
+
188
+ if class_weight == "balanced" or n_outputs == 1:
189
+ class_weight_k = class_weight
190
+ else:
191
+ class_weight_k = class_weight[k]
192
+
193
+ if indices is not None:
194
+ # Get class weights for the subsample, covering all classes in
195
+ # case some labels that were present in the original data are
196
+ # missing from the sample.
197
+ y_subsample = y_full[indices]
198
+ classes_subsample = np.unique(y_subsample)
199
+
200
+ weight_k = np.take(
201
+ compute_class_weight(
202
+ class_weight_k, classes=classes_subsample, y=y_subsample
203
+ ),
204
+ np.searchsorted(classes_subsample, classes_full),
205
+ mode="clip",
206
+ )
207
+
208
+ classes_missing = set(classes_full) - set(classes_subsample)
209
+ else:
210
+ weight_k = compute_class_weight(
211
+ class_weight_k, classes=classes_full, y=y_full
212
+ )
213
+
214
+ weight_k = weight_k[np.searchsorted(classes_full, y_full)]
215
+
216
+ if classes_missing:
217
+ # Make missing classes' weight zero
218
+ weight_k[np.isin(y_full, list(classes_missing))] = 0.0
219
+
220
+ expanded_class_weight.append(weight_k)
221
+
222
+ expanded_class_weight = np.prod(expanded_class_weight, axis=0, dtype=np.float64)
223
+
224
+ return expanded_class_weight
venv/lib/python3.10/site-packages/sklearn/utils/deprecation.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import warnings
3
+
4
+ __all__ = ["deprecated"]
5
+
6
+
7
+ class deprecated:
8
+ """Decorator to mark a function or class as deprecated.
9
+
10
+ Issue a warning when the function is called/the class is instantiated and
11
+ adds a warning to the docstring.
12
+
13
+ The optional extra argument will be appended to the deprecation message
14
+ and the docstring. Note: to use this with the default value for extra, put
15
+ in an empty of parentheses:
16
+
17
+ Examples
18
+ --------
19
+ >>> from sklearn.utils import deprecated
20
+ >>> deprecated()
21
+ <sklearn.utils.deprecation.deprecated object at ...>
22
+ >>> @deprecated()
23
+ ... def some_function(): pass
24
+
25
+ Parameters
26
+ ----------
27
+ extra : str, default=''
28
+ To be added to the deprecation messages.
29
+ """
30
+
31
+ # Adapted from https://wiki.python.org/moin/PythonDecoratorLibrary,
32
+ # but with many changes.
33
+
34
+ def __init__(self, extra=""):
35
+ self.extra = extra
36
+
37
+ def __call__(self, obj):
38
+ """Call method
39
+
40
+ Parameters
41
+ ----------
42
+ obj : object
43
+ """
44
+ if isinstance(obj, type):
45
+ return self._decorate_class(obj)
46
+ elif isinstance(obj, property):
47
+ # Note that this is only triggered properly if the `property`
48
+ # decorator comes before the `deprecated` decorator, like so:
49
+ #
50
+ # @deprecated(msg)
51
+ # @property
52
+ # def deprecated_attribute_(self):
53
+ # ...
54
+ return self._decorate_property(obj)
55
+ else:
56
+ return self._decorate_fun(obj)
57
+
58
+ def _decorate_class(self, cls):
59
+ msg = "Class %s is deprecated" % cls.__name__
60
+ if self.extra:
61
+ msg += "; %s" % self.extra
62
+
63
+ new = cls.__new__
64
+
65
+ def wrapped(cls, *args, **kwargs):
66
+ warnings.warn(msg, category=FutureWarning)
67
+ if new is object.__new__:
68
+ return object.__new__(cls)
69
+ return new(cls, *args, **kwargs)
70
+
71
+ cls.__new__ = wrapped
72
+
73
+ wrapped.__name__ = "__new__"
74
+ wrapped.deprecated_original = new
75
+
76
+ return cls
77
+
78
+ def _decorate_fun(self, fun):
79
+ """Decorate function fun"""
80
+
81
+ msg = "Function %s is deprecated" % fun.__name__
82
+ if self.extra:
83
+ msg += "; %s" % self.extra
84
+
85
+ @functools.wraps(fun)
86
+ def wrapped(*args, **kwargs):
87
+ warnings.warn(msg, category=FutureWarning)
88
+ return fun(*args, **kwargs)
89
+
90
+ # Add a reference to the wrapped function so that we can introspect
91
+ # on function arguments in Python 2 (already works in Python 3)
92
+ wrapped.__wrapped__ = fun
93
+
94
+ return wrapped
95
+
96
+ def _decorate_property(self, prop):
97
+ msg = self.extra
98
+
99
+ @property
100
+ @functools.wraps(prop)
101
+ def wrapped(*args, **kwargs):
102
+ warnings.warn(msg, category=FutureWarning)
103
+ return prop.fget(*args, **kwargs)
104
+
105
+ return wrapped
106
+
107
+
108
+ def _is_deprecated(func):
109
+ """Helper to check if func is wrapped by our deprecated decorator"""
110
+ closures = getattr(func, "__closure__", [])
111
+ if closures is None:
112
+ closures = []
113
+ is_deprecated = "deprecated" in "".join(
114
+ [c.cell_contents for c in closures if isinstance(c.cell_contents, str)]
115
+ )
116
+ return is_deprecated
venv/lib/python3.10/site-packages/sklearn/utils/extmath.py ADDED
@@ -0,0 +1,1284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The :mod:`sklearn.utils.extmath` module includes utilities to perform
3
+ optimal mathematical operations in scikit-learn that are not available in SciPy.
4
+ """
5
+ # Authors: Gael Varoquaux
6
+ # Alexandre Gramfort
7
+ # Alexandre T. Passos
8
+ # Olivier Grisel
9
+ # Lars Buitinck
10
+ # Stefan van der Walt
11
+ # Kyle Kastner
12
+ # Giorgio Patrini
13
+ # License: BSD 3 clause
14
+
15
+ import warnings
16
+ from functools import partial
17
+ from numbers import Integral
18
+
19
+ import numpy as np
20
+ from scipy import linalg, sparse
21
+
22
+ from ..utils import deprecated
23
+ from ..utils._param_validation import Interval, StrOptions, validate_params
24
+ from . import check_random_state
25
+ from ._array_api import _is_numpy_namespace, device, get_namespace
26
+ from .sparsefuncs_fast import csr_row_norms
27
+ from .validation import check_array
28
+
29
+
30
+ def squared_norm(x):
31
+ """Squared Euclidean or Frobenius norm of x.
32
+
33
+ Faster than norm(x) ** 2.
34
+
35
+ Parameters
36
+ ----------
37
+ x : array-like
38
+ The input array which could be either be a vector or a 2 dimensional array.
39
+
40
+ Returns
41
+ -------
42
+ float
43
+ The Euclidean norm when x is a vector, the Frobenius norm when x
44
+ is a matrix (2-d array).
45
+ """
46
+ x = np.ravel(x, order="K")
47
+ if np.issubdtype(x.dtype, np.integer):
48
+ warnings.warn(
49
+ (
50
+ "Array type is integer, np.dot may overflow. "
51
+ "Data should be float type to avoid this issue"
52
+ ),
53
+ UserWarning,
54
+ )
55
+ return np.dot(x, x)
56
+
57
+
58
+ def row_norms(X, squared=False):
59
+ """Row-wise (squared) Euclidean norm of X.
60
+
61
+ Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports sparse
62
+ matrices and does not create an X.shape-sized temporary.
63
+
64
+ Performs no input validation.
65
+
66
+ Parameters
67
+ ----------
68
+ X : array-like
69
+ The input array.
70
+ squared : bool, default=False
71
+ If True, return squared norms.
72
+
73
+ Returns
74
+ -------
75
+ array-like
76
+ The row-wise (squared) Euclidean norm of X.
77
+ """
78
+ if sparse.issparse(X):
79
+ X = X.tocsr()
80
+ norms = csr_row_norms(X)
81
+ if not squared:
82
+ norms = np.sqrt(norms)
83
+ else:
84
+ xp, _ = get_namespace(X)
85
+ if _is_numpy_namespace(xp):
86
+ X = np.asarray(X)
87
+ norms = np.einsum("ij,ij->i", X, X)
88
+ norms = xp.asarray(norms)
89
+ else:
90
+ norms = xp.sum(xp.multiply(X, X), axis=1)
91
+ if not squared:
92
+ norms = xp.sqrt(norms)
93
+ return norms
94
+
95
+
96
+ def fast_logdet(A):
97
+ """Compute logarithm of determinant of a square matrix.
98
+
99
+ The (natural) logarithm of the determinant of a square matrix
100
+ is returned if det(A) is non-negative and well defined.
101
+ If the determinant is zero or negative returns -Inf.
102
+
103
+ Equivalent to : np.log(np.det(A)) but more robust.
104
+
105
+ Parameters
106
+ ----------
107
+ A : array_like of shape (n, n)
108
+ The square matrix.
109
+
110
+ Returns
111
+ -------
112
+ logdet : float
113
+ When det(A) is strictly positive, log(det(A)) is returned.
114
+ When det(A) is non-positive or not defined, then -inf is returned.
115
+
116
+ See Also
117
+ --------
118
+ numpy.linalg.slogdet : Compute the sign and (natural) logarithm of the determinant
119
+ of an array.
120
+
121
+ Examples
122
+ --------
123
+ >>> import numpy as np
124
+ >>> from sklearn.utils.extmath import fast_logdet
125
+ >>> a = np.array([[5, 1], [2, 8]])
126
+ >>> fast_logdet(a)
127
+ 3.6375861597263857
128
+ """
129
+ xp, _ = get_namespace(A)
130
+ sign, ld = xp.linalg.slogdet(A)
131
+ if not sign > 0:
132
+ return -xp.inf
133
+ return ld
134
+
135
+
136
+ def density(w):
137
+ """Compute density of a sparse vector.
138
+
139
+ Parameters
140
+ ----------
141
+ w : {ndarray, sparse matrix}
142
+ The input data can be numpy ndarray or a sparse matrix.
143
+
144
+ Returns
145
+ -------
146
+ float
147
+ The density of w, between 0 and 1.
148
+
149
+ Examples
150
+ --------
151
+ >>> from scipy import sparse
152
+ >>> from sklearn.utils.extmath import density
153
+ >>> X = sparse.random(10, 10, density=0.25, random_state=0)
154
+ >>> density(X)
155
+ 0.25
156
+ """
157
+ if hasattr(w, "toarray"):
158
+ d = float(w.nnz) / (w.shape[0] * w.shape[1])
159
+ else:
160
+ d = 0 if w is None else float((w != 0).sum()) / w.size
161
+ return d
162
+
163
+
164
+ def safe_sparse_dot(a, b, *, dense_output=False):
165
+ """Dot product that handle the sparse matrix case correctly.
166
+
167
+ Parameters
168
+ ----------
169
+ a : {ndarray, sparse matrix}
170
+ b : {ndarray, sparse matrix}
171
+ dense_output : bool, default=False
172
+ When False, ``a`` and ``b`` both being sparse will yield sparse output.
173
+ When True, output will always be a dense array.
174
+
175
+ Returns
176
+ -------
177
+ dot_product : {ndarray, sparse matrix}
178
+ Sparse if ``a`` and ``b`` are sparse and ``dense_output=False``.
179
+
180
+ Examples
181
+ --------
182
+ >>> from scipy.sparse import csr_matrix
183
+ >>> from sklearn.utils.extmath import safe_sparse_dot
184
+ >>> X = csr_matrix([[1, 2], [3, 4], [5, 6]])
185
+ >>> dot_product = safe_sparse_dot(X, X.T)
186
+ >>> dot_product.toarray()
187
+ array([[ 5, 11, 17],
188
+ [11, 25, 39],
189
+ [17, 39, 61]])
190
+ """
191
+ if a.ndim > 2 or b.ndim > 2:
192
+ if sparse.issparse(a):
193
+ # sparse is always 2D. Implies b is 3D+
194
+ # [i, j] @ [k, ..., l, m, n] -> [i, k, ..., l, n]
195
+ b_ = np.rollaxis(b, -2)
196
+ b_2d = b_.reshape((b.shape[-2], -1))
197
+ ret = a @ b_2d
198
+ ret = ret.reshape(a.shape[0], *b_.shape[1:])
199
+ elif sparse.issparse(b):
200
+ # sparse is always 2D. Implies a is 3D+
201
+ # [k, ..., l, m] @ [i, j] -> [k, ..., l, j]
202
+ a_2d = a.reshape(-1, a.shape[-1])
203
+ ret = a_2d @ b
204
+ ret = ret.reshape(*a.shape[:-1], b.shape[1])
205
+ else:
206
+ ret = np.dot(a, b)
207
+ else:
208
+ ret = a @ b
209
+
210
+ if (
211
+ sparse.issparse(a)
212
+ and sparse.issparse(b)
213
+ and dense_output
214
+ and hasattr(ret, "toarray")
215
+ ):
216
+ return ret.toarray()
217
+ return ret
218
+
219
+
220
+ def randomized_range_finder(
221
+ A, *, size, n_iter, power_iteration_normalizer="auto", random_state=None
222
+ ):
223
+ """Compute an orthonormal matrix whose range approximates the range of A.
224
+
225
+ Parameters
226
+ ----------
227
+ A : 2D array
228
+ The input data matrix.
229
+
230
+ size : int
231
+ Size of the return array.
232
+
233
+ n_iter : int
234
+ Number of power iterations used to stabilize the result.
235
+
236
+ power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto'
237
+ Whether the power iterations are normalized with step-by-step
238
+ QR factorization (the slowest but most accurate), 'none'
239
+ (the fastest but numerically unstable when `n_iter` is large, e.g.
240
+ typically 5 or larger), or 'LU' factorization (numerically stable
241
+ but can lose slightly in accuracy). The 'auto' mode applies no
242
+ normalization if `n_iter` <= 2 and switches to LU otherwise.
243
+
244
+ .. versionadded:: 0.18
245
+
246
+ random_state : int, RandomState instance or None, default=None
247
+ The seed of the pseudo random number generator to use when shuffling
248
+ the data, i.e. getting the random vectors to initialize the algorithm.
249
+ Pass an int for reproducible results across multiple function calls.
250
+ See :term:`Glossary <random_state>`.
251
+
252
+ Returns
253
+ -------
254
+ Q : ndarray
255
+ A (size x size) projection matrix, the range of which
256
+ approximates well the range of the input matrix A.
257
+
258
+ Notes
259
+ -----
260
+
261
+ Follows Algorithm 4.3 of
262
+ :arxiv:`"Finding structure with randomness:
263
+ Stochastic algorithms for constructing approximate matrix decompositions"
264
+ <0909.4061>`
265
+ Halko, et al. (2009)
266
+
267
+ An implementation of a randomized algorithm for principal component
268
+ analysis
269
+ A. Szlam et al. 2014
270
+
271
+ Examples
272
+ --------
273
+ >>> import numpy as np
274
+ >>> from sklearn.utils.extmath import randomized_range_finder
275
+ >>> A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
276
+ >>> randomized_range_finder(A, size=2, n_iter=2, random_state=42)
277
+ array([[-0.21..., 0.88...],
278
+ [-0.52..., 0.24...],
279
+ [-0.82..., -0.38...]])
280
+ """
281
+ xp, is_array_api_compliant = get_namespace(A)
282
+ random_state = check_random_state(random_state)
283
+
284
+ # Generating normal random vectors with shape: (A.shape[1], size)
285
+ # XXX: generate random number directly from xp if it's possible
286
+ # one day.
287
+ Q = xp.asarray(random_state.normal(size=(A.shape[1], size)))
288
+ if hasattr(A, "dtype") and xp.isdtype(A.dtype, kind="real floating"):
289
+ # Use float32 computation and components if A has a float32 dtype.
290
+ Q = xp.astype(Q, A.dtype, copy=False)
291
+
292
+ # Move Q to device if needed only after converting to float32 if needed to
293
+ # avoid allocating unnecessary memory on the device.
294
+
295
+ # Note: we cannot combine the astype and to_device operations in one go
296
+ # using xp.asarray(..., dtype=dtype, device=device) because downcasting
297
+ # from float64 to float32 in asarray might not always be accepted as only
298
+ # casts following type promotion rules are guarateed to work.
299
+ # https://github.com/data-apis/array-api/issues/647
300
+ if is_array_api_compliant:
301
+ Q = xp.asarray(Q, device=device(A))
302
+
303
+ # Deal with "auto" mode
304
+ if power_iteration_normalizer == "auto":
305
+ if n_iter <= 2:
306
+ power_iteration_normalizer = "none"
307
+ elif is_array_api_compliant:
308
+ # XXX: https://github.com/data-apis/array-api/issues/627
309
+ warnings.warn(
310
+ "Array API does not support LU factorization, falling back to QR"
311
+ " instead. Set `power_iteration_normalizer='QR'` explicitly to silence"
312
+ " this warning."
313
+ )
314
+ power_iteration_normalizer = "QR"
315
+ else:
316
+ power_iteration_normalizer = "LU"
317
+ elif power_iteration_normalizer == "LU" and is_array_api_compliant:
318
+ raise ValueError(
319
+ "Array API does not support LU factorization. Set "
320
+ "`power_iteration_normalizer='QR'` instead."
321
+ )
322
+
323
+ if is_array_api_compliant:
324
+ qr_normalizer = partial(xp.linalg.qr, mode="reduced")
325
+ else:
326
+ # Use scipy.linalg instead of numpy.linalg when not explicitly
327
+ # using the Array API.
328
+ qr_normalizer = partial(linalg.qr, mode="economic")
329
+
330
+ if power_iteration_normalizer == "QR":
331
+ normalizer = qr_normalizer
332
+ elif power_iteration_normalizer == "LU":
333
+ normalizer = partial(linalg.lu, permute_l=True)
334
+ else:
335
+ normalizer = lambda x: (x, None)
336
+
337
+ # Perform power iterations with Q to further 'imprint' the top
338
+ # singular vectors of A in Q
339
+ for _ in range(n_iter):
340
+ Q, _ = normalizer(A @ Q)
341
+ Q, _ = normalizer(A.T @ Q)
342
+
343
+ # Sample the range of A using by linear projection of Q
344
+ # Extract an orthonormal basis
345
+ Q, _ = qr_normalizer(A @ Q)
346
+
347
+ return Q
348
+
349
+
350
+ @validate_params(
351
+ {
352
+ "M": [np.ndarray, "sparse matrix"],
353
+ "n_components": [Interval(Integral, 1, None, closed="left")],
354
+ "n_oversamples": [Interval(Integral, 0, None, closed="left")],
355
+ "n_iter": [Interval(Integral, 0, None, closed="left"), StrOptions({"auto"})],
356
+ "power_iteration_normalizer": [StrOptions({"auto", "QR", "LU", "none"})],
357
+ "transpose": ["boolean", StrOptions({"auto"})],
358
+ "flip_sign": ["boolean"],
359
+ "random_state": ["random_state"],
360
+ "svd_lapack_driver": [StrOptions({"gesdd", "gesvd"})],
361
+ },
362
+ prefer_skip_nested_validation=True,
363
+ )
364
+ def randomized_svd(
365
+ M,
366
+ n_components,
367
+ *,
368
+ n_oversamples=10,
369
+ n_iter="auto",
370
+ power_iteration_normalizer="auto",
371
+ transpose="auto",
372
+ flip_sign=True,
373
+ random_state=None,
374
+ svd_lapack_driver="gesdd",
375
+ ):
376
+ """Compute a truncated randomized SVD.
377
+
378
+ This method solves the fixed-rank approximation problem described in [1]_
379
+ (problem (1.5), p5).
380
+
381
+ Parameters
382
+ ----------
383
+ M : {ndarray, sparse matrix}
384
+ Matrix to decompose.
385
+
386
+ n_components : int
387
+ Number of singular values and vectors to extract.
388
+
389
+ n_oversamples : int, default=10
390
+ Additional number of random vectors to sample the range of `M` so as
391
+ to ensure proper conditioning. The total number of random vectors
392
+ used to find the range of `M` is `n_components + n_oversamples`. Smaller
393
+ number can improve speed but can negatively impact the quality of
394
+ approximation of singular vectors and singular values. Users might wish
395
+ to increase this parameter up to `2*k - n_components` where k is the
396
+ effective rank, for large matrices, noisy problems, matrices with
397
+ slowly decaying spectrums, or to increase precision accuracy. See [1]_
398
+ (pages 5, 23 and 26).
399
+
400
+ n_iter : int or 'auto', default='auto'
401
+ Number of power iterations. It can be used to deal with very noisy
402
+ problems. When 'auto', it is set to 4, unless `n_components` is small
403
+ (< .1 * min(X.shape)) in which case `n_iter` is set to 7.
404
+ This improves precision with few components. Note that in general
405
+ users should rather increase `n_oversamples` before increasing `n_iter`
406
+ as the principle of the randomized method is to avoid usage of these
407
+ more costly power iterations steps. When `n_components` is equal
408
+ or greater to the effective matrix rank and the spectrum does not
409
+ present a slow decay, `n_iter=0` or `1` should even work fine in theory
410
+ (see [1]_ page 9).
411
+
412
+ .. versionchanged:: 0.18
413
+
414
+ power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto'
415
+ Whether the power iterations are normalized with step-by-step
416
+ QR factorization (the slowest but most accurate), 'none'
417
+ (the fastest but numerically unstable when `n_iter` is large, e.g.
418
+ typically 5 or larger), or 'LU' factorization (numerically stable
419
+ but can lose slightly in accuracy). The 'auto' mode applies no
420
+ normalization if `n_iter` <= 2 and switches to LU otherwise.
421
+
422
+ .. versionadded:: 0.18
423
+
424
+ transpose : bool or 'auto', default='auto'
425
+ Whether the algorithm should be applied to M.T instead of M. The
426
+ result should approximately be the same. The 'auto' mode will
427
+ trigger the transposition if M.shape[1] > M.shape[0] since this
428
+ implementation of randomized SVD tend to be a little faster in that
429
+ case.
430
+
431
+ .. versionchanged:: 0.18
432
+
433
+ flip_sign : bool, default=True
434
+ The output of a singular value decomposition is only unique up to a
435
+ permutation of the signs of the singular vectors. If `flip_sign` is
436
+ set to `True`, the sign ambiguity is resolved by making the largest
437
+ loadings for each component in the left singular vectors positive.
438
+
439
+ random_state : int, RandomState instance or None, default='warn'
440
+ The seed of the pseudo random number generator to use when
441
+ shuffling the data, i.e. getting the random vectors to initialize
442
+ the algorithm. Pass an int for reproducible results across multiple
443
+ function calls. See :term:`Glossary <random_state>`.
444
+
445
+ .. versionchanged:: 1.2
446
+ The default value changed from 0 to None.
447
+
448
+ svd_lapack_driver : {"gesdd", "gesvd"}, default="gesdd"
449
+ Whether to use the more efficient divide-and-conquer approach
450
+ (`"gesdd"`) or more general rectangular approach (`"gesvd"`) to compute
451
+ the SVD of the matrix B, which is the projection of M into a low
452
+ dimensional subspace, as described in [1]_.
453
+
454
+ .. versionadded:: 1.2
455
+
456
+ Returns
457
+ -------
458
+ u : ndarray of shape (n_samples, n_components)
459
+ Unitary matrix having left singular vectors with signs flipped as columns.
460
+ s : ndarray of shape (n_components,)
461
+ The singular values, sorted in non-increasing order.
462
+ vh : ndarray of shape (n_components, n_features)
463
+ Unitary matrix having right singular vectors with signs flipped as rows.
464
+
465
+ Notes
466
+ -----
467
+ This algorithm finds a (usually very good) approximate truncated
468
+ singular value decomposition using randomization to speed up the
469
+ computations. It is particularly fast on large matrices on which
470
+ you wish to extract only a small number of components. In order to
471
+ obtain further speed up, `n_iter` can be set <=2 (at the cost of
472
+ loss of precision). To increase the precision it is recommended to
473
+ increase `n_oversamples`, up to `2*k-n_components` where k is the
474
+ effective rank. Usually, `n_components` is chosen to be greater than k
475
+ so increasing `n_oversamples` up to `n_components` should be enough.
476
+
477
+ References
478
+ ----------
479
+ .. [1] :arxiv:`"Finding structure with randomness:
480
+ Stochastic algorithms for constructing approximate matrix decompositions"
481
+ <0909.4061>`
482
+ Halko, et al. (2009)
483
+
484
+ .. [2] A randomized algorithm for the decomposition of matrices
485
+ Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert
486
+
487
+ .. [3] An implementation of a randomized algorithm for principal component
488
+ analysis A. Szlam et al. 2014
489
+
490
+ Examples
491
+ --------
492
+ >>> import numpy as np
493
+ >>> from sklearn.utils.extmath import randomized_svd
494
+ >>> a = np.array([[1, 2, 3, 5],
495
+ ... [3, 4, 5, 6],
496
+ ... [7, 8, 9, 10]])
497
+ >>> U, s, Vh = randomized_svd(a, n_components=2, random_state=0)
498
+ >>> U.shape, s.shape, Vh.shape
499
+ ((3, 2), (2,), (2, 4))
500
+ """
501
+ if sparse.issparse(M) and M.format in ("lil", "dok"):
502
+ warnings.warn(
503
+ "Calculating SVD of a {} is expensive. "
504
+ "csr_matrix is more efficient.".format(type(M).__name__),
505
+ sparse.SparseEfficiencyWarning,
506
+ )
507
+
508
+ random_state = check_random_state(random_state)
509
+ n_random = n_components + n_oversamples
510
+ n_samples, n_features = M.shape
511
+
512
+ if n_iter == "auto":
513
+ # Checks if the number of iterations is explicitly specified
514
+ # Adjust n_iter. 7 was found a good compromise for PCA. See #5299
515
+ n_iter = 7 if n_components < 0.1 * min(M.shape) else 4
516
+
517
+ if transpose == "auto":
518
+ transpose = n_samples < n_features
519
+ if transpose:
520
+ # this implementation is a bit faster with smaller shape[1]
521
+ M = M.T
522
+
523
+ Q = randomized_range_finder(
524
+ M,
525
+ size=n_random,
526
+ n_iter=n_iter,
527
+ power_iteration_normalizer=power_iteration_normalizer,
528
+ random_state=random_state,
529
+ )
530
+
531
+ # project M to the (k + p) dimensional space using the basis vectors
532
+ B = Q.T @ M
533
+
534
+ # compute the SVD on the thin matrix: (k + p) wide
535
+ xp, is_array_api_compliant = get_namespace(B)
536
+ if is_array_api_compliant:
537
+ Uhat, s, Vt = xp.linalg.svd(B, full_matrices=False)
538
+ else:
539
+ # When when array_api_dispatch is disabled, rely on scipy.linalg
540
+ # instead of numpy.linalg to avoid introducing a behavior change w.r.t.
541
+ # previous versions of scikit-learn.
542
+ Uhat, s, Vt = linalg.svd(
543
+ B, full_matrices=False, lapack_driver=svd_lapack_driver
544
+ )
545
+ del B
546
+ U = Q @ Uhat
547
+
548
+ if flip_sign:
549
+ if not transpose:
550
+ U, Vt = svd_flip(U, Vt)
551
+ else:
552
+ # In case of transpose u_based_decision=false
553
+ # to actually flip based on u and not v.
554
+ U, Vt = svd_flip(U, Vt, u_based_decision=False)
555
+
556
+ if transpose:
557
+ # transpose back the results according to the input convention
558
+ return Vt[:n_components, :].T, s[:n_components], U[:, :n_components].T
559
+ else:
560
+ return U[:, :n_components], s[:n_components], Vt[:n_components, :]
561
+
562
+
563
+ def _randomized_eigsh(
564
+ M,
565
+ n_components,
566
+ *,
567
+ n_oversamples=10,
568
+ n_iter="auto",
569
+ power_iteration_normalizer="auto",
570
+ selection="module",
571
+ random_state=None,
572
+ ):
573
+ """Computes a truncated eigendecomposition using randomized methods
574
+
575
+ This method solves the fixed-rank approximation problem described in the
576
+ Halko et al paper.
577
+
578
+ The choice of which components to select can be tuned with the `selection`
579
+ parameter.
580
+
581
+ .. versionadded:: 0.24
582
+
583
+ Parameters
584
+ ----------
585
+ M : ndarray or sparse matrix
586
+ Matrix to decompose, it should be real symmetric square or complex
587
+ hermitian
588
+
589
+ n_components : int
590
+ Number of eigenvalues and vectors to extract.
591
+
592
+ n_oversamples : int, default=10
593
+ Additional number of random vectors to sample the range of M so as
594
+ to ensure proper conditioning. The total number of random vectors
595
+ used to find the range of M is n_components + n_oversamples. Smaller
596
+ number can improve speed but can negatively impact the quality of
597
+ approximation of eigenvectors and eigenvalues. Users might wish
598
+ to increase this parameter up to `2*k - n_components` where k is the
599
+ effective rank, for large matrices, noisy problems, matrices with
600
+ slowly decaying spectrums, or to increase precision accuracy. See Halko
601
+ et al (pages 5, 23 and 26).
602
+
603
+ n_iter : int or 'auto', default='auto'
604
+ Number of power iterations. It can be used to deal with very noisy
605
+ problems. When 'auto', it is set to 4, unless `n_components` is small
606
+ (< .1 * min(X.shape)) in which case `n_iter` is set to 7.
607
+ This improves precision with few components. Note that in general
608
+ users should rather increase `n_oversamples` before increasing `n_iter`
609
+ as the principle of the randomized method is to avoid usage of these
610
+ more costly power iterations steps. When `n_components` is equal
611
+ or greater to the effective matrix rank and the spectrum does not
612
+ present a slow decay, `n_iter=0` or `1` should even work fine in theory
613
+ (see Halko et al paper, page 9).
614
+
615
+ power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto'
616
+ Whether the power iterations are normalized with step-by-step
617
+ QR factorization (the slowest but most accurate), 'none'
618
+ (the fastest but numerically unstable when `n_iter` is large, e.g.
619
+ typically 5 or larger), or 'LU' factorization (numerically stable
620
+ but can lose slightly in accuracy). The 'auto' mode applies no
621
+ normalization if `n_iter` <= 2 and switches to LU otherwise.
622
+
623
+ selection : {'value', 'module'}, default='module'
624
+ Strategy used to select the n components. When `selection` is `'value'`
625
+ (not yet implemented, will become the default when implemented), the
626
+ components corresponding to the n largest eigenvalues are returned.
627
+ When `selection` is `'module'`, the components corresponding to the n
628
+ eigenvalues with largest modules are returned.
629
+
630
+ random_state : int, RandomState instance, default=None
631
+ The seed of the pseudo random number generator to use when shuffling
632
+ the data, i.e. getting the random vectors to initialize the algorithm.
633
+ Pass an int for reproducible results across multiple function calls.
634
+ See :term:`Glossary <random_state>`.
635
+
636
+ Notes
637
+ -----
638
+ This algorithm finds a (usually very good) approximate truncated
639
+ eigendecomposition using randomized methods to speed up the computations.
640
+
641
+ This method is particularly fast on large matrices on which
642
+ you wish to extract only a small number of components. In order to
643
+ obtain further speed up, `n_iter` can be set <=2 (at the cost of
644
+ loss of precision). To increase the precision it is recommended to
645
+ increase `n_oversamples`, up to `2*k-n_components` where k is the
646
+ effective rank. Usually, `n_components` is chosen to be greater than k
647
+ so increasing `n_oversamples` up to `n_components` should be enough.
648
+
649
+ Strategy 'value': not implemented yet.
650
+ Algorithms 5.3, 5.4 and 5.5 in the Halko et al paper should provide good
651
+ candidates for a future implementation.
652
+
653
+ Strategy 'module':
654
+ The principle is that for diagonalizable matrices, the singular values and
655
+ eigenvalues are related: if t is an eigenvalue of A, then :math:`|t|` is a
656
+ singular value of A. This method relies on a randomized SVD to find the n
657
+ singular components corresponding to the n singular values with largest
658
+ modules, and then uses the signs of the singular vectors to find the true
659
+ sign of t: if the sign of left and right singular vectors are different
660
+ then the corresponding eigenvalue is negative.
661
+
662
+ Returns
663
+ -------
664
+ eigvals : 1D array of shape (n_components,) containing the `n_components`
665
+ eigenvalues selected (see ``selection`` parameter).
666
+ eigvecs : 2D array of shape (M.shape[0], n_components) containing the
667
+ `n_components` eigenvectors corresponding to the `eigvals`, in the
668
+ corresponding order. Note that this follows the `scipy.linalg.eigh`
669
+ convention.
670
+
671
+ See Also
672
+ --------
673
+ :func:`randomized_svd`
674
+
675
+ References
676
+ ----------
677
+ * :arxiv:`"Finding structure with randomness:
678
+ Stochastic algorithms for constructing approximate matrix decompositions"
679
+ (Algorithm 4.3 for strategy 'module') <0909.4061>`
680
+ Halko, et al. (2009)
681
+ """
682
+ if selection == "value": # pragma: no cover
683
+ # to do : an algorithm can be found in the Halko et al reference
684
+ raise NotImplementedError()
685
+
686
+ elif selection == "module":
687
+ # Note: no need for deterministic U and Vt (flip_sign=True),
688
+ # as we only use the dot product UVt afterwards
689
+ U, S, Vt = randomized_svd(
690
+ M,
691
+ n_components=n_components,
692
+ n_oversamples=n_oversamples,
693
+ n_iter=n_iter,
694
+ power_iteration_normalizer=power_iteration_normalizer,
695
+ flip_sign=False,
696
+ random_state=random_state,
697
+ )
698
+
699
+ eigvecs = U[:, :n_components]
700
+ eigvals = S[:n_components]
701
+
702
+ # Conversion of Singular values into Eigenvalues:
703
+ # For any eigenvalue t, the corresponding singular value is |t|.
704
+ # So if there is a negative eigenvalue t, the corresponding singular
705
+ # value will be -t, and the left (U) and right (V) singular vectors
706
+ # will have opposite signs.
707
+ # Fastest way: see <https://stackoverflow.com/a/61974002/7262247>
708
+ diag_VtU = np.einsum("ji,ij->j", Vt[:n_components, :], U[:, :n_components])
709
+ signs = np.sign(diag_VtU)
710
+ eigvals = eigvals * signs
711
+
712
+ else: # pragma: no cover
713
+ raise ValueError("Invalid `selection`: %r" % selection)
714
+
715
+ return eigvals, eigvecs
716
+
717
+
718
+ def weighted_mode(a, w, *, axis=0):
719
+ """Return an array of the weighted modal (most common) value in the passed array.
720
+
721
+ If there is more than one such value, only the first is returned.
722
+ The bin-count for the modal bins is also returned.
723
+
724
+ This is an extension of the algorithm in scipy.stats.mode.
725
+
726
+ Parameters
727
+ ----------
728
+ a : array-like of shape (n_samples,)
729
+ Array of which values to find mode(s).
730
+ w : array-like of shape (n_samples,)
731
+ Array of weights for each value.
732
+ axis : int, default=0
733
+ Axis along which to operate. Default is 0, i.e. the first axis.
734
+
735
+ Returns
736
+ -------
737
+ vals : ndarray
738
+ Array of modal values.
739
+ score : ndarray
740
+ Array of weighted counts for each mode.
741
+
742
+ See Also
743
+ --------
744
+ scipy.stats.mode: Calculates the Modal (most common) value of array elements
745
+ along specified axis.
746
+
747
+ Examples
748
+ --------
749
+ >>> from sklearn.utils.extmath import weighted_mode
750
+ >>> x = [4, 1, 4, 2, 4, 2]
751
+ >>> weights = [1, 1, 1, 1, 1, 1]
752
+ >>> weighted_mode(x, weights)
753
+ (array([4.]), array([3.]))
754
+
755
+ The value 4 appears three times: with uniform weights, the result is
756
+ simply the mode of the distribution.
757
+
758
+ >>> weights = [1, 3, 0.5, 1.5, 1, 2] # deweight the 4's
759
+ >>> weighted_mode(x, weights)
760
+ (array([2.]), array([3.5]))
761
+
762
+ The value 2 has the highest score: it appears twice with weights of
763
+ 1.5 and 2: the sum of these is 3.5.
764
+ """
765
+ if axis is None:
766
+ a = np.ravel(a)
767
+ w = np.ravel(w)
768
+ axis = 0
769
+ else:
770
+ a = np.asarray(a)
771
+ w = np.asarray(w)
772
+
773
+ if a.shape != w.shape:
774
+ w = np.full(a.shape, w, dtype=w.dtype)
775
+
776
+ scores = np.unique(np.ravel(a)) # get ALL unique values
777
+ testshape = list(a.shape)
778
+ testshape[axis] = 1
779
+ oldmostfreq = np.zeros(testshape)
780
+ oldcounts = np.zeros(testshape)
781
+ for score in scores:
782
+ template = np.zeros(a.shape)
783
+ ind = a == score
784
+ template[ind] = w[ind]
785
+ counts = np.expand_dims(np.sum(template, axis), axis)
786
+ mostfrequent = np.where(counts > oldcounts, score, oldmostfreq)
787
+ oldcounts = np.maximum(counts, oldcounts)
788
+ oldmostfreq = mostfrequent
789
+ return mostfrequent, oldcounts
790
+
791
+
792
+ def cartesian(arrays, out=None):
793
+ """Generate a cartesian product of input arrays.
794
+
795
+ Parameters
796
+ ----------
797
+ arrays : list of array-like
798
+ 1-D arrays to form the cartesian product of.
799
+ out : ndarray of shape (M, len(arrays)), default=None
800
+ Array to place the cartesian product in.
801
+
802
+ Returns
803
+ -------
804
+ out : ndarray of shape (M, len(arrays))
805
+ Array containing the cartesian products formed of input arrays.
806
+ If not provided, the `dtype` of the output array is set to the most
807
+ permissive `dtype` of the input arrays, according to NumPy type
808
+ promotion.
809
+
810
+ .. versionadded:: 1.2
811
+ Add support for arrays of different types.
812
+
813
+ Notes
814
+ -----
815
+ This function may not be used on more than 32 arrays
816
+ because the underlying numpy functions do not support it.
817
+
818
+ Examples
819
+ --------
820
+ >>> from sklearn.utils.extmath import cartesian
821
+ >>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
822
+ array([[1, 4, 6],
823
+ [1, 4, 7],
824
+ [1, 5, 6],
825
+ [1, 5, 7],
826
+ [2, 4, 6],
827
+ [2, 4, 7],
828
+ [2, 5, 6],
829
+ [2, 5, 7],
830
+ [3, 4, 6],
831
+ [3, 4, 7],
832
+ [3, 5, 6],
833
+ [3, 5, 7]])
834
+ """
835
+ arrays = [np.asarray(x) for x in arrays]
836
+ shape = (len(x) for x in arrays)
837
+
838
+ ix = np.indices(shape)
839
+ ix = ix.reshape(len(arrays), -1).T
840
+
841
+ if out is None:
842
+ dtype = np.result_type(*arrays) # find the most permissive dtype
843
+ out = np.empty_like(ix, dtype=dtype)
844
+
845
+ for n, arr in enumerate(arrays):
846
+ out[:, n] = arrays[n][ix[:, n]]
847
+
848
+ return out
849
+
850
+
851
+ def svd_flip(u, v, u_based_decision=True):
852
+ """Sign correction to ensure deterministic output from SVD.
853
+
854
+ Adjusts the columns of u and the rows of v such that the loadings in the
855
+ columns in u that are largest in absolute value are always positive.
856
+
857
+ If u_based_decision is False, then the same sign correction is applied to
858
+ so that the rows in v that are largest in absolute value are always
859
+ positive.
860
+
861
+ Parameters
862
+ ----------
863
+ u : ndarray
864
+ Parameters u and v are the output of `linalg.svd` or
865
+ :func:`~sklearn.utils.extmath.randomized_svd`, with matching inner
866
+ dimensions so one can compute `np.dot(u * s, v)`.
867
+
868
+ v : ndarray
869
+ Parameters u and v are the output of `linalg.svd` or
870
+ :func:`~sklearn.utils.extmath.randomized_svd`, with matching inner
871
+ dimensions so one can compute `np.dot(u * s, v)`. The input v should
872
+ really be called vt to be consistent with scipy's output.
873
+
874
+ u_based_decision : bool, default=True
875
+ If True, use the columns of u as the basis for sign flipping.
876
+ Otherwise, use the rows of v. The choice of which variable to base the
877
+ decision on is generally algorithm dependent.
878
+
879
+ Returns
880
+ -------
881
+ u_adjusted : ndarray
882
+ Array u with adjusted columns and the same dimensions as u.
883
+
884
+ v_adjusted : ndarray
885
+ Array v with adjusted rows and the same dimensions as v.
886
+ """
887
+ xp, _ = get_namespace(u, v)
888
+ device = getattr(u, "device", None)
889
+
890
+ if u_based_decision:
891
+ # columns of u, rows of v, or equivalently rows of u.T and v
892
+ max_abs_u_cols = xp.argmax(xp.abs(u.T), axis=1)
893
+ shift = xp.arange(u.T.shape[0], device=device)
894
+ indices = max_abs_u_cols + shift * u.T.shape[1]
895
+ signs = xp.sign(xp.take(xp.reshape(u.T, (-1,)), indices, axis=0))
896
+ u *= signs[np.newaxis, :]
897
+ v *= signs[:, np.newaxis]
898
+ else:
899
+ # rows of v, columns of u
900
+ max_abs_v_rows = xp.argmax(xp.abs(v), axis=1)
901
+ shift = xp.arange(v.shape[0], device=device)
902
+ indices = max_abs_v_rows + shift * v.shape[1]
903
+ signs = xp.sign(xp.take(xp.reshape(v, (-1,)), indices))
904
+ u *= signs[np.newaxis, :]
905
+ v *= signs[:, np.newaxis]
906
+ return u, v
907
+
908
+
909
+ # TODO(1.6): remove
910
+ @deprecated( # type: ignore
911
+ "The function `log_logistic` is deprecated and will be removed in 1.6. "
912
+ "Use `-np.logaddexp(0, -x)` instead."
913
+ )
914
+ def log_logistic(X, out=None):
915
+ """Compute the log of the logistic function, ``log(1 / (1 + e ** -x))``.
916
+
917
+ This implementation is numerically stable and uses `-np.logaddexp(0, -x)`.
918
+
919
+ For the ordinary logistic function, use ``scipy.special.expit``.
920
+
921
+ Parameters
922
+ ----------
923
+ X : array-like of shape (M, N) or (M,)
924
+ Argument to the logistic function.
925
+
926
+ out : array-like of shape (M, N) or (M,), default=None
927
+ Preallocated output array.
928
+
929
+ Returns
930
+ -------
931
+ out : ndarray of shape (M, N) or (M,)
932
+ Log of the logistic function evaluated at every point in x.
933
+
934
+ Notes
935
+ -----
936
+ See the blog post describing this implementation:
937
+ http://fa.bianp.net/blog/2013/numerical-optimizers-for-logistic-regression/
938
+ """
939
+ X = check_array(X, dtype=np.float64, ensure_2d=False)
940
+
941
+ if out is None:
942
+ out = np.empty_like(X)
943
+
944
+ np.logaddexp(0, -X, out=out)
945
+ out *= -1
946
+ return out
947
+
948
+
949
+ def softmax(X, copy=True):
950
+ """
951
+ Calculate the softmax function.
952
+
953
+ The softmax function is calculated by
954
+ np.exp(X) / np.sum(np.exp(X), axis=1)
955
+
956
+ This will cause overflow when large values are exponentiated.
957
+ Hence the largest value in each row is subtracted from each data
958
+ point to prevent this.
959
+
960
+ Parameters
961
+ ----------
962
+ X : array-like of float of shape (M, N)
963
+ Argument to the logistic function.
964
+
965
+ copy : bool, default=True
966
+ Copy X or not.
967
+
968
+ Returns
969
+ -------
970
+ out : ndarray of shape (M, N)
971
+ Softmax function evaluated at every point in x.
972
+ """
973
+ xp, is_array_api_compliant = get_namespace(X)
974
+ if copy:
975
+ X = xp.asarray(X, copy=True)
976
+ max_prob = xp.reshape(xp.max(X, axis=1), (-1, 1))
977
+ X -= max_prob
978
+
979
+ if _is_numpy_namespace(xp):
980
+ # optimization for NumPy arrays
981
+ np.exp(X, out=np.asarray(X))
982
+ else:
983
+ # array_api does not have `out=`
984
+ X = xp.exp(X)
985
+
986
+ sum_prob = xp.reshape(xp.sum(X, axis=1), (-1, 1))
987
+ X /= sum_prob
988
+ return X
989
+
990
+
991
+ def make_nonnegative(X, min_value=0):
992
+ """Ensure `X.min()` >= `min_value`.
993
+
994
+ Parameters
995
+ ----------
996
+ X : array-like
997
+ The matrix to make non-negative.
998
+ min_value : float, default=0
999
+ The threshold value.
1000
+
1001
+ Returns
1002
+ -------
1003
+ array-like
1004
+ The thresholded array.
1005
+
1006
+ Raises
1007
+ ------
1008
+ ValueError
1009
+ When X is sparse.
1010
+ """
1011
+ min_ = X.min()
1012
+ if min_ < min_value:
1013
+ if sparse.issparse(X):
1014
+ raise ValueError(
1015
+ "Cannot make the data matrix"
1016
+ " nonnegative because it is sparse."
1017
+ " Adding a value to every entry would"
1018
+ " make it no longer sparse."
1019
+ )
1020
+ X = X + (min_value - min_)
1021
+ return X
1022
+
1023
+
1024
+ # Use at least float64 for the accumulating functions to avoid precision issue
1025
+ # see https://github.com/numpy/numpy/issues/9393. The float64 is also retained
1026
+ # as it is in case the float overflows
1027
+ def _safe_accumulator_op(op, x, *args, **kwargs):
1028
+ """
1029
+ This function provides numpy accumulator functions with a float64 dtype
1030
+ when used on a floating point input. This prevents accumulator overflow on
1031
+ smaller floating point dtypes.
1032
+
1033
+ Parameters
1034
+ ----------
1035
+ op : function
1036
+ A numpy accumulator function such as np.mean or np.sum.
1037
+ x : ndarray
1038
+ A numpy array to apply the accumulator function.
1039
+ *args : positional arguments
1040
+ Positional arguments passed to the accumulator function after the
1041
+ input x.
1042
+ **kwargs : keyword arguments
1043
+ Keyword arguments passed to the accumulator function.
1044
+
1045
+ Returns
1046
+ -------
1047
+ result
1048
+ The output of the accumulator function passed to this function.
1049
+ """
1050
+ if np.issubdtype(x.dtype, np.floating) and x.dtype.itemsize < 8:
1051
+ result = op(x, *args, **kwargs, dtype=np.float64)
1052
+ else:
1053
+ result = op(x, *args, **kwargs)
1054
+ return result
1055
+
1056
+
1057
+ def _incremental_mean_and_var(
1058
+ X, last_mean, last_variance, last_sample_count, sample_weight=None
1059
+ ):
1060
+ """Calculate mean update and a Youngs and Cramer variance update.
1061
+
1062
+ If sample_weight is given, the weighted mean and variance is computed.
1063
+
1064
+ Update a given mean and (possibly) variance according to new data given
1065
+ in X. last_mean is always required to compute the new mean.
1066
+ If last_variance is None, no variance is computed and None return for
1067
+ updated_variance.
1068
+
1069
+ From the paper "Algorithms for computing the sample variance: analysis and
1070
+ recommendations", by Chan, Golub, and LeVeque.
1071
+
1072
+ Parameters
1073
+ ----------
1074
+ X : array-like of shape (n_samples, n_features)
1075
+ Data to use for variance update.
1076
+
1077
+ last_mean : array-like of shape (n_features,)
1078
+
1079
+ last_variance : array-like of shape (n_features,)
1080
+
1081
+ last_sample_count : array-like of shape (n_features,)
1082
+ The number of samples encountered until now if sample_weight is None.
1083
+ If sample_weight is not None, this is the sum of sample_weight
1084
+ encountered.
1085
+
1086
+ sample_weight : array-like of shape (n_samples,) or None
1087
+ Sample weights. If None, compute the unweighted mean/variance.
1088
+
1089
+ Returns
1090
+ -------
1091
+ updated_mean : ndarray of shape (n_features,)
1092
+
1093
+ updated_variance : ndarray of shape (n_features,)
1094
+ None if last_variance was None.
1095
+
1096
+ updated_sample_count : ndarray of shape (n_features,)
1097
+
1098
+ Notes
1099
+ -----
1100
+ NaNs are ignored during the algorithm.
1101
+
1102
+ References
1103
+ ----------
1104
+ T. Chan, G. Golub, R. LeVeque. Algorithms for computing the sample
1105
+ variance: recommendations, The American Statistician, Vol. 37, No. 3,
1106
+ pp. 242-247
1107
+
1108
+ Also, see the sparse implementation of this in
1109
+ `utils.sparsefuncs.incr_mean_variance_axis` and
1110
+ `utils.sparsefuncs_fast.incr_mean_variance_axis0`
1111
+ """
1112
+ # old = stats until now
1113
+ # new = the current increment
1114
+ # updated = the aggregated stats
1115
+ last_sum = last_mean * last_sample_count
1116
+ X_nan_mask = np.isnan(X)
1117
+ if np.any(X_nan_mask):
1118
+ sum_op = np.nansum
1119
+ else:
1120
+ sum_op = np.sum
1121
+ if sample_weight is not None:
1122
+ # equivalent to np.nansum(X * sample_weight, axis=0)
1123
+ # safer because np.float64(X*W) != np.float64(X)*np.float64(W)
1124
+ new_sum = _safe_accumulator_op(
1125
+ np.matmul, sample_weight, np.where(X_nan_mask, 0, X)
1126
+ )
1127
+ new_sample_count = _safe_accumulator_op(
1128
+ np.sum, sample_weight[:, None] * (~X_nan_mask), axis=0
1129
+ )
1130
+ else:
1131
+ new_sum = _safe_accumulator_op(sum_op, X, axis=0)
1132
+ n_samples = X.shape[0]
1133
+ new_sample_count = n_samples - np.sum(X_nan_mask, axis=0)
1134
+
1135
+ updated_sample_count = last_sample_count + new_sample_count
1136
+
1137
+ updated_mean = (last_sum + new_sum) / updated_sample_count
1138
+
1139
+ if last_variance is None:
1140
+ updated_variance = None
1141
+ else:
1142
+ T = new_sum / new_sample_count
1143
+ temp = X - T
1144
+ if sample_weight is not None:
1145
+ # equivalent to np.nansum((X-T)**2 * sample_weight, axis=0)
1146
+ # safer because np.float64(X*W) != np.float64(X)*np.float64(W)
1147
+ correction = _safe_accumulator_op(
1148
+ np.matmul, sample_weight, np.where(X_nan_mask, 0, temp)
1149
+ )
1150
+ temp **= 2
1151
+ new_unnormalized_variance = _safe_accumulator_op(
1152
+ np.matmul, sample_weight, np.where(X_nan_mask, 0, temp)
1153
+ )
1154
+ else:
1155
+ correction = _safe_accumulator_op(sum_op, temp, axis=0)
1156
+ temp **= 2
1157
+ new_unnormalized_variance = _safe_accumulator_op(sum_op, temp, axis=0)
1158
+
1159
+ # correction term of the corrected 2 pass algorithm.
1160
+ # See "Algorithms for computing the sample variance: analysis
1161
+ # and recommendations", by Chan, Golub, and LeVeque.
1162
+ new_unnormalized_variance -= correction**2 / new_sample_count
1163
+
1164
+ last_unnormalized_variance = last_variance * last_sample_count
1165
+
1166
+ with np.errstate(divide="ignore", invalid="ignore"):
1167
+ last_over_new_count = last_sample_count / new_sample_count
1168
+ updated_unnormalized_variance = (
1169
+ last_unnormalized_variance
1170
+ + new_unnormalized_variance
1171
+ + last_over_new_count
1172
+ / updated_sample_count
1173
+ * (last_sum / last_over_new_count - new_sum) ** 2
1174
+ )
1175
+
1176
+ zeros = last_sample_count == 0
1177
+ updated_unnormalized_variance[zeros] = new_unnormalized_variance[zeros]
1178
+ updated_variance = updated_unnormalized_variance / updated_sample_count
1179
+
1180
+ return updated_mean, updated_variance, updated_sample_count
1181
+
1182
+
1183
+ def _deterministic_vector_sign_flip(u):
1184
+ """Modify the sign of vectors for reproducibility.
1185
+
1186
+ Flips the sign of elements of all the vectors (rows of u) such that
1187
+ the absolute maximum element of each vector is positive.
1188
+
1189
+ Parameters
1190
+ ----------
1191
+ u : ndarray
1192
+ Array with vectors as its rows.
1193
+
1194
+ Returns
1195
+ -------
1196
+ u_flipped : ndarray with same shape as u
1197
+ Array with the sign flipped vectors as its rows.
1198
+ """
1199
+ max_abs_rows = np.argmax(np.abs(u), axis=1)
1200
+ signs = np.sign(u[range(u.shape[0]), max_abs_rows])
1201
+ u *= signs[:, np.newaxis]
1202
+ return u
1203
+
1204
+
1205
+ def stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08):
1206
+ """Use high precision for cumsum and check that final value matches sum.
1207
+
1208
+ Warns if the final cumulative sum does not match the sum (up to the chosen
1209
+ tolerance).
1210
+
1211
+ Parameters
1212
+ ----------
1213
+ arr : array-like
1214
+ To be cumulatively summed as flat.
1215
+ axis : int, default=None
1216
+ Axis along which the cumulative sum is computed.
1217
+ The default (None) is to compute the cumsum over the flattened array.
1218
+ rtol : float, default=1e-05
1219
+ Relative tolerance, see ``np.allclose``.
1220
+ atol : float, default=1e-08
1221
+ Absolute tolerance, see ``np.allclose``.
1222
+
1223
+ Returns
1224
+ -------
1225
+ out : ndarray
1226
+ Array with the cumulative sums along the chosen axis.
1227
+ """
1228
+ out = np.cumsum(arr, axis=axis, dtype=np.float64)
1229
+ expected = np.sum(arr, axis=axis, dtype=np.float64)
1230
+ if not np.allclose(
1231
+ out.take(-1, axis=axis), expected, rtol=rtol, atol=atol, equal_nan=True
1232
+ ):
1233
+ warnings.warn(
1234
+ (
1235
+ "cumsum was found to be unstable: "
1236
+ "its last element does not correspond to sum"
1237
+ ),
1238
+ RuntimeWarning,
1239
+ )
1240
+ return out
1241
+
1242
+
1243
+ def _nanaverage(a, weights=None):
1244
+ """Compute the weighted average, ignoring NaNs.
1245
+
1246
+ Parameters
1247
+ ----------
1248
+ a : ndarray
1249
+ Array containing data to be averaged.
1250
+ weights : array-like, default=None
1251
+ An array of weights associated with the values in a. Each value in a
1252
+ contributes to the average according to its associated weight. The
1253
+ weights array can either be 1-D of the same shape as a. If `weights=None`,
1254
+ then all data in a are assumed to have a weight equal to one.
1255
+
1256
+ Returns
1257
+ -------
1258
+ weighted_average : float
1259
+ The weighted average.
1260
+
1261
+ Notes
1262
+ -----
1263
+ This wrapper to combine :func:`numpy.average` and :func:`numpy.nanmean`, so
1264
+ that :func:`np.nan` values are ignored from the average and weights can
1265
+ be passed. Note that when possible, we delegate to the prime methods.
1266
+ """
1267
+
1268
+ if len(a) == 0:
1269
+ return np.nan
1270
+
1271
+ mask = np.isnan(a)
1272
+ if mask.all():
1273
+ return np.nan
1274
+
1275
+ if weights is None:
1276
+ return np.nanmean(a)
1277
+
1278
+ weights = np.asarray(weights)
1279
+ a, weights = a[~mask], weights[~mask]
1280
+ try:
1281
+ return np.average(a, weights=weights)
1282
+ except ZeroDivisionError:
1283
+ # this is when all weights are zero, then ignore them
1284
+ return np.average(a)
venv/lib/python3.10/site-packages/sklearn/utils/optimize.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Our own implementation of the Newton algorithm
3
+
4
+ Unlike the scipy.optimize version, this version of the Newton conjugate
5
+ gradient solver uses only one function call to retrieve the
6
+ func value, the gradient value and a callable for the Hessian matvec
7
+ product. If the function call is very expensive (e.g. for logistic
8
+ regression with large design matrix), this approach gives very
9
+ significant speedups.
10
+ """
11
+ # This is a modified file from scipy.optimize
12
+ # Original authors: Travis Oliphant, Eric Jones
13
+ # Modifications by Gael Varoquaux, Mathieu Blondel and Tom Dupre la Tour
14
+ # License: BSD
15
+
16
+ import warnings
17
+
18
+ import numpy as np
19
+ import scipy
20
+
21
+ from ..exceptions import ConvergenceWarning
22
+ from .fixes import line_search_wolfe1, line_search_wolfe2
23
+
24
+
25
+ class _LineSearchError(RuntimeError):
26
+ pass
27
+
28
+
29
+ def _line_search_wolfe12(f, fprime, xk, pk, gfk, old_fval, old_old_fval, **kwargs):
30
+ """
31
+ Same as line_search_wolfe1, but fall back to line_search_wolfe2 if
32
+ suitable step length is not found, and raise an exception if a
33
+ suitable step length is not found.
34
+
35
+ Raises
36
+ ------
37
+ _LineSearchError
38
+ If no suitable step size is found.
39
+
40
+ """
41
+ ret = line_search_wolfe1(f, fprime, xk, pk, gfk, old_fval, old_old_fval, **kwargs)
42
+
43
+ if ret[0] is None:
44
+ # Have a look at the line_search method of our NewtonSolver class. We borrow
45
+ # the logic from there
46
+ # Deal with relative loss differences around machine precision.
47
+ args = kwargs.get("args", tuple())
48
+ fval = f(xk + pk, *args)
49
+ eps = 16 * np.finfo(np.asarray(old_fval).dtype).eps
50
+ tiny_loss = np.abs(old_fval * eps)
51
+ loss_improvement = fval - old_fval
52
+ check = np.abs(loss_improvement) <= tiny_loss
53
+ if check:
54
+ # 2.1 Check sum of absolute gradients as alternative condition.
55
+ sum_abs_grad_old = scipy.linalg.norm(gfk, ord=1)
56
+ grad = fprime(xk + pk, *args)
57
+ sum_abs_grad = scipy.linalg.norm(grad, ord=1)
58
+ check = sum_abs_grad < sum_abs_grad_old
59
+ if check:
60
+ ret = (
61
+ 1.0, # step size
62
+ ret[1] + 1, # number of function evaluations
63
+ ret[2] + 1, # number of gradient evaluations
64
+ fval,
65
+ old_fval,
66
+ grad,
67
+ )
68
+
69
+ if ret[0] is None:
70
+ # line search failed: try different one.
71
+ # TODO: It seems that the new check for the sum of absolute gradients above
72
+ # catches all cases that, earlier, ended up here. In fact, our tests never
73
+ # trigger this "if branch" here and we can consider to remove it.
74
+ ret = line_search_wolfe2(
75
+ f, fprime, xk, pk, gfk, old_fval, old_old_fval, **kwargs
76
+ )
77
+
78
+ if ret[0] is None:
79
+ raise _LineSearchError()
80
+
81
+ return ret
82
+
83
+
84
+ def _cg(fhess_p, fgrad, maxiter, tol):
85
+ """
86
+ Solve iteratively the linear system 'fhess_p . xsupi = fgrad'
87
+ with a conjugate gradient descent.
88
+
89
+ Parameters
90
+ ----------
91
+ fhess_p : callable
92
+ Function that takes the gradient as a parameter and returns the
93
+ matrix product of the Hessian and gradient.
94
+
95
+ fgrad : ndarray of shape (n_features,) or (n_features + 1,)
96
+ Gradient vector.
97
+
98
+ maxiter : int
99
+ Number of CG iterations.
100
+
101
+ tol : float
102
+ Stopping criterion.
103
+
104
+ Returns
105
+ -------
106
+ xsupi : ndarray of shape (n_features,) or (n_features + 1,)
107
+ Estimated solution.
108
+ """
109
+ xsupi = np.zeros(len(fgrad), dtype=fgrad.dtype)
110
+ ri = np.copy(fgrad)
111
+ psupi = -ri
112
+ i = 0
113
+ dri0 = np.dot(ri, ri)
114
+ # We also track of |p_i|^2.
115
+ psupi_norm2 = dri0
116
+
117
+ while i <= maxiter:
118
+ if np.sum(np.abs(ri)) <= tol:
119
+ break
120
+
121
+ Ap = fhess_p(psupi)
122
+ # check curvature
123
+ curv = np.dot(psupi, Ap)
124
+ if 0 <= curv <= 16 * np.finfo(np.float64).eps * psupi_norm2:
125
+ # See https://arxiv.org/abs/1803.02924, Algo 1 Capped Conjugate Gradient.
126
+ break
127
+ elif curv < 0:
128
+ if i > 0:
129
+ break
130
+ else:
131
+ # fall back to steepest descent direction
132
+ xsupi += dri0 / curv * psupi
133
+ break
134
+ alphai = dri0 / curv
135
+ xsupi += alphai * psupi
136
+ ri += alphai * Ap
137
+ dri1 = np.dot(ri, ri)
138
+ betai = dri1 / dri0
139
+ psupi = -ri + betai * psupi
140
+ # We use |p_i|^2 = |r_i|^2 + beta_i^2 |p_{i-1}|^2
141
+ psupi_norm2 = dri1 + betai**2 * psupi_norm2
142
+ i = i + 1
143
+ dri0 = dri1 # update np.dot(ri,ri) for next time.
144
+
145
+ return xsupi
146
+
147
+
148
+ def _newton_cg(
149
+ grad_hess,
150
+ func,
151
+ grad,
152
+ x0,
153
+ args=(),
154
+ tol=1e-4,
155
+ maxiter=100,
156
+ maxinner=200,
157
+ line_search=True,
158
+ warn=True,
159
+ ):
160
+ """
161
+ Minimization of scalar function of one or more variables using the
162
+ Newton-CG algorithm.
163
+
164
+ Parameters
165
+ ----------
166
+ grad_hess : callable
167
+ Should return the gradient and a callable returning the matvec product
168
+ of the Hessian.
169
+
170
+ func : callable
171
+ Should return the value of the function.
172
+
173
+ grad : callable
174
+ Should return the function value and the gradient. This is used
175
+ by the linesearch functions.
176
+
177
+ x0 : array of float
178
+ Initial guess.
179
+
180
+ args : tuple, default=()
181
+ Arguments passed to func_grad_hess, func and grad.
182
+
183
+ tol : float, default=1e-4
184
+ Stopping criterion. The iteration will stop when
185
+ ``max{|g_i | i = 1, ..., n} <= tol``
186
+ where ``g_i`` is the i-th component of the gradient.
187
+
188
+ maxiter : int, default=100
189
+ Number of Newton iterations.
190
+
191
+ maxinner : int, default=200
192
+ Number of CG iterations.
193
+
194
+ line_search : bool, default=True
195
+ Whether to use a line search or not.
196
+
197
+ warn : bool, default=True
198
+ Whether to warn when didn't converge.
199
+
200
+ Returns
201
+ -------
202
+ xk : ndarray of float
203
+ Estimated minimum.
204
+ """
205
+ x0 = np.asarray(x0).flatten()
206
+ xk = np.copy(x0)
207
+ k = 0
208
+
209
+ if line_search:
210
+ old_fval = func(x0, *args)
211
+ old_old_fval = None
212
+
213
+ # Outer loop: our Newton iteration
214
+ while k < maxiter:
215
+ # Compute a search direction pk by applying the CG method to
216
+ # del2 f(xk) p = - fgrad f(xk) starting from 0.
217
+ fgrad, fhess_p = grad_hess(xk, *args)
218
+
219
+ absgrad = np.abs(fgrad)
220
+ if np.max(absgrad) <= tol:
221
+ break
222
+
223
+ maggrad = np.sum(absgrad)
224
+ eta = min([0.5, np.sqrt(maggrad)])
225
+ termcond = eta * maggrad
226
+
227
+ # Inner loop: solve the Newton update by conjugate gradient, to
228
+ # avoid inverting the Hessian
229
+ xsupi = _cg(fhess_p, fgrad, maxiter=maxinner, tol=termcond)
230
+
231
+ alphak = 1.0
232
+
233
+ if line_search:
234
+ try:
235
+ alphak, fc, gc, old_fval, old_old_fval, gfkp1 = _line_search_wolfe12(
236
+ func, grad, xk, xsupi, fgrad, old_fval, old_old_fval, args=args
237
+ )
238
+ except _LineSearchError:
239
+ warnings.warn("Line Search failed")
240
+ break
241
+
242
+ xk += alphak * xsupi # upcast if necessary
243
+ k += 1
244
+
245
+ if warn and k >= maxiter:
246
+ warnings.warn(
247
+ "newton-cg failed to converge. Increase the number of iterations.",
248
+ ConvergenceWarning,
249
+ )
250
+ return xk, k
251
+
252
+
253
+ def _check_optimize_result(solver, result, max_iter=None, extra_warning_msg=None):
254
+ """Check the OptimizeResult for successful convergence
255
+
256
+ Parameters
257
+ ----------
258
+ solver : str
259
+ Solver name. Currently only `lbfgs` is supported.
260
+
261
+ result : OptimizeResult
262
+ Result of the scipy.optimize.minimize function.
263
+
264
+ max_iter : int, default=None
265
+ Expected maximum number of iterations.
266
+
267
+ extra_warning_msg : str, default=None
268
+ Extra warning message.
269
+
270
+ Returns
271
+ -------
272
+ n_iter : int
273
+ Number of iterations.
274
+ """
275
+ # handle both scipy and scikit-learn solver names
276
+ if solver == "lbfgs":
277
+ if result.status != 0:
278
+ try:
279
+ # The message is already decoded in scipy>=1.6.0
280
+ result_message = result.message.decode("latin1")
281
+ except AttributeError:
282
+ result_message = result.message
283
+ warning_msg = (
284
+ "{} failed to converge (status={}):\n{}.\n\n"
285
+ "Increase the number of iterations (max_iter) "
286
+ "or scale the data as shown in:\n"
287
+ " https://scikit-learn.org/stable/modules/"
288
+ "preprocessing.html"
289
+ ).format(solver, result.status, result_message)
290
+ if extra_warning_msg is not None:
291
+ warning_msg += "\n" + extra_warning_msg
292
+ warnings.warn(warning_msg, ConvergenceWarning, stacklevel=2)
293
+ if max_iter is not None:
294
+ # In scipy <= 1.0.0, nit may exceed maxiter for lbfgs.
295
+ # See https://github.com/scipy/scipy/issues/7854
296
+ n_iter_i = min(result.nit, max_iter)
297
+ else:
298
+ n_iter_i = result.nit
299
+ else:
300
+ raise NotImplementedError
301
+
302
+ return n_iter_i
venv/lib/python3.10/site-packages/sklearn/utils/parallel.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The :mod:`sklearn.utils.parallel` customizes `joblib` tools for scikit-learn usage.
3
+ """
4
+
5
+ import functools
6
+ import warnings
7
+ from functools import update_wrapper
8
+
9
+ import joblib
10
+
11
+ from .._config import config_context, get_config
12
+
13
+
14
+ def _with_config(delayed_func, config):
15
+ """Helper function that intends to attach a config to a delayed function."""
16
+ if hasattr(delayed_func, "with_config"):
17
+ return delayed_func.with_config(config)
18
+ else:
19
+ warnings.warn(
20
+ (
21
+ "`sklearn.utils.parallel.Parallel` needs to be used in "
22
+ "conjunction with `sklearn.utils.parallel.delayed` instead of "
23
+ "`joblib.delayed` to correctly propagate the scikit-learn "
24
+ "configuration to the joblib workers."
25
+ ),
26
+ UserWarning,
27
+ )
28
+ return delayed_func
29
+
30
+
31
+ class Parallel(joblib.Parallel):
32
+ """Tweak of :class:`joblib.Parallel` that propagates the scikit-learn configuration.
33
+
34
+ This subclass of :class:`joblib.Parallel` ensures that the active configuration
35
+ (thread-local) of scikit-learn is propagated to the parallel workers for the
36
+ duration of the execution of the parallel tasks.
37
+
38
+ The API does not change and you can refer to :class:`joblib.Parallel`
39
+ documentation for more details.
40
+
41
+ .. versionadded:: 1.3
42
+ """
43
+
44
+ def __call__(self, iterable):
45
+ """Dispatch the tasks and return the results.
46
+
47
+ Parameters
48
+ ----------
49
+ iterable : iterable
50
+ Iterable containing tuples of (delayed_function, args, kwargs) that should
51
+ be consumed.
52
+
53
+ Returns
54
+ -------
55
+ results : list
56
+ List of results of the tasks.
57
+ """
58
+ # Capture the thread-local scikit-learn configuration at the time
59
+ # Parallel.__call__ is issued since the tasks can be dispatched
60
+ # in a different thread depending on the backend and on the value of
61
+ # pre_dispatch and n_jobs.
62
+ config = get_config()
63
+ iterable_with_config = (
64
+ (_with_config(delayed_func, config), args, kwargs)
65
+ for delayed_func, args, kwargs in iterable
66
+ )
67
+ return super().__call__(iterable_with_config)
68
+
69
+
70
+ # remove when https://github.com/joblib/joblib/issues/1071 is fixed
71
+ def delayed(function):
72
+ """Decorator used to capture the arguments of a function.
73
+
74
+ This alternative to `joblib.delayed` is meant to be used in conjunction
75
+ with `sklearn.utils.parallel.Parallel`. The latter captures the scikit-
76
+ learn configuration by calling `sklearn.get_config()` in the current
77
+ thread, prior to dispatching the first task. The captured configuration is
78
+ then propagated and enabled for the duration of the execution of the
79
+ delayed function in the joblib workers.
80
+
81
+ .. versionchanged:: 1.3
82
+ `delayed` was moved from `sklearn.utils.fixes` to `sklearn.utils.parallel`
83
+ in scikit-learn 1.3.
84
+
85
+ Parameters
86
+ ----------
87
+ function : callable
88
+ The function to be delayed.
89
+
90
+ Returns
91
+ -------
92
+ output: tuple
93
+ Tuple containing the delayed function, the positional arguments, and the
94
+ keyword arguments.
95
+ """
96
+
97
+ @functools.wraps(function)
98
+ def delayed_function(*args, **kwargs):
99
+ return _FuncWrapper(function), args, kwargs
100
+
101
+ return delayed_function
102
+
103
+
104
+ class _FuncWrapper:
105
+ """Load the global configuration before calling the function."""
106
+
107
+ def __init__(self, function):
108
+ self.function = function
109
+ update_wrapper(self, self.function)
110
+
111
+ def with_config(self, config):
112
+ self.config = config
113
+ return self
114
+
115
+ def __call__(self, *args, **kwargs):
116
+ config = getattr(self, "config", None)
117
+ if config is None:
118
+ warnings.warn(
119
+ (
120
+ "`sklearn.utils.parallel.delayed` should be used with"
121
+ " `sklearn.utils.parallel.Parallel` to make it possible to"
122
+ " propagate the scikit-learn configuration of the current thread to"
123
+ " the joblib workers."
124
+ ),
125
+ UserWarning,
126
+ )
127
+ config = {}
128
+ with config_context(**config):
129
+ return self.function(*args, **kwargs)
venv/lib/python3.10/site-packages/sklearn/utils/sparsefuncs.py ADDED
@@ -0,0 +1,745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The :mod:`sklearn.utils.sparsefuncs` module includes a collection of utilities to
3
+ work with sparse matrices and arrays.
4
+ """
5
+
6
+ # Authors: Manoj Kumar
7
+ # Thomas Unterthiner
8
+ # Giorgio Patrini
9
+ #
10
+ # License: BSD 3 clause
11
+ import numpy as np
12
+ import scipy.sparse as sp
13
+ from scipy.sparse.linalg import LinearOperator
14
+
15
+ from ..utils.fixes import _sparse_min_max, _sparse_nan_min_max
16
+ from ..utils.validation import _check_sample_weight
17
+ from .sparsefuncs_fast import (
18
+ csc_mean_variance_axis0 as _csc_mean_var_axis0,
19
+ )
20
+ from .sparsefuncs_fast import (
21
+ csr_mean_variance_axis0 as _csr_mean_var_axis0,
22
+ )
23
+ from .sparsefuncs_fast import (
24
+ incr_mean_variance_axis0 as _incr_mean_var_axis0,
25
+ )
26
+
27
+
28
+ def _raise_typeerror(X):
29
+ """Raises a TypeError if X is not a CSR or CSC matrix"""
30
+ input_type = X.format if sp.issparse(X) else type(X)
31
+ err = "Expected a CSR or CSC sparse matrix, got %s." % input_type
32
+ raise TypeError(err)
33
+
34
+
35
+ def _raise_error_wrong_axis(axis):
36
+ if axis not in (0, 1):
37
+ raise ValueError(
38
+ "Unknown axis value: %d. Use 0 for rows, or 1 for columns" % axis
39
+ )
40
+
41
+
42
+ def inplace_csr_column_scale(X, scale):
43
+ """Inplace column scaling of a CSR matrix.
44
+
45
+ Scale each feature of the data matrix by multiplying with specific scale
46
+ provided by the caller assuming a (n_samples, n_features) shape.
47
+
48
+ Parameters
49
+ ----------
50
+ X : sparse matrix of shape (n_samples, n_features)
51
+ Matrix to normalize using the variance of the features.
52
+ It should be of CSR format.
53
+
54
+ scale : ndarray of shape (n_features,), dtype={np.float32, np.float64}
55
+ Array of precomputed feature-wise values to use for scaling.
56
+
57
+ Examples
58
+ --------
59
+ >>> from sklearn.utils import sparsefuncs
60
+ >>> from scipy import sparse
61
+ >>> import numpy as np
62
+ >>> indptr = np.array([0, 3, 4, 4, 4])
63
+ >>> indices = np.array([0, 1, 2, 2])
64
+ >>> data = np.array([8, 1, 2, 5])
65
+ >>> scale = np.array([2, 3, 2])
66
+ >>> csr = sparse.csr_matrix((data, indices, indptr))
67
+ >>> csr.todense()
68
+ matrix([[8, 1, 2],
69
+ [0, 0, 5],
70
+ [0, 0, 0],
71
+ [0, 0, 0]])
72
+ >>> sparsefuncs.inplace_csr_column_scale(csr, scale)
73
+ >>> csr.todense()
74
+ matrix([[16, 3, 4],
75
+ [ 0, 0, 10],
76
+ [ 0, 0, 0],
77
+ [ 0, 0, 0]])
78
+ """
79
+ assert scale.shape[0] == X.shape[1]
80
+ X.data *= scale.take(X.indices, mode="clip")
81
+
82
+
83
+ def inplace_csr_row_scale(X, scale):
84
+ """Inplace row scaling of a CSR matrix.
85
+
86
+ Scale each sample of the data matrix by multiplying with specific scale
87
+ provided by the caller assuming a (n_samples, n_features) shape.
88
+
89
+ Parameters
90
+ ----------
91
+ X : sparse matrix of shape (n_samples, n_features)
92
+ Matrix to be scaled. It should be of CSR format.
93
+
94
+ scale : ndarray of float of shape (n_samples,)
95
+ Array of precomputed sample-wise values to use for scaling.
96
+ """
97
+ assert scale.shape[0] == X.shape[0]
98
+ X.data *= np.repeat(scale, np.diff(X.indptr))
99
+
100
+
101
+ def mean_variance_axis(X, axis, weights=None, return_sum_weights=False):
102
+ """Compute mean and variance along an axis on a CSR or CSC matrix.
103
+
104
+ Parameters
105
+ ----------
106
+ X : sparse matrix of shape (n_samples, n_features)
107
+ Input data. It can be of CSR or CSC format.
108
+
109
+ axis : {0, 1}
110
+ Axis along which the axis should be computed.
111
+
112
+ weights : ndarray of shape (n_samples,) or (n_features,), default=None
113
+ If axis is set to 0 shape is (n_samples,) or
114
+ if axis is set to 1 shape is (n_features,).
115
+ If it is set to None, then samples are equally weighted.
116
+
117
+ .. versionadded:: 0.24
118
+
119
+ return_sum_weights : bool, default=False
120
+ If True, returns the sum of weights seen for each feature
121
+ if `axis=0` or each sample if `axis=1`.
122
+
123
+ .. versionadded:: 0.24
124
+
125
+ Returns
126
+ -------
127
+
128
+ means : ndarray of shape (n_features,), dtype=floating
129
+ Feature-wise means.
130
+
131
+ variances : ndarray of shape (n_features,), dtype=floating
132
+ Feature-wise variances.
133
+
134
+ sum_weights : ndarray of shape (n_features,), dtype=floating
135
+ Returned if `return_sum_weights` is `True`.
136
+
137
+ Examples
138
+ --------
139
+ >>> from sklearn.utils import sparsefuncs
140
+ >>> from scipy import sparse
141
+ >>> import numpy as np
142
+ >>> indptr = np.array([0, 3, 4, 4, 4])
143
+ >>> indices = np.array([0, 1, 2, 2])
144
+ >>> data = np.array([8, 1, 2, 5])
145
+ >>> scale = np.array([2, 3, 2])
146
+ >>> csr = sparse.csr_matrix((data, indices, indptr))
147
+ >>> csr.todense()
148
+ matrix([[8, 1, 2],
149
+ [0, 0, 5],
150
+ [0, 0, 0],
151
+ [0, 0, 0]])
152
+ >>> sparsefuncs.mean_variance_axis(csr, axis=0)
153
+ (array([2. , 0.25, 1.75]), array([12. , 0.1875, 4.1875]))
154
+ """
155
+ _raise_error_wrong_axis(axis)
156
+
157
+ if sp.issparse(X) and X.format == "csr":
158
+ if axis == 0:
159
+ return _csr_mean_var_axis0(
160
+ X, weights=weights, return_sum_weights=return_sum_weights
161
+ )
162
+ else:
163
+ return _csc_mean_var_axis0(
164
+ X.T, weights=weights, return_sum_weights=return_sum_weights
165
+ )
166
+ elif sp.issparse(X) and X.format == "csc":
167
+ if axis == 0:
168
+ return _csc_mean_var_axis0(
169
+ X, weights=weights, return_sum_weights=return_sum_weights
170
+ )
171
+ else:
172
+ return _csr_mean_var_axis0(
173
+ X.T, weights=weights, return_sum_weights=return_sum_weights
174
+ )
175
+ else:
176
+ _raise_typeerror(X)
177
+
178
+
179
+ def incr_mean_variance_axis(X, *, axis, last_mean, last_var, last_n, weights=None):
180
+ """Compute incremental mean and variance along an axis on a CSR or CSC matrix.
181
+
182
+ last_mean, last_var are the statistics computed at the last step by this
183
+ function. Both must be initialized to 0-arrays of the proper size, i.e.
184
+ the number of features in X. last_n is the number of samples encountered
185
+ until now.
186
+
187
+ Parameters
188
+ ----------
189
+ X : CSR or CSC sparse matrix of shape (n_samples, n_features)
190
+ Input data.
191
+
192
+ axis : {0, 1}
193
+ Axis along which the axis should be computed.
194
+
195
+ last_mean : ndarray of shape (n_features,) or (n_samples,), dtype=floating
196
+ Array of means to update with the new data X.
197
+ Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1.
198
+
199
+ last_var : ndarray of shape (n_features,) or (n_samples,), dtype=floating
200
+ Array of variances to update with the new data X.
201
+ Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1.
202
+
203
+ last_n : float or ndarray of shape (n_features,) or (n_samples,), \
204
+ dtype=floating
205
+ Sum of the weights seen so far, excluding the current weights
206
+ If not float, it should be of shape (n_features,) if
207
+ axis=0 or (n_samples,) if axis=1. If float it corresponds to
208
+ having same weights for all samples (or features).
209
+
210
+ weights : ndarray of shape (n_samples,) or (n_features,), default=None
211
+ If axis is set to 0 shape is (n_samples,) or
212
+ if axis is set to 1 shape is (n_features,).
213
+ If it is set to None, then samples are equally weighted.
214
+
215
+ .. versionadded:: 0.24
216
+
217
+ Returns
218
+ -------
219
+ means : ndarray of shape (n_features,) or (n_samples,), dtype=floating
220
+ Updated feature-wise means if axis = 0 or
221
+ sample-wise means if axis = 1.
222
+
223
+ variances : ndarray of shape (n_features,) or (n_samples,), dtype=floating
224
+ Updated feature-wise variances if axis = 0 or
225
+ sample-wise variances if axis = 1.
226
+
227
+ n : ndarray of shape (n_features,) or (n_samples,), dtype=integral
228
+ Updated number of seen samples per feature if axis=0
229
+ or number of seen features per sample if axis=1.
230
+
231
+ If weights is not None, n is a sum of the weights of the seen
232
+ samples or features instead of the actual number of seen
233
+ samples or features.
234
+
235
+ Notes
236
+ -----
237
+ NaNs are ignored in the algorithm.
238
+
239
+ Examples
240
+ --------
241
+ >>> from sklearn.utils import sparsefuncs
242
+ >>> from scipy import sparse
243
+ >>> import numpy as np
244
+ >>> indptr = np.array([0, 3, 4, 4, 4])
245
+ >>> indices = np.array([0, 1, 2, 2])
246
+ >>> data = np.array([8, 1, 2, 5])
247
+ >>> scale = np.array([2, 3, 2])
248
+ >>> csr = sparse.csr_matrix((data, indices, indptr))
249
+ >>> csr.todense()
250
+ matrix([[8, 1, 2],
251
+ [0, 0, 5],
252
+ [0, 0, 0],
253
+ [0, 0, 0]])
254
+ >>> sparsefuncs.incr_mean_variance_axis(
255
+ ... csr, axis=0, last_mean=np.zeros(3), last_var=np.zeros(3), last_n=2
256
+ ... )
257
+ (array([1.3..., 0.1..., 1.1...]), array([8.8..., 0.1..., 3.4...]),
258
+ array([6., 6., 6.]))
259
+ """
260
+ _raise_error_wrong_axis(axis)
261
+
262
+ if not (sp.issparse(X) and X.format in ("csc", "csr")):
263
+ _raise_typeerror(X)
264
+
265
+ if np.size(last_n) == 1:
266
+ last_n = np.full(last_mean.shape, last_n, dtype=last_mean.dtype)
267
+
268
+ if not (np.size(last_mean) == np.size(last_var) == np.size(last_n)):
269
+ raise ValueError("last_mean, last_var, last_n do not have the same shapes.")
270
+
271
+ if axis == 1:
272
+ if np.size(last_mean) != X.shape[0]:
273
+ raise ValueError(
274
+ "If axis=1, then last_mean, last_n, last_var should be of "
275
+ f"size n_samples {X.shape[0]} (Got {np.size(last_mean)})."
276
+ )
277
+ else: # axis == 0
278
+ if np.size(last_mean) != X.shape[1]:
279
+ raise ValueError(
280
+ "If axis=0, then last_mean, last_n, last_var should be of "
281
+ f"size n_features {X.shape[1]} (Got {np.size(last_mean)})."
282
+ )
283
+
284
+ X = X.T if axis == 1 else X
285
+
286
+ if weights is not None:
287
+ weights = _check_sample_weight(weights, X, dtype=X.dtype)
288
+
289
+ return _incr_mean_var_axis0(
290
+ X, last_mean=last_mean, last_var=last_var, last_n=last_n, weights=weights
291
+ )
292
+
293
+
294
+ def inplace_column_scale(X, scale):
295
+ """Inplace column scaling of a CSC/CSR matrix.
296
+
297
+ Scale each feature of the data matrix by multiplying with specific scale
298
+ provided by the caller assuming a (n_samples, n_features) shape.
299
+
300
+ Parameters
301
+ ----------
302
+ X : sparse matrix of shape (n_samples, n_features)
303
+ Matrix to normalize using the variance of the features. It should be
304
+ of CSC or CSR format.
305
+
306
+ scale : ndarray of shape (n_features,), dtype={np.float32, np.float64}
307
+ Array of precomputed feature-wise values to use for scaling.
308
+
309
+ Examples
310
+ --------
311
+ >>> from sklearn.utils import sparsefuncs
312
+ >>> from scipy import sparse
313
+ >>> import numpy as np
314
+ >>> indptr = np.array([0, 3, 4, 4, 4])
315
+ >>> indices = np.array([0, 1, 2, 2])
316
+ >>> data = np.array([8, 1, 2, 5])
317
+ >>> scale = np.array([2, 3, 2])
318
+ >>> csr = sparse.csr_matrix((data, indices, indptr))
319
+ >>> csr.todense()
320
+ matrix([[8, 1, 2],
321
+ [0, 0, 5],
322
+ [0, 0, 0],
323
+ [0, 0, 0]])
324
+ >>> sparsefuncs.inplace_column_scale(csr, scale)
325
+ >>> csr.todense()
326
+ matrix([[16, 3, 4],
327
+ [ 0, 0, 10],
328
+ [ 0, 0, 0],
329
+ [ 0, 0, 0]])
330
+ """
331
+ if sp.issparse(X) and X.format == "csc":
332
+ inplace_csr_row_scale(X.T, scale)
333
+ elif sp.issparse(X) and X.format == "csr":
334
+ inplace_csr_column_scale(X, scale)
335
+ else:
336
+ _raise_typeerror(X)
337
+
338
+
339
+ def inplace_row_scale(X, scale):
340
+ """Inplace row scaling of a CSR or CSC matrix.
341
+
342
+ Scale each row of the data matrix by multiplying with specific scale
343
+ provided by the caller assuming a (n_samples, n_features) shape.
344
+
345
+ Parameters
346
+ ----------
347
+ X : sparse matrix of shape (n_samples, n_features)
348
+ Matrix to be scaled. It should be of CSR or CSC format.
349
+
350
+ scale : ndarray of shape (n_features,), dtype={np.float32, np.float64}
351
+ Array of precomputed sample-wise values to use for scaling.
352
+
353
+ Examples
354
+ --------
355
+ >>> from sklearn.utils import sparsefuncs
356
+ >>> from scipy import sparse
357
+ >>> import numpy as np
358
+ >>> indptr = np.array([0, 2, 3, 4, 5])
359
+ >>> indices = np.array([0, 1, 2, 3, 3])
360
+ >>> data = np.array([8, 1, 2, 5, 6])
361
+ >>> scale = np.array([2, 3, 4, 5])
362
+ >>> csr = sparse.csr_matrix((data, indices, indptr))
363
+ >>> csr.todense()
364
+ matrix([[8, 1, 0, 0],
365
+ [0, 0, 2, 0],
366
+ [0, 0, 0, 5],
367
+ [0, 0, 0, 6]])
368
+ >>> sparsefuncs.inplace_row_scale(csr, scale)
369
+ >>> csr.todense()
370
+ matrix([[16, 2, 0, 0],
371
+ [ 0, 0, 6, 0],
372
+ [ 0, 0, 0, 20],
373
+ [ 0, 0, 0, 30]])
374
+ """
375
+ if sp.issparse(X) and X.format == "csc":
376
+ inplace_csr_column_scale(X.T, scale)
377
+ elif sp.issparse(X) and X.format == "csr":
378
+ inplace_csr_row_scale(X, scale)
379
+ else:
380
+ _raise_typeerror(X)
381
+
382
+
383
+ def inplace_swap_row_csc(X, m, n):
384
+ """Swap two rows of a CSC matrix in-place.
385
+
386
+ Parameters
387
+ ----------
388
+ X : sparse matrix of shape (n_samples, n_features)
389
+ Matrix whose two rows are to be swapped. It should be of
390
+ CSC format.
391
+
392
+ m : int
393
+ Index of the row of X to be swapped.
394
+
395
+ n : int
396
+ Index of the row of X to be swapped.
397
+ """
398
+ for t in [m, n]:
399
+ if isinstance(t, np.ndarray):
400
+ raise TypeError("m and n should be valid integers")
401
+
402
+ if m < 0:
403
+ m += X.shape[0]
404
+ if n < 0:
405
+ n += X.shape[0]
406
+
407
+ m_mask = X.indices == m
408
+ X.indices[X.indices == n] = m
409
+ X.indices[m_mask] = n
410
+
411
+
412
+ def inplace_swap_row_csr(X, m, n):
413
+ """Swap two rows of a CSR matrix in-place.
414
+
415
+ Parameters
416
+ ----------
417
+ X : sparse matrix of shape (n_samples, n_features)
418
+ Matrix whose two rows are to be swapped. It should be of
419
+ CSR format.
420
+
421
+ m : int
422
+ Index of the row of X to be swapped.
423
+
424
+ n : int
425
+ Index of the row of X to be swapped.
426
+ """
427
+ for t in [m, n]:
428
+ if isinstance(t, np.ndarray):
429
+ raise TypeError("m and n should be valid integers")
430
+
431
+ if m < 0:
432
+ m += X.shape[0]
433
+ if n < 0:
434
+ n += X.shape[0]
435
+
436
+ # The following swapping makes life easier since m is assumed to be the
437
+ # smaller integer below.
438
+ if m > n:
439
+ m, n = n, m
440
+
441
+ indptr = X.indptr
442
+ m_start = indptr[m]
443
+ m_stop = indptr[m + 1]
444
+ n_start = indptr[n]
445
+ n_stop = indptr[n + 1]
446
+ nz_m = m_stop - m_start
447
+ nz_n = n_stop - n_start
448
+
449
+ if nz_m != nz_n:
450
+ # Modify indptr first
451
+ X.indptr[m + 2 : n] += nz_n - nz_m
452
+ X.indptr[m + 1] = m_start + nz_n
453
+ X.indptr[n] = n_stop - nz_m
454
+
455
+ X.indices = np.concatenate(
456
+ [
457
+ X.indices[:m_start],
458
+ X.indices[n_start:n_stop],
459
+ X.indices[m_stop:n_start],
460
+ X.indices[m_start:m_stop],
461
+ X.indices[n_stop:],
462
+ ]
463
+ )
464
+ X.data = np.concatenate(
465
+ [
466
+ X.data[:m_start],
467
+ X.data[n_start:n_stop],
468
+ X.data[m_stop:n_start],
469
+ X.data[m_start:m_stop],
470
+ X.data[n_stop:],
471
+ ]
472
+ )
473
+
474
+
475
+ def inplace_swap_row(X, m, n):
476
+ """
477
+ Swap two rows of a CSC/CSR matrix in-place.
478
+
479
+ Parameters
480
+ ----------
481
+ X : sparse matrix of shape (n_samples, n_features)
482
+ Matrix whose two rows are to be swapped. It should be of CSR or
483
+ CSC format.
484
+
485
+ m : int
486
+ Index of the row of X to be swapped.
487
+
488
+ n : int
489
+ Index of the row of X to be swapped.
490
+
491
+ Examples
492
+ --------
493
+ >>> from sklearn.utils import sparsefuncs
494
+ >>> from scipy import sparse
495
+ >>> import numpy as np
496
+ >>> indptr = np.array([0, 2, 3, 3, 3])
497
+ >>> indices = np.array([0, 2, 2])
498
+ >>> data = np.array([8, 2, 5])
499
+ >>> csr = sparse.csr_matrix((data, indices, indptr))
500
+ >>> csr.todense()
501
+ matrix([[8, 0, 2],
502
+ [0, 0, 5],
503
+ [0, 0, 0],
504
+ [0, 0, 0]])
505
+ >>> sparsefuncs.inplace_swap_row(csr, 0, 1)
506
+ >>> csr.todense()
507
+ matrix([[0, 0, 5],
508
+ [8, 0, 2],
509
+ [0, 0, 0],
510
+ [0, 0, 0]])
511
+ """
512
+ if sp.issparse(X) and X.format == "csc":
513
+ inplace_swap_row_csc(X, m, n)
514
+ elif sp.issparse(X) and X.format == "csr":
515
+ inplace_swap_row_csr(X, m, n)
516
+ else:
517
+ _raise_typeerror(X)
518
+
519
+
520
+ def inplace_swap_column(X, m, n):
521
+ """
522
+ Swap two columns of a CSC/CSR matrix in-place.
523
+
524
+ Parameters
525
+ ----------
526
+ X : sparse matrix of shape (n_samples, n_features)
527
+ Matrix whose two columns are to be swapped. It should be of
528
+ CSR or CSC format.
529
+
530
+ m : int
531
+ Index of the column of X to be swapped.
532
+
533
+ n : int
534
+ Index of the column of X to be swapped.
535
+
536
+ Examples
537
+ --------
538
+ >>> from sklearn.utils import sparsefuncs
539
+ >>> from scipy import sparse
540
+ >>> import numpy as np
541
+ >>> indptr = np.array([0, 2, 3, 3, 3])
542
+ >>> indices = np.array([0, 2, 2])
543
+ >>> data = np.array([8, 2, 5])
544
+ >>> csr = sparse.csr_matrix((data, indices, indptr))
545
+ >>> csr.todense()
546
+ matrix([[8, 0, 2],
547
+ [0, 0, 5],
548
+ [0, 0, 0],
549
+ [0, 0, 0]])
550
+ >>> sparsefuncs.inplace_swap_column(csr, 0, 1)
551
+ >>> csr.todense()
552
+ matrix([[0, 8, 2],
553
+ [0, 0, 5],
554
+ [0, 0, 0],
555
+ [0, 0, 0]])
556
+ """
557
+ if m < 0:
558
+ m += X.shape[1]
559
+ if n < 0:
560
+ n += X.shape[1]
561
+ if sp.issparse(X) and X.format == "csc":
562
+ inplace_swap_row_csr(X, m, n)
563
+ elif sp.issparse(X) and X.format == "csr":
564
+ inplace_swap_row_csc(X, m, n)
565
+ else:
566
+ _raise_typeerror(X)
567
+
568
+
569
+ def min_max_axis(X, axis, ignore_nan=False):
570
+ """Compute minimum and maximum along an axis on a CSR or CSC matrix.
571
+
572
+ Optionally ignore NaN values.
573
+
574
+ Parameters
575
+ ----------
576
+ X : sparse matrix of shape (n_samples, n_features)
577
+ Input data. It should be of CSR or CSC format.
578
+
579
+ axis : {0, 1}
580
+ Axis along which the axis should be computed.
581
+
582
+ ignore_nan : bool, default=False
583
+ Ignore or passing through NaN values.
584
+
585
+ .. versionadded:: 0.20
586
+
587
+ Returns
588
+ -------
589
+
590
+ mins : ndarray of shape (n_features,), dtype={np.float32, np.float64}
591
+ Feature-wise minima.
592
+
593
+ maxs : ndarray of shape (n_features,), dtype={np.float32, np.float64}
594
+ Feature-wise maxima.
595
+ """
596
+ if sp.issparse(X) and X.format in ("csr", "csc"):
597
+ if ignore_nan:
598
+ return _sparse_nan_min_max(X, axis=axis)
599
+ else:
600
+ return _sparse_min_max(X, axis=axis)
601
+ else:
602
+ _raise_typeerror(X)
603
+
604
+
605
+ def count_nonzero(X, axis=None, sample_weight=None):
606
+ """A variant of X.getnnz() with extension to weighting on axis 0.
607
+
608
+ Useful in efficiently calculating multilabel metrics.
609
+
610
+ Parameters
611
+ ----------
612
+ X : sparse matrix of shape (n_samples, n_labels)
613
+ Input data. It should be of CSR format.
614
+
615
+ axis : {0, 1}, default=None
616
+ The axis on which the data is aggregated.
617
+
618
+ sample_weight : array-like of shape (n_samples,), default=None
619
+ Weight for each row of X.
620
+
621
+ Returns
622
+ -------
623
+ nnz : int, float, ndarray of shape (n_samples,) or ndarray of shape (n_features,)
624
+ Number of non-zero values in the array along a given axis. Otherwise,
625
+ the total number of non-zero values in the array is returned.
626
+ """
627
+ if axis == -1:
628
+ axis = 1
629
+ elif axis == -2:
630
+ axis = 0
631
+ elif X.format != "csr":
632
+ raise TypeError("Expected CSR sparse format, got {0}".format(X.format))
633
+
634
+ # We rely here on the fact that np.diff(Y.indptr) for a CSR
635
+ # will return the number of nonzero entries in each row.
636
+ # A bincount over Y.indices will return the number of nonzeros
637
+ # in each column. See ``csr_matrix.getnnz`` in scipy >= 0.14.
638
+ if axis is None:
639
+ if sample_weight is None:
640
+ return X.nnz
641
+ else:
642
+ return np.dot(np.diff(X.indptr), sample_weight)
643
+ elif axis == 1:
644
+ out = np.diff(X.indptr)
645
+ if sample_weight is None:
646
+ # astype here is for consistency with axis=0 dtype
647
+ return out.astype("intp")
648
+ return out * sample_weight
649
+ elif axis == 0:
650
+ if sample_weight is None:
651
+ return np.bincount(X.indices, minlength=X.shape[1])
652
+ else:
653
+ weights = np.repeat(sample_weight, np.diff(X.indptr))
654
+ return np.bincount(X.indices, minlength=X.shape[1], weights=weights)
655
+ else:
656
+ raise ValueError("Unsupported axis: {0}".format(axis))
657
+
658
+
659
+ def _get_median(data, n_zeros):
660
+ """Compute the median of data with n_zeros additional zeros.
661
+
662
+ This function is used to support sparse matrices; it modifies data
663
+ in-place.
664
+ """
665
+ n_elems = len(data) + n_zeros
666
+ if not n_elems:
667
+ return np.nan
668
+ n_negative = np.count_nonzero(data < 0)
669
+ middle, is_odd = divmod(n_elems, 2)
670
+ data.sort()
671
+
672
+ if is_odd:
673
+ return _get_elem_at_rank(middle, data, n_negative, n_zeros)
674
+
675
+ return (
676
+ _get_elem_at_rank(middle - 1, data, n_negative, n_zeros)
677
+ + _get_elem_at_rank(middle, data, n_negative, n_zeros)
678
+ ) / 2.0
679
+
680
+
681
+ def _get_elem_at_rank(rank, data, n_negative, n_zeros):
682
+ """Find the value in data augmented with n_zeros for the given rank"""
683
+ if rank < n_negative:
684
+ return data[rank]
685
+ if rank - n_negative < n_zeros:
686
+ return 0
687
+ return data[rank - n_zeros]
688
+
689
+
690
+ def csc_median_axis_0(X):
691
+ """Find the median across axis 0 of a CSC matrix.
692
+
693
+ It is equivalent to doing np.median(X, axis=0).
694
+
695
+ Parameters
696
+ ----------
697
+ X : sparse matrix of shape (n_samples, n_features)
698
+ Input data. It should be of CSC format.
699
+
700
+ Returns
701
+ -------
702
+ median : ndarray of shape (n_features,)
703
+ Median.
704
+ """
705
+ if not (sp.issparse(X) and X.format == "csc"):
706
+ raise TypeError("Expected matrix of CSC format, got %s" % X.format)
707
+
708
+ indptr = X.indptr
709
+ n_samples, n_features = X.shape
710
+ median = np.zeros(n_features)
711
+
712
+ for f_ind, (start, end) in enumerate(zip(indptr[:-1], indptr[1:])):
713
+ # Prevent modifying X in place
714
+ data = np.copy(X.data[start:end])
715
+ nz = n_samples - data.size
716
+ median[f_ind] = _get_median(data, nz)
717
+
718
+ return median
719
+
720
+
721
+ def _implicit_column_offset(X, offset):
722
+ """Create an implicitly offset linear operator.
723
+
724
+ This is used by PCA on sparse data to avoid densifying the whole data
725
+ matrix.
726
+
727
+ Params
728
+ ------
729
+ X : sparse matrix of shape (n_samples, n_features)
730
+ offset : ndarray of shape (n_features,)
731
+
732
+ Returns
733
+ -------
734
+ centered : LinearOperator
735
+ """
736
+ offset = offset[None, :]
737
+ XT = X.T
738
+ return LinearOperator(
739
+ matvec=lambda x: X @ x - offset @ x,
740
+ matmat=lambda x: X @ x - offset @ x,
741
+ rmatvec=lambda x: XT @ x - (offset * x.sum()),
742
+ rmatmat=lambda x: XT @ x - offset.T @ x.sum(axis=0)[None, :],
743
+ dtype=X.dtype,
744
+ shape=X.shape,
745
+ )
venv/lib/python3.10/site-packages/sklearn/utils/sparsefuncs_fast.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (840 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/stats.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from .extmath import stable_cumsum
4
+
5
+
6
+ def _weighted_percentile(array, sample_weight, percentile=50):
7
+ """Compute weighted percentile
8
+
9
+ Computes lower weighted percentile. If `array` is a 2D array, the
10
+ `percentile` is computed along the axis 0.
11
+
12
+ .. versionchanged:: 0.24
13
+ Accepts 2D `array`.
14
+
15
+ Parameters
16
+ ----------
17
+ array : 1D or 2D array
18
+ Values to take the weighted percentile of.
19
+
20
+ sample_weight: 1D or 2D array
21
+ Weights for each value in `array`. Must be same shape as `array` or
22
+ of shape `(array.shape[0],)`.
23
+
24
+ percentile: int or float, default=50
25
+ Percentile to compute. Must be value between 0 and 100.
26
+
27
+ Returns
28
+ -------
29
+ percentile : int if `array` 1D, ndarray if `array` 2D
30
+ Weighted percentile.
31
+ """
32
+ n_dim = array.ndim
33
+ if n_dim == 0:
34
+ return array[()]
35
+ if array.ndim == 1:
36
+ array = array.reshape((-1, 1))
37
+ # When sample_weight 1D, repeat for each array.shape[1]
38
+ if array.shape != sample_weight.shape and array.shape[0] == sample_weight.shape[0]:
39
+ sample_weight = np.tile(sample_weight, (array.shape[1], 1)).T
40
+ sorted_idx = np.argsort(array, axis=0)
41
+ sorted_weights = np.take_along_axis(sample_weight, sorted_idx, axis=0)
42
+
43
+ # Find index of median prediction for each sample
44
+ weight_cdf = stable_cumsum(sorted_weights, axis=0)
45
+ adjusted_percentile = percentile / 100 * weight_cdf[-1]
46
+
47
+ # For percentile=0, ignore leading observations with sample_weight=0. GH20528
48
+ mask = adjusted_percentile == 0
49
+ adjusted_percentile[mask] = np.nextafter(
50
+ adjusted_percentile[mask], adjusted_percentile[mask] + 1
51
+ )
52
+
53
+ percentile_idx = np.array(
54
+ [
55
+ np.searchsorted(weight_cdf[:, i], adjusted_percentile[i])
56
+ for i in range(weight_cdf.shape[1])
57
+ ]
58
+ )
59
+ percentile_idx = np.array(percentile_idx)
60
+ # In rare cases, percentile_idx equals to sorted_idx.shape[0]
61
+ max_idx = sorted_idx.shape[0] - 1
62
+ percentile_idx = np.apply_along_axis(
63
+ lambda x: np.clip(x, 0, max_idx), axis=0, arr=percentile_idx
64
+ )
65
+
66
+ col_index = np.arange(array.shape[1])
67
+ percentile_in_sorted = sorted_idx[percentile_idx, col_index]
68
+ percentile = array[percentile_in_sorted, col_index]
69
+ return percentile[0] if n_dim == 1 else percentile
venv/lib/python3.10/site-packages/sklearn/utils/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_bunch.cpython-310.pyc ADDED
Binary file (999 Bytes). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc ADDED
Binary file (43.1 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_multiclass.cpython-310.pyc ADDED
Binary file (13.9 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc ADDED
Binary file (1.49 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_param_validation.cpython-310.pyc ADDED
Binary file (21.7 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_plotting.cpython-310.pyc ADDED
Binary file (1.68 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_seq_dataset.cpython-310.pyc ADDED
Binary file (5.24 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_show_versions.cpython-310.pyc ADDED
Binary file (1.32 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_stats.cpython-310.pyc ADDED
Binary file (3.09 kB). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_weight_vector.cpython-310.pyc ADDED
Binary file (812 Bytes). View file
 
venv/lib/python3.10/site-packages/sklearn/utils/tests/test_arpack.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from numpy.testing import assert_allclose
3
+
4
+ from sklearn.utils import check_random_state
5
+ from sklearn.utils._arpack import _init_arpack_v0
6
+
7
+
8
+ @pytest.mark.parametrize("seed", range(100))
9
+ def test_init_arpack_v0(seed):
10
+ # check that the initialization a sampling from an uniform distribution
11
+ # where we can fix the random state
12
+ size = 1000
13
+ v0 = _init_arpack_v0(size, seed)
14
+
15
+ rng = check_random_state(seed)
16
+ assert_allclose(v0, rng.uniform(-1, 1, size=size))
venv/lib/python3.10/site-packages/sklearn/utils/tests/test_array_api.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+
3
+ import numpy
4
+ import pytest
5
+ from numpy.testing import assert_allclose
6
+
7
+ from sklearn._config import config_context
8
+ from sklearn.base import BaseEstimator
9
+ from sklearn.utils._array_api import (
10
+ _ArrayAPIWrapper,
11
+ _asarray_with_order,
12
+ _atol_for_type,
13
+ _convert_to_numpy,
14
+ _estimator_with_converted_arrays,
15
+ _nanmax,
16
+ _nanmin,
17
+ _NumPyAPIWrapper,
18
+ _weighted_sum,
19
+ get_namespace,
20
+ supported_float_dtypes,
21
+ yield_namespace_device_dtype_combinations,
22
+ )
23
+ from sklearn.utils._testing import (
24
+ _array_api_for_tests,
25
+ skip_if_array_api_compat_not_configured,
26
+ )
27
+
28
+ pytestmark = pytest.mark.filterwarnings(
29
+ "ignore:The numpy.array_api submodule:UserWarning"
30
+ )
31
+
32
+
33
+ @pytest.mark.parametrize("X", [numpy.asarray([1, 2, 3]), [1, 2, 3]])
34
+ def test_get_namespace_ndarray_default(X):
35
+ """Check that get_namespace returns NumPy wrapper"""
36
+ xp_out, is_array_api_compliant = get_namespace(X)
37
+ assert isinstance(xp_out, _NumPyAPIWrapper)
38
+ assert not is_array_api_compliant
39
+
40
+
41
+ def test_get_namespace_ndarray_creation_device():
42
+ """Check expected behavior with device and creation functions."""
43
+ X = numpy.asarray([1, 2, 3])
44
+ xp_out, _ = get_namespace(X)
45
+
46
+ full_array = xp_out.full(10, fill_value=2.0, device="cpu")
47
+ assert_allclose(full_array, [2.0] * 10)
48
+
49
+ with pytest.raises(ValueError, match="Unsupported device"):
50
+ xp_out.zeros(10, device="cuda")
51
+
52
+
53
+ @skip_if_array_api_compat_not_configured
54
+ def test_get_namespace_ndarray_with_dispatch():
55
+ """Test get_namespace on NumPy ndarrays."""
56
+ array_api_compat = pytest.importorskip("array_api_compat")
57
+
58
+ X_np = numpy.asarray([[1, 2, 3]])
59
+
60
+ with config_context(array_api_dispatch=True):
61
+ xp_out, is_array_api_compliant = get_namespace(X_np)
62
+ assert is_array_api_compliant
63
+ assert xp_out is array_api_compat.numpy
64
+
65
+
66
+ @skip_if_array_api_compat_not_configured
67
+ def test_get_namespace_array_api():
68
+ """Test get_namespace for ArrayAPI arrays."""
69
+ xp = pytest.importorskip("numpy.array_api")
70
+
71
+ X_np = numpy.asarray([[1, 2, 3]])
72
+ X_xp = xp.asarray(X_np)
73
+ with config_context(array_api_dispatch=True):
74
+ xp_out, is_array_api_compliant = get_namespace(X_xp)
75
+ assert is_array_api_compliant
76
+ assert isinstance(xp_out, _ArrayAPIWrapper)
77
+
78
+ with pytest.raises(TypeError):
79
+ xp_out, is_array_api_compliant = get_namespace(X_xp, X_np)
80
+
81
+
82
+ class _AdjustableNameAPITestWrapper(_ArrayAPIWrapper):
83
+ """API wrapper that has an adjustable name. Used for testing."""
84
+
85
+ def __init__(self, array_namespace, name):
86
+ super().__init__(array_namespace=array_namespace)
87
+ self.__name__ = name
88
+
89
+
90
+ def test_array_api_wrapper_astype():
91
+ """Test _ArrayAPIWrapper for ArrayAPIs that is not NumPy."""
92
+ numpy_array_api = pytest.importorskip("numpy.array_api")
93
+ xp_ = _AdjustableNameAPITestWrapper(numpy_array_api, "wrapped_numpy.array_api")
94
+ xp = _ArrayAPIWrapper(xp_)
95
+
96
+ X = xp.asarray(([[1, 2, 3], [3, 4, 5]]), dtype=xp.float64)
97
+ X_converted = xp.astype(X, xp.float32)
98
+ assert X_converted.dtype == xp.float32
99
+
100
+ X_converted = xp.asarray(X, dtype=xp.float32)
101
+ assert X_converted.dtype == xp.float32
102
+
103
+
104
+ @pytest.mark.parametrize("array_api", ["numpy", "numpy.array_api"])
105
+ def test_asarray_with_order(array_api):
106
+ """Test _asarray_with_order passes along order for NumPy arrays."""
107
+ xp = pytest.importorskip(array_api)
108
+
109
+ X = xp.asarray([1.2, 3.4, 5.1])
110
+ X_new = _asarray_with_order(X, order="F", xp=xp)
111
+
112
+ X_new_np = numpy.asarray(X_new)
113
+ assert X_new_np.flags["F_CONTIGUOUS"]
114
+
115
+
116
+ def test_asarray_with_order_ignored():
117
+ """Test _asarray_with_order ignores order for Generic ArrayAPI."""
118
+ xp = pytest.importorskip("numpy.array_api")
119
+ xp_ = _AdjustableNameAPITestWrapper(xp, "wrapped.array_api")
120
+
121
+ X = numpy.asarray([[1.2, 3.4, 5.1], [3.4, 5.5, 1.2]], order="C")
122
+ X = xp_.asarray(X)
123
+
124
+ X_new = _asarray_with_order(X, order="F", xp=xp_)
125
+
126
+ X_new_np = numpy.asarray(X_new)
127
+ assert X_new_np.flags["C_CONTIGUOUS"]
128
+ assert not X_new_np.flags["F_CONTIGUOUS"]
129
+
130
+
131
+ @pytest.mark.parametrize(
132
+ "array_namespace, device, dtype_name", yield_namespace_device_dtype_combinations()
133
+ )
134
+ @pytest.mark.parametrize(
135
+ "sample_weight, normalize, expected",
136
+ [
137
+ (None, False, 10.0),
138
+ (None, True, 2.5),
139
+ ([0.4, 0.4, 0.5, 0.7], False, 5.5),
140
+ ([0.4, 0.4, 0.5, 0.7], True, 2.75),
141
+ ([1, 2, 3, 4], False, 30.0),
142
+ ([1, 2, 3, 4], True, 3.0),
143
+ ],
144
+ )
145
+ def test_weighted_sum(
146
+ array_namespace, device, dtype_name, sample_weight, normalize, expected
147
+ ):
148
+ xp = _array_api_for_tests(array_namespace, device)
149
+ sample_score = numpy.asarray([1, 2, 3, 4], dtype=dtype_name)
150
+ sample_score = xp.asarray(sample_score, device=device)
151
+ if sample_weight is not None:
152
+ sample_weight = numpy.asarray(sample_weight, dtype=dtype_name)
153
+ sample_weight = xp.asarray(sample_weight, device=device)
154
+
155
+ with config_context(array_api_dispatch=True):
156
+ result = _weighted_sum(sample_score, sample_weight, normalize)
157
+
158
+ assert isinstance(result, float)
159
+ assert_allclose(result, expected, atol=_atol_for_type(dtype_name))
160
+
161
+
162
+ @skip_if_array_api_compat_not_configured
163
+ @pytest.mark.parametrize(
164
+ "library", ["numpy", "numpy.array_api", "cupy", "cupy.array_api", "torch"]
165
+ )
166
+ @pytest.mark.parametrize(
167
+ "X,reduction,expected",
168
+ [
169
+ ([1, 2, numpy.nan], _nanmin, 1),
170
+ ([1, -2, -numpy.nan], _nanmin, -2),
171
+ ([numpy.inf, numpy.inf], _nanmin, numpy.inf),
172
+ (
173
+ [[1, 2, 3], [numpy.nan, numpy.nan, numpy.nan], [4, 5, 6.0]],
174
+ partial(_nanmin, axis=0),
175
+ [1.0, 2.0, 3.0],
176
+ ),
177
+ (
178
+ [[1, 2, 3], [numpy.nan, numpy.nan, numpy.nan], [4, 5, 6.0]],
179
+ partial(_nanmin, axis=1),
180
+ [1.0, numpy.nan, 4.0],
181
+ ),
182
+ ([1, 2, numpy.nan], _nanmax, 2),
183
+ ([1, 2, numpy.nan], _nanmax, 2),
184
+ ([-numpy.inf, -numpy.inf], _nanmax, -numpy.inf),
185
+ (
186
+ [[1, 2, 3], [numpy.nan, numpy.nan, numpy.nan], [4, 5, 6.0]],
187
+ partial(_nanmax, axis=0),
188
+ [4.0, 5.0, 6.0],
189
+ ),
190
+ (
191
+ [[1, 2, 3], [numpy.nan, numpy.nan, numpy.nan], [4, 5, 6.0]],
192
+ partial(_nanmax, axis=1),
193
+ [3.0, numpy.nan, 6.0],
194
+ ),
195
+ ],
196
+ )
197
+ def test_nan_reductions(library, X, reduction, expected):
198
+ """Check NaN reductions like _nanmin and _nanmax"""
199
+ xp = pytest.importorskip(library)
200
+
201
+ if isinstance(expected, list):
202
+ expected = xp.asarray(expected)
203
+
204
+ with config_context(array_api_dispatch=True):
205
+ result = reduction(xp.asarray(X))
206
+
207
+ assert_allclose(result, expected)
208
+
209
+
210
+ @skip_if_array_api_compat_not_configured
211
+ @pytest.mark.parametrize("library", ["cupy", "torch", "cupy.array_api"])
212
+ def test_convert_to_numpy_gpu(library): # pragma: nocover
213
+ """Check convert_to_numpy for GPU backed libraries."""
214
+ xp = pytest.importorskip(library)
215
+
216
+ if library == "torch":
217
+ if not xp.backends.cuda.is_built():
218
+ pytest.skip("test requires cuda")
219
+ X_gpu = xp.asarray([1.0, 2.0, 3.0], device="cuda")
220
+ else:
221
+ X_gpu = xp.asarray([1.0, 2.0, 3.0])
222
+
223
+ X_cpu = _convert_to_numpy(X_gpu, xp=xp)
224
+ expected_output = numpy.asarray([1.0, 2.0, 3.0])
225
+ assert_allclose(X_cpu, expected_output)
226
+
227
+
228
+ def test_convert_to_numpy_cpu():
229
+ """Check convert_to_numpy for PyTorch CPU arrays."""
230
+ torch = pytest.importorskip("torch")
231
+ X_torch = torch.asarray([1.0, 2.0, 3.0], device="cpu")
232
+
233
+ X_cpu = _convert_to_numpy(X_torch, xp=torch)
234
+ expected_output = numpy.asarray([1.0, 2.0, 3.0])
235
+ assert_allclose(X_cpu, expected_output)
236
+
237
+
238
+ class SimpleEstimator(BaseEstimator):
239
+ def fit(self, X, y=None):
240
+ self.X_ = X
241
+ self.n_features_ = X.shape[0]
242
+ return self
243
+
244
+
245
+ @skip_if_array_api_compat_not_configured
246
+ @pytest.mark.parametrize(
247
+ "array_namespace, converter",
248
+ [
249
+ ("torch", lambda array: array.cpu().numpy()),
250
+ ("numpy.array_api", lambda array: numpy.asarray(array)),
251
+ ("cupy.array_api", lambda array: array._array.get()),
252
+ ],
253
+ )
254
+ def test_convert_estimator_to_ndarray(array_namespace, converter):
255
+ """Convert estimator attributes to ndarray."""
256
+ xp = pytest.importorskip(array_namespace)
257
+
258
+ X = xp.asarray([[1.3, 4.5]])
259
+ est = SimpleEstimator().fit(X)
260
+
261
+ new_est = _estimator_with_converted_arrays(est, converter)
262
+ assert isinstance(new_est.X_, numpy.ndarray)
263
+
264
+
265
+ @skip_if_array_api_compat_not_configured
266
+ def test_convert_estimator_to_array_api():
267
+ """Convert estimator attributes to ArrayAPI arrays."""
268
+ xp = pytest.importorskip("numpy.array_api")
269
+
270
+ X_np = numpy.asarray([[1.3, 4.5]])
271
+ est = SimpleEstimator().fit(X_np)
272
+
273
+ new_est = _estimator_with_converted_arrays(est, lambda array: xp.asarray(array))
274
+ assert hasattr(new_est.X_, "__array_namespace__")
275
+
276
+
277
+ def test_reshape_behavior():
278
+ """Check reshape behavior with copy and is strict with non-tuple shape."""
279
+ xp = _NumPyAPIWrapper()
280
+ X = xp.asarray([[1, 2, 3], [3, 4, 5]])
281
+
282
+ X_no_copy = xp.reshape(X, (-1,), copy=False)
283
+ assert X_no_copy.base is X
284
+
285
+ X_copy = xp.reshape(X, (6, 1), copy=True)
286
+ assert X_copy.base is not X.base
287
+
288
+ with pytest.raises(TypeError, match="shape must be a tuple"):
289
+ xp.reshape(X, -1)
290
+
291
+
292
+ @pytest.mark.parametrize("wrapper", [_ArrayAPIWrapper, _NumPyAPIWrapper])
293
+ def test_get_namespace_array_api_isdtype(wrapper):
294
+ """Test isdtype implementation from _ArrayAPIWrapper and _NumPyAPIWrapper."""
295
+
296
+ if wrapper == _ArrayAPIWrapper:
297
+ xp_ = pytest.importorskip("numpy.array_api")
298
+ xp = _ArrayAPIWrapper(xp_)
299
+ else:
300
+ xp = _NumPyAPIWrapper()
301
+
302
+ assert xp.isdtype(xp.float32, xp.float32)
303
+ assert xp.isdtype(xp.float32, "real floating")
304
+ assert xp.isdtype(xp.float64, "real floating")
305
+ assert not xp.isdtype(xp.int32, "real floating")
306
+
307
+ for dtype in supported_float_dtypes(xp):
308
+ assert xp.isdtype(dtype, "real floating")
309
+
310
+ assert xp.isdtype(xp.bool, "bool")
311
+ assert not xp.isdtype(xp.float32, "bool")
312
+
313
+ assert xp.isdtype(xp.int16, "signed integer")
314
+ assert not xp.isdtype(xp.uint32, "signed integer")
315
+
316
+ assert xp.isdtype(xp.uint16, "unsigned integer")
317
+ assert not xp.isdtype(xp.int64, "unsigned integer")
318
+
319
+ assert xp.isdtype(xp.int64, "numeric")
320
+ assert xp.isdtype(xp.float32, "numeric")
321
+ assert xp.isdtype(xp.uint32, "numeric")
322
+
323
+ assert not xp.isdtype(xp.float32, "complex floating")
324
+
325
+ if wrapper == _NumPyAPIWrapper:
326
+ assert not xp.isdtype(xp.int8, "complex floating")
327
+ assert xp.isdtype(xp.complex64, "complex floating")
328
+ assert xp.isdtype(xp.complex128, "complex floating")
329
+
330
+ with pytest.raises(ValueError, match="Unrecognized data type"):
331
+ assert xp.isdtype(xp.int16, "unknown")
venv/lib/python3.10/site-packages/sklearn/utils/tests/test_arrayfuncs.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from sklearn.utils._testing import assert_allclose
5
+ from sklearn.utils.arrayfuncs import _all_with_any_reduction_axis_1, min_pos
6
+
7
+
8
+ def test_min_pos():
9
+ # Check that min_pos returns a positive value and that it's consistent
10
+ # between float and double
11
+ X = np.random.RandomState(0).randn(100)
12
+
13
+ min_double = min_pos(X)
14
+ min_float = min_pos(X.astype(np.float32))
15
+
16
+ assert_allclose(min_double, min_float)
17
+ assert min_double >= 0
18
+
19
+
20
+ @pytest.mark.parametrize("dtype", [np.float32, np.float64])
21
+ def test_min_pos_no_positive(dtype):
22
+ # Check that the return value of min_pos is the maximum representable
23
+ # value of the input dtype when all input elements are <= 0 (#19328)
24
+ X = np.full(100, -1.0).astype(dtype, copy=False)
25
+
26
+ assert min_pos(X) == np.finfo(dtype).max
27
+
28
+
29
+ @pytest.mark.parametrize("dtype", [np.int16, np.int32, np.float32, np.float64])
30
+ @pytest.mark.parametrize("value", [0, 1.5, -1])
31
+ def test_all_with_any_reduction_axis_1(dtype, value):
32
+ # Check that return value is False when there is no row equal to `value`
33
+ X = np.arange(12, dtype=dtype).reshape(3, 4)
34
+ assert not _all_with_any_reduction_axis_1(X, value=value)
35
+
36
+ # Make a row equal to `value`
37
+ X[1, :] = value
38
+ assert _all_with_any_reduction_axis_1(X, value=value)
venv/lib/python3.10/site-packages/sklearn/utils/tests/test_bunch.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from sklearn.utils import Bunch
7
+
8
+
9
+ def test_bunch_attribute_deprecation():
10
+ """Check that bunch raises deprecation message with `__getattr__`."""
11
+ bunch = Bunch()
12
+ values = np.asarray([1, 2, 3])
13
+ msg = (
14
+ "Key: 'values', is deprecated in 1.3 and will be "
15
+ "removed in 1.5. Please use 'grid_values' instead"
16
+ )
17
+ bunch._set_deprecated(
18
+ values, new_key="grid_values", deprecated_key="values", warning_message=msg
19
+ )
20
+
21
+ with warnings.catch_warnings():
22
+ # Does not warn for "grid_values"
23
+ warnings.simplefilter("error")
24
+ v = bunch["grid_values"]
25
+
26
+ assert v is values
27
+
28
+ with pytest.warns(FutureWarning, match=msg):
29
+ # Warns for "values"
30
+ v = bunch["values"]
31
+
32
+ assert v is values
venv/lib/python3.10/site-packages/sklearn/utils/tests/test_class_weight.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+ from numpy.testing import assert_allclose
4
+
5
+ from sklearn.datasets import make_blobs
6
+ from sklearn.linear_model import LogisticRegression
7
+ from sklearn.tree import DecisionTreeClassifier
8
+ from sklearn.utils._testing import assert_almost_equal, assert_array_almost_equal
9
+ from sklearn.utils.class_weight import compute_class_weight, compute_sample_weight
10
+ from sklearn.utils.fixes import CSC_CONTAINERS
11
+
12
+
13
+ def test_compute_class_weight():
14
+ # Test (and demo) compute_class_weight.
15
+ y = np.asarray([2, 2, 2, 3, 3, 4])
16
+ classes = np.unique(y)
17
+
18
+ cw = compute_class_weight("balanced", classes=classes, y=y)
19
+ # total effect of samples is preserved
20
+ class_counts = np.bincount(y)[2:]
21
+ assert_almost_equal(np.dot(cw, class_counts), y.shape[0])
22
+ assert cw[0] < cw[1] < cw[2]
23
+
24
+
25
+ @pytest.mark.parametrize(
26
+ "y_type, class_weight, classes, err_msg",
27
+ [
28
+ (
29
+ "numeric",
30
+ "balanced",
31
+ np.arange(4),
32
+ "classes should have valid labels that are in y",
33
+ ),
34
+ # Non-regression for https://github.com/scikit-learn/scikit-learn/issues/8312
35
+ (
36
+ "numeric",
37
+ {"label_not_present": 1.0},
38
+ np.arange(4),
39
+ r"The classes, \[0, 1, 2, 3\], are not in class_weight",
40
+ ),
41
+ (
42
+ "numeric",
43
+ "balanced",
44
+ np.arange(2),
45
+ "classes should include all valid labels",
46
+ ),
47
+ (
48
+ "numeric",
49
+ {0: 1.0, 1: 2.0},
50
+ np.arange(2),
51
+ "classes should include all valid labels",
52
+ ),
53
+ (
54
+ "string",
55
+ {"dogs": 3, "cat": 2},
56
+ np.array(["dog", "cat"]),
57
+ r"The classes, \['dog'\], are not in class_weight",
58
+ ),
59
+ ],
60
+ )
61
+ def test_compute_class_weight_not_present(y_type, class_weight, classes, err_msg):
62
+ # Raise error when y does not contain all class labels
63
+ y = (
64
+ np.asarray([0, 0, 0, 1, 1, 2])
65
+ if y_type == "numeric"
66
+ else np.asarray(["dog", "cat", "dog"])
67
+ )
68
+
69
+ print(y)
70
+ with pytest.raises(ValueError, match=err_msg):
71
+ compute_class_weight(class_weight, classes=classes, y=y)
72
+
73
+
74
+ def test_compute_class_weight_dict():
75
+ classes = np.arange(3)
76
+ class_weights = {0: 1.0, 1: 2.0, 2: 3.0}
77
+ y = np.asarray([0, 0, 1, 2])
78
+ cw = compute_class_weight(class_weights, classes=classes, y=y)
79
+
80
+ # When the user specifies class weights, compute_class_weights should just
81
+ # return them.
82
+ assert_array_almost_equal(np.asarray([1.0, 2.0, 3.0]), cw)
83
+
84
+ # When a class weight is specified that isn't in classes, the weight is ignored
85
+ class_weights = {0: 1.0, 1: 2.0, 2: 3.0, 4: 1.5}
86
+ cw = compute_class_weight(class_weights, classes=classes, y=y)
87
+ assert_allclose([1.0, 2.0, 3.0], cw)
88
+
89
+ class_weights = {-1: 5.0, 0: 4.0, 1: 2.0, 2: 3.0}
90
+ cw = compute_class_weight(class_weights, classes=classes, y=y)
91
+ assert_allclose([4.0, 2.0, 3.0], cw)
92
+
93
+
94
+ def test_compute_class_weight_invariance():
95
+ # Test that results with class_weight="balanced" is invariant wrt
96
+ # class imbalance if the number of samples is identical.
97
+ # The test uses a balanced two class dataset with 100 datapoints.
98
+ # It creates three versions, one where class 1 is duplicated
99
+ # resulting in 150 points of class 1 and 50 of class 0,
100
+ # one where there are 50 points in class 1 and 150 in class 0,
101
+ # and one where there are 100 points of each class (this one is balanced
102
+ # again).
103
+ # With balancing class weights, all three should give the same model.
104
+ X, y = make_blobs(centers=2, random_state=0)
105
+ # create dataset where class 1 is duplicated twice
106
+ X_1 = np.vstack([X] + [X[y == 1]] * 2)
107
+ y_1 = np.hstack([y] + [y[y == 1]] * 2)
108
+ # create dataset where class 0 is duplicated twice
109
+ X_0 = np.vstack([X] + [X[y == 0]] * 2)
110
+ y_0 = np.hstack([y] + [y[y == 0]] * 2)
111
+ # duplicate everything
112
+ X_ = np.vstack([X] * 2)
113
+ y_ = np.hstack([y] * 2)
114
+ # results should be identical
115
+ logreg1 = LogisticRegression(class_weight="balanced").fit(X_1, y_1)
116
+ logreg0 = LogisticRegression(class_weight="balanced").fit(X_0, y_0)
117
+ logreg = LogisticRegression(class_weight="balanced").fit(X_, y_)
118
+ assert_array_almost_equal(logreg1.coef_, logreg0.coef_)
119
+ assert_array_almost_equal(logreg.coef_, logreg0.coef_)
120
+
121
+
122
+ def test_compute_class_weight_balanced_negative():
123
+ # Test compute_class_weight when labels are negative
124
+ # Test with balanced class labels.
125
+ classes = np.array([-2, -1, 0])
126
+ y = np.asarray([-1, -1, 0, 0, -2, -2])
127
+
128
+ cw = compute_class_weight("balanced", classes=classes, y=y)
129
+ assert len(cw) == len(classes)
130
+ assert_array_almost_equal(cw, np.array([1.0, 1.0, 1.0]))
131
+
132
+ # Test with unbalanced class labels.
133
+ y = np.asarray([-1, 0, 0, -2, -2, -2])
134
+
135
+ cw = compute_class_weight("balanced", classes=classes, y=y)
136
+ assert len(cw) == len(classes)
137
+ class_counts = np.bincount(y + 2)
138
+ assert_almost_equal(np.dot(cw, class_counts), y.shape[0])
139
+ assert_array_almost_equal(cw, [2.0 / 3, 2.0, 1.0])
140
+
141
+
142
+ def test_compute_class_weight_balanced_unordered():
143
+ # Test compute_class_weight when classes are unordered
144
+ classes = np.array([1, 0, 3])
145
+ y = np.asarray([1, 0, 0, 3, 3, 3])
146
+
147
+ cw = compute_class_weight("balanced", classes=classes, y=y)
148
+ class_counts = np.bincount(y)[classes]
149
+ assert_almost_equal(np.dot(cw, class_counts), y.shape[0])
150
+ assert_array_almost_equal(cw, [2.0, 1.0, 2.0 / 3])
151
+
152
+
153
+ def test_compute_class_weight_default():
154
+ # Test for the case where no weight is given for a present class.
155
+ # Current behaviour is to assign the unweighted classes a weight of 1.
156
+ y = np.asarray([2, 2, 2, 3, 3, 4])
157
+ classes = np.unique(y)
158
+ classes_len = len(classes)
159
+
160
+ # Test for non specified weights
161
+ cw = compute_class_weight(None, classes=classes, y=y)
162
+ assert len(cw) == classes_len
163
+ assert_array_almost_equal(cw, np.ones(3))
164
+
165
+ # Tests for partly specified weights
166
+ cw = compute_class_weight({2: 1.5}, classes=classes, y=y)
167
+ assert len(cw) == classes_len
168
+ assert_array_almost_equal(cw, [1.5, 1.0, 1.0])
169
+
170
+ cw = compute_class_weight({2: 1.5, 4: 0.5}, classes=classes, y=y)
171
+ assert len(cw) == classes_len
172
+ assert_array_almost_equal(cw, [1.5, 1.0, 0.5])
173
+
174
+
175
+ def test_compute_sample_weight():
176
+ # Test (and demo) compute_sample_weight.
177
+ # Test with balanced classes
178
+ y = np.asarray([1, 1, 1, 2, 2, 2])
179
+ sample_weight = compute_sample_weight("balanced", y)
180
+ assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
181
+
182
+ # Test with user-defined weights
183
+ sample_weight = compute_sample_weight({1: 2, 2: 1}, y)
184
+ assert_array_almost_equal(sample_weight, [2.0, 2.0, 2.0, 1.0, 1.0, 1.0])
185
+
186
+ # Test with column vector of balanced classes
187
+ y = np.asarray([[1], [1], [1], [2], [2], [2]])
188
+ sample_weight = compute_sample_weight("balanced", y)
189
+ assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
190
+
191
+ # Test with unbalanced classes
192
+ y = np.asarray([1, 1, 1, 2, 2, 2, 3])
193
+ sample_weight = compute_sample_weight("balanced", y)
194
+ expected_balanced = np.array(
195
+ [0.7777, 0.7777, 0.7777, 0.7777, 0.7777, 0.7777, 2.3333]
196
+ )
197
+ assert_array_almost_equal(sample_weight, expected_balanced, decimal=4)
198
+
199
+ # Test with `None` weights
200
+ sample_weight = compute_sample_weight(None, y)
201
+ assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
202
+
203
+ # Test with multi-output of balanced classes
204
+ y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]])
205
+ sample_weight = compute_sample_weight("balanced", y)
206
+ assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
207
+
208
+ # Test with multi-output with user-defined weights
209
+ y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]])
210
+ sample_weight = compute_sample_weight([{1: 2, 2: 1}, {0: 1, 1: 2}], y)
211
+ assert_array_almost_equal(sample_weight, [2.0, 2.0, 2.0, 2.0, 2.0, 2.0])
212
+
213
+ # Test with multi-output of unbalanced classes
214
+ y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [3, -1]])
215
+ sample_weight = compute_sample_weight("balanced", y)
216
+ assert_array_almost_equal(sample_weight, expected_balanced**2, decimal=3)
217
+
218
+
219
+ def test_compute_sample_weight_with_subsample():
220
+ # Test compute_sample_weight with subsamples specified.
221
+ # Test with balanced classes and all samples present
222
+ y = np.asarray([1, 1, 1, 2, 2, 2])
223
+ sample_weight = compute_sample_weight("balanced", y, indices=range(6))
224
+ assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
225
+
226
+ # Test with column vector of balanced classes and all samples present
227
+ y = np.asarray([[1], [1], [1], [2], [2], [2]])
228
+ sample_weight = compute_sample_weight("balanced", y, indices=range(6))
229
+ assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
230
+
231
+ # Test with a subsample
232
+ y = np.asarray([1, 1, 1, 2, 2, 2])
233
+ sample_weight = compute_sample_weight("balanced", y, indices=range(4))
234
+ assert_array_almost_equal(sample_weight, [2.0 / 3, 2.0 / 3, 2.0 / 3, 2.0, 2.0, 2.0])
235
+
236
+ # Test with a bootstrap subsample
237
+ y = np.asarray([1, 1, 1, 2, 2, 2])
238
+ sample_weight = compute_sample_weight("balanced", y, indices=[0, 1, 1, 2, 2, 3])
239
+ expected_balanced = np.asarray([0.6, 0.6, 0.6, 3.0, 3.0, 3.0])
240
+ assert_array_almost_equal(sample_weight, expected_balanced)
241
+
242
+ # Test with a bootstrap subsample for multi-output
243
+ y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]])
244
+ sample_weight = compute_sample_weight("balanced", y, indices=[0, 1, 1, 2, 2, 3])
245
+ assert_array_almost_equal(sample_weight, expected_balanced**2)
246
+
247
+ # Test with a missing class
248
+ y = np.asarray([1, 1, 1, 2, 2, 2, 3])
249
+ sample_weight = compute_sample_weight("balanced", y, indices=range(6))
250
+ assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0])
251
+
252
+ # Test with a missing class for multi-output
253
+ y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [2, 2]])
254
+ sample_weight = compute_sample_weight("balanced", y, indices=range(6))
255
+ assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0])
256
+
257
+
258
+ @pytest.mark.parametrize(
259
+ "y_type, class_weight, indices, err_msg",
260
+ [
261
+ (
262
+ "single-output",
263
+ {1: 2, 2: 1},
264
+ range(4),
265
+ "The only valid class_weight for subsampling is 'balanced'.",
266
+ ),
267
+ (
268
+ "multi-output",
269
+ {1: 2, 2: 1},
270
+ None,
271
+ "For multi-output, class_weight should be a list of dicts, or the string",
272
+ ),
273
+ (
274
+ "multi-output",
275
+ [{1: 2, 2: 1}],
276
+ None,
277
+ r"Got 1 element\(s\) while having 2 outputs",
278
+ ),
279
+ ],
280
+ )
281
+ def test_compute_sample_weight_errors(y_type, class_weight, indices, err_msg):
282
+ # Test compute_sample_weight raises errors expected.
283
+ # Invalid preset string
284
+ y_single_output = np.asarray([1, 1, 1, 2, 2, 2])
285
+ y_multi_output = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]])
286
+
287
+ y = y_single_output if y_type == "single-output" else y_multi_output
288
+ with pytest.raises(ValueError, match=err_msg):
289
+ compute_sample_weight(class_weight, y, indices=indices)
290
+
291
+
292
+ def test_compute_sample_weight_more_than_32():
293
+ # Non-regression smoke test for #12146
294
+ y = np.arange(50) # more than 32 distinct classes
295
+ indices = np.arange(50) # use subsampling
296
+ weight = compute_sample_weight("balanced", y, indices=indices)
297
+ assert_array_almost_equal(weight, np.ones(y.shape[0]))
298
+
299
+
300
+ def test_class_weight_does_not_contains_more_classes():
301
+ """Check that class_weight can contain more labels than in y.
302
+
303
+ Non-regression test for #22413
304
+ """
305
+ tree = DecisionTreeClassifier(class_weight={0: 1, 1: 10, 2: 20})
306
+
307
+ # Does not raise
308
+ tree.fit([[0, 0, 1], [1, 0, 1], [1, 2, 0]], [0, 0, 1])
309
+
310
+
311
+ @pytest.mark.parametrize("csc_container", CSC_CONTAINERS)
312
+ def test_compute_sample_weight_sparse(csc_container):
313
+ """Check that we can compute weight for sparse `y`."""
314
+ y = csc_container(np.asarray([[0], [1], [1]]))
315
+ sample_weight = compute_sample_weight("balanced", y)
316
+ assert_allclose(sample_weight, [1.5, 0.75, 0.75])