ZTWHHH commited on
Commit
a0b5c0d
·
verified ·
1 Parent(s): 20cb61e

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. .gitattributes +5 -0
  2. videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so +3 -0
  3. videollama2/lib/python3.10/site-packages/sklearn/linear_model/_sag_fast.cpython-310-x86_64-linux-gnu.so +3 -0
  4. videollama2/lib/python3.10/site-packages/sklearn/metrics/_base.py +251 -0
  5. videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__init__.py +101 -0
  6. videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py +449 -0
  7. videollama2/lib/python3.10/site-packages/sklearn/metrics/_ranking.py +1826 -0
  8. videollama2/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so +3 -0
  9. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_available_if.cpython-310.pyc +0 -0
  10. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_encode.cpython-310.pyc +0 -0
  11. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_mask.cpython-310.pyc +0 -0
  12. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_mocking.cpython-310.pyc +0 -0
  13. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_set_output.cpython-310.pyc +0 -0
  14. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_show_versions.cpython-310.pyc +0 -0
  15. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_tags.cpython-310.pyc +0 -0
  16. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_testing.cpython-310.pyc +0 -0
  17. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/deprecation.cpython-310.pyc +0 -0
  18. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/estimator_checks.cpython-310.pyc +0 -0
  19. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/extmath.cpython-310.pyc +0 -0
  20. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/fixes.cpython-310.pyc +0 -0
  21. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/graph.cpython-310.pyc +0 -0
  22. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/multiclass.cpython-310.pyc +0 -0
  23. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/optimize.cpython-310.pyc +0 -0
  24. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/stats.cpython-310.pyc +0 -0
  25. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/validation.cpython-310.pyc +0 -0
  26. videollama2/lib/python3.10/site-packages/sklearn/utils/_estimator_html_repr.py +428 -0
  27. videollama2/lib/python3.10/site-packages/sklearn/utils/_fast_dict.pxd +22 -0
  28. videollama2/lib/python3.10/site-packages/sklearn/utils/_isfinite.cpython-310-x86_64-linux-gnu.so +3 -0
  29. videollama2/lib/python3.10/site-packages/sklearn/utils/_random.pxd +39 -0
  30. videollama2/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.pxd +116 -0
  31. videollama2/lib/python3.10/site-packages/sklearn/utils/_sorting.pxd +9 -0
  32. videollama2/lib/python3.10/site-packages/sklearn/utils/_typedefs.cpython-310-x86_64-linux-gnu.so +0 -0
  33. videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so +3 -0
  34. videollama2/lib/python3.10/site-packages/sklearn/utils/deprecation.py +115 -0
  35. videollama2/lib/python3.10/site-packages/sklearn/utils/fixes.py +216 -0
  36. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  37. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/conftest.cpython-310.pyc +0 -0
  38. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_array_api.cpython-310.pyc +0 -0
  39. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_arrayfuncs.cpython-310.pyc +0 -0
  40. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_class_weight.cpython-310.pyc +0 -0
  41. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_blas.cpython-310.pyc +0 -0
  42. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_templating.cpython-310.pyc +0 -0
  43. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_deprecation.cpython-310.pyc +0 -0
  44. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_encode.cpython-310.pyc +0 -0
  45. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc +0 -0
  46. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_html_repr.cpython-310.pyc +0 -0
  47. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_fast_dict.cpython-310.pyc +0 -0
  48. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_mocking.cpython-310.pyc +0 -0
  49. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_murmurhash.cpython-310.pyc +0 -0
  50. videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -1926,3 +1926,8 @@ videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.cpython
1926
  videollama2/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1927
  parrot/lib/python3.10/site-packages/opencv_python.libs/libssl-28bef1ac.so.1.1 filter=lfs diff=lfs merge=lfs -text
1928
  parrot/lib/python3.10/site-packages/opencv_python.libs/libgfortran-91cc3cb1.so.3.0.0 filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
1926
  videollama2/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1927
  parrot/lib/python3.10/site-packages/opencv_python.libs/libssl-28bef1ac.so.1.1 filter=lfs diff=lfs merge=lfs -text
1928
  parrot/lib/python3.10/site-packages/opencv_python.libs/libgfortran-91cc3cb1.so.3.0.0 filter=lfs diff=lfs merge=lfs -text
1929
+ videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1930
+ videollama2/lib/python3.10/site-packages/sklearn/linear_model/_sag_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1931
+ videollama2/lib/python3.10/site-packages/sklearn/utils/_isfinite.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1932
+ videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1933
+ videollama2/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02427d73dd89676ee2cc95481e05e33b647a6aafeda54130d205c4560e762d5b
3
+ size 274121
videollama2/lib/python3.10/site-packages/sklearn/linear_model/_sag_fast.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0206e05f51082e3e1af0024f8321918f56819b5df690dbc159e81b081ccd9fd
3
+ size 170705
videollama2/lib/python3.10/site-packages/sklearn/metrics/_base.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Common code for all metrics.
3
+
4
+ """
5
+ # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
6
+ # Mathieu Blondel <mathieu@mblondel.org>
7
+ # Olivier Grisel <olivier.grisel@ensta.org>
8
+ # Arnaud Joly <a.joly@ulg.ac.be>
9
+ # Jochen Wersdorfer <jochen@wersdoerfer.de>
10
+ # Lars Buitinck
11
+ # Joel Nothman <joel.nothman@gmail.com>
12
+ # Noel Dawe <noel@dawe.me>
13
+ # License: BSD 3 clause
14
+
15
+ from itertools import combinations
16
+
17
+ import numpy as np
18
+
19
+ from ..utils import check_array, check_consistent_length
20
+ from ..utils.multiclass import type_of_target
21
+
22
+
23
+ def _average_binary_score(binary_metric, y_true, y_score, average, sample_weight=None):
24
+ """Average a binary metric for multilabel classification.
25
+
26
+ Parameters
27
+ ----------
28
+ y_true : array, shape = [n_samples] or [n_samples, n_classes]
29
+ True binary labels in binary label indicators.
30
+
31
+ y_score : array, shape = [n_samples] or [n_samples, n_classes]
32
+ Target scores, can either be probability estimates of the positive
33
+ class, confidence values, or binary decisions.
34
+
35
+ average : {None, 'micro', 'macro', 'samples', 'weighted'}, default='macro'
36
+ If ``None``, the scores for each class are returned. Otherwise,
37
+ this determines the type of averaging performed on the data:
38
+
39
+ ``'micro'``:
40
+ Calculate metrics globally by considering each element of the label
41
+ indicator matrix as a label.
42
+ ``'macro'``:
43
+ Calculate metrics for each label, and find their unweighted
44
+ mean. This does not take label imbalance into account.
45
+ ``'weighted'``:
46
+ Calculate metrics for each label, and find their average, weighted
47
+ by support (the number of true instances for each label).
48
+ ``'samples'``:
49
+ Calculate metrics for each instance, and find their average.
50
+
51
+ Will be ignored when ``y_true`` is binary.
52
+
53
+ sample_weight : array-like of shape (n_samples,), default=None
54
+ Sample weights.
55
+
56
+ binary_metric : callable, returns shape [n_classes]
57
+ The binary metric function to use.
58
+
59
+ Returns
60
+ -------
61
+ score : float or array of shape [n_classes]
62
+ If not ``None``, average the score, else return the score for each
63
+ classes.
64
+
65
+ """
66
+ average_options = (None, "micro", "macro", "weighted", "samples")
67
+ if average not in average_options:
68
+ raise ValueError("average has to be one of {0}".format(average_options))
69
+
70
+ y_type = type_of_target(y_true)
71
+ if y_type not in ("binary", "multilabel-indicator"):
72
+ raise ValueError("{0} format is not supported".format(y_type))
73
+
74
+ if y_type == "binary":
75
+ return binary_metric(y_true, y_score, sample_weight=sample_weight)
76
+
77
+ check_consistent_length(y_true, y_score, sample_weight)
78
+ y_true = check_array(y_true)
79
+ y_score = check_array(y_score)
80
+
81
+ not_average_axis = 1
82
+ score_weight = sample_weight
83
+ average_weight = None
84
+
85
+ if average == "micro":
86
+ if score_weight is not None:
87
+ score_weight = np.repeat(score_weight, y_true.shape[1])
88
+ y_true = y_true.ravel()
89
+ y_score = y_score.ravel()
90
+
91
+ elif average == "weighted":
92
+ if score_weight is not None:
93
+ average_weight = np.sum(
94
+ np.multiply(y_true, np.reshape(score_weight, (-1, 1))), axis=0
95
+ )
96
+ else:
97
+ average_weight = np.sum(y_true, axis=0)
98
+ if np.isclose(average_weight.sum(), 0.0):
99
+ return 0
100
+
101
+ elif average == "samples":
102
+ # swap average_weight <-> score_weight
103
+ average_weight = score_weight
104
+ score_weight = None
105
+ not_average_axis = 0
106
+
107
+ if y_true.ndim == 1:
108
+ y_true = y_true.reshape((-1, 1))
109
+
110
+ if y_score.ndim == 1:
111
+ y_score = y_score.reshape((-1, 1))
112
+
113
+ n_classes = y_score.shape[not_average_axis]
114
+ score = np.zeros((n_classes,))
115
+ for c in range(n_classes):
116
+ y_true_c = y_true.take([c], axis=not_average_axis).ravel()
117
+ y_score_c = y_score.take([c], axis=not_average_axis).ravel()
118
+ score[c] = binary_metric(y_true_c, y_score_c, sample_weight=score_weight)
119
+
120
+ # Average the results
121
+ if average is not None:
122
+ if average_weight is not None:
123
+ # Scores with 0 weights are forced to be 0, preventing the average
124
+ # score from being affected by 0-weighted NaN elements.
125
+ average_weight = np.asarray(average_weight)
126
+ score[average_weight == 0] = 0
127
+ return np.average(score, weights=average_weight)
128
+ else:
129
+ return score
130
+
131
+
132
+ def _average_multiclass_ovo_score(binary_metric, y_true, y_score, average="macro"):
133
+ """Average one-versus-one scores for multiclass classification.
134
+
135
+ Uses the binary metric for one-vs-one multiclass classification,
136
+ where the score is computed according to the Hand & Till (2001) algorithm.
137
+
138
+ Parameters
139
+ ----------
140
+ binary_metric : callable
141
+ The binary metric function to use that accepts the following as input:
142
+ y_true_target : array, shape = [n_samples_target]
143
+ Some sub-array of y_true for a pair of classes designated
144
+ positive and negative in the one-vs-one scheme.
145
+ y_score_target : array, shape = [n_samples_target]
146
+ Scores corresponding to the probability estimates
147
+ of a sample belonging to the designated positive class label
148
+
149
+ y_true : array-like of shape (n_samples,)
150
+ True multiclass labels.
151
+
152
+ y_score : array-like of shape (n_samples, n_classes)
153
+ Target scores corresponding to probability estimates of a sample
154
+ belonging to a particular class.
155
+
156
+ average : {'macro', 'weighted'}, default='macro'
157
+ Determines the type of averaging performed on the pairwise binary
158
+ metric scores:
159
+ ``'macro'``:
160
+ Calculate metrics for each label, and find their unweighted
161
+ mean. This does not take label imbalance into account. Classes
162
+ are assumed to be uniformly distributed.
163
+ ``'weighted'``:
164
+ Calculate metrics for each label, taking into account the
165
+ prevalence of the classes.
166
+
167
+ Returns
168
+ -------
169
+ score : float
170
+ Average of the pairwise binary metric scores.
171
+ """
172
+ check_consistent_length(y_true, y_score)
173
+
174
+ y_true_unique = np.unique(y_true)
175
+ n_classes = y_true_unique.shape[0]
176
+ n_pairs = n_classes * (n_classes - 1) // 2
177
+ pair_scores = np.empty(n_pairs)
178
+
179
+ is_weighted = average == "weighted"
180
+ prevalence = np.empty(n_pairs) if is_weighted else None
181
+
182
+ # Compute scores treating a as positive class and b as negative class,
183
+ # then b as positive class and a as negative class
184
+ for ix, (a, b) in enumerate(combinations(y_true_unique, 2)):
185
+ a_mask = y_true == a
186
+ b_mask = y_true == b
187
+ ab_mask = np.logical_or(a_mask, b_mask)
188
+
189
+ if is_weighted:
190
+ prevalence[ix] = np.average(ab_mask)
191
+
192
+ a_true = a_mask[ab_mask]
193
+ b_true = b_mask[ab_mask]
194
+
195
+ a_true_score = binary_metric(a_true, y_score[ab_mask, a])
196
+ b_true_score = binary_metric(b_true, y_score[ab_mask, b])
197
+ pair_scores[ix] = (a_true_score + b_true_score) / 2
198
+
199
+ return np.average(pair_scores, weights=prevalence)
200
+
201
+
202
+ def _check_pos_label_consistency(pos_label, y_true):
203
+ """Check if `pos_label` need to be specified or not.
204
+
205
+ In binary classification, we fix `pos_label=1` if the labels are in the set
206
+ {-1, 1} or {0, 1}. Otherwise, we raise an error asking to specify the
207
+ `pos_label` parameters.
208
+
209
+ Parameters
210
+ ----------
211
+ pos_label : int, str or None
212
+ The positive label.
213
+ y_true : ndarray of shape (n_samples,)
214
+ The target vector.
215
+
216
+ Returns
217
+ -------
218
+ pos_label : int
219
+ If `pos_label` can be inferred, it will be returned.
220
+
221
+ Raises
222
+ ------
223
+ ValueError
224
+ In the case that `y_true` does not have label in {-1, 1} or {0, 1},
225
+ it will raise a `ValueError`.
226
+ """
227
+ # ensure binary classification if pos_label is not specified
228
+ # classes.dtype.kind in ('O', 'U', 'S') is required to avoid
229
+ # triggering a FutureWarning by calling np.array_equal(a, b)
230
+ # when elements in the two arrays are not comparable.
231
+ classes = np.unique(y_true)
232
+ if pos_label is None and (
233
+ classes.dtype.kind in "OUS"
234
+ or not (
235
+ np.array_equal(classes, [0, 1])
236
+ or np.array_equal(classes, [-1, 1])
237
+ or np.array_equal(classes, [0])
238
+ or np.array_equal(classes, [-1])
239
+ or np.array_equal(classes, [1])
240
+ )
241
+ ):
242
+ classes_repr = ", ".join(repr(c) for c in classes)
243
+ raise ValueError(
244
+ f"y_true takes value in {{{classes_repr}}} and pos_label is not "
245
+ "specified: either make y_true take value in {0, 1} or "
246
+ "{-1, 1} or pass pos_label explicitly."
247
+ )
248
+ elif pos_label is None:
249
+ pos_label = 1
250
+
251
+ return pos_label
videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__init__.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pairwise Distances Reductions
2
+ # =============================
3
+ #
4
+ # Author: Julien Jerphanion <git@jjerphan.xyz>
5
+ #
6
+ # Overview
7
+ # --------
8
+ #
9
+ # This module provides routines to compute pairwise distances between a set
10
+ # of row vectors of X and another set of row vectors of Y and apply a
11
+ # reduction on top. The canonical example is the brute-force computation
12
+ # of the top k nearest neighbors by leveraging the arg-k-min reduction.
13
+ #
14
+ # The reduction takes a matrix of pairwise distances between rows of X and Y
15
+ # as input and outputs an aggregate data-structure for each row of X. The
16
+ # aggregate values are typically smaller than the number of rows in Y, hence
17
+ # the term reduction.
18
+ #
19
+ # For computational reasons, the reduction are performed on the fly on chunks
20
+ # of rows of X and Y so as to keep intermediate data-structures in CPU cache
21
+ # and avoid unnecessary round trips of large distance arrays with the RAM
22
+ # that would otherwise severely degrade the speed by making the overall
23
+ # processing memory-bound.
24
+ #
25
+ # Finally, the routines follow a generic parallelization template to process
26
+ # chunks of data with OpenMP loops (via Cython prange), either on rows of X
27
+ # or rows of Y depending on their respective sizes.
28
+ #
29
+ #
30
+ # Dispatching to specialized implementations
31
+ # ------------------------------------------
32
+ #
33
+ # Dispatchers are meant to be used in the Python code. Under the hood, a
34
+ # dispatcher must only define the logic to choose at runtime to the correct
35
+ # dtype-specialized :class:`BaseDistancesReductionDispatcher` implementation based
36
+ # on the dtype of X and of Y.
37
+ #
38
+ #
39
+ # High-level diagram
40
+ # ------------------
41
+ #
42
+ # Legend:
43
+ #
44
+ # A ---⊳ B: A inherits from B
45
+ # A ---x B: A dispatches to B
46
+ #
47
+ #
48
+ # (base dispatcher)
49
+ # BaseDistancesReductionDispatcher
50
+ # ∆
51
+ # |
52
+ # |
53
+ # +-----------------------+----------------------+
54
+ # | |
55
+ # (dispatcher) (dispatcher)
56
+ # ArgKmin RadiusNeighbors
57
+ # | |
58
+ # | |
59
+ # | (float{32,64} implem.) |
60
+ # | BaseDistancesReduction{32,64} |
61
+ # | ∆ |
62
+ # | | |
63
+ # | | |
64
+ # | +-----------------+-----------------+ |
65
+ # | | | |
66
+ # | | | |
67
+ # x | | x
68
+ # ArgKmin{32,64} RadiusNeighbors{32,64}
69
+ # | ∆ ∆ |
70
+ # | | | |
71
+ # ======================= Specializations =============================
72
+ # | | | |
73
+ # | | | |
74
+ # x | | x
75
+ # EuclideanArgKmin{32,64} EuclideanRadiusNeighbors{32,64}
76
+ #
77
+ # For instance :class:`ArgKmin` dispatches to:
78
+ # - :class:`ArgKmin64` if X and Y are two `float64` array-likes
79
+ # - :class:`ArgKmin32` if X and Y are two `float32` array-likes
80
+ #
81
+ # In addition, if the metric parameter is set to "euclidean" or "sqeuclidean",
82
+ # then `ArgKmin{32,64}` further dispatches to `EuclideanArgKmin{32,64}`. For
83
+ # example, :class:`ArgKmin64` would dispatch to :class:`EuclideanArgKmin64`, a
84
+ # specialized subclass that optimally handles the Euclidean distance case
85
+ # using Generalized Matrix Multiplication over `float64` data (see the
86
+ # docstring of :class:`GEMMTermComputer64` for details).
87
+
88
+
89
+ from ._dispatcher import (
90
+ BaseDistancesReductionDispatcher,
91
+ ArgKmin,
92
+ RadiusNeighbors,
93
+ sqeuclidean_row_norms,
94
+ )
95
+
96
+ __all__ = [
97
+ "BaseDistancesReductionDispatcher",
98
+ "ArgKmin",
99
+ "RadiusNeighbors",
100
+ "sqeuclidean_row_norms",
101
+ ]
videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+
3
+ import numpy as np
4
+
5
+ from typing import List
6
+
7
+ from scipy.sparse import isspmatrix_csr
8
+
9
+ from .._dist_metrics import BOOL_METRICS, METRIC_MAPPING
10
+
11
+ from ._base import _sqeuclidean_row_norms32, _sqeuclidean_row_norms64
12
+ from ._argkmin import (
13
+ ArgKmin64,
14
+ ArgKmin32,
15
+ )
16
+ from ._radius_neighbors import (
17
+ RadiusNeighbors64,
18
+ RadiusNeighbors32,
19
+ )
20
+
21
+ from ... import get_config
22
+
23
+
24
+ def sqeuclidean_row_norms(X, num_threads):
25
+ """Compute the squared euclidean norm of the rows of X in parallel.
26
+
27
+ Parameters
28
+ ----------
29
+ X : ndarray or CSR matrix of shape (n_samples, n_features)
30
+ Input data. Must be c-contiguous.
31
+
32
+ num_threads : int
33
+ The number of OpenMP threads to use.
34
+
35
+ Returns
36
+ -------
37
+ sqeuclidean_row_norms : ndarray of shape (n_samples,)
38
+ Arrays containing the squared euclidean norm of each row of X.
39
+ """
40
+ if X.dtype == np.float64:
41
+ return np.asarray(_sqeuclidean_row_norms64(X, num_threads))
42
+ if X.dtype == np.float32:
43
+ return np.asarray(_sqeuclidean_row_norms32(X, num_threads))
44
+
45
+ raise ValueError(
46
+ "Only float64 or float32 datasets are supported at this time, "
47
+ f"got: X.dtype={X.dtype}."
48
+ )
49
+
50
+
51
+ class BaseDistancesReductionDispatcher:
52
+ """Abstract base dispatcher for pairwise distance computation & reduction.
53
+
54
+ Each dispatcher extending the base :class:`BaseDistancesReductionDispatcher`
55
+ dispatcher must implement the :meth:`compute` classmethod.
56
+ """
57
+
58
+ @classmethod
59
+ def valid_metrics(cls) -> List[str]:
60
+ excluded = {
61
+ # PyFunc cannot be supported because it necessitates interacting with
62
+ # the CPython interpreter to call user defined functions.
63
+ "pyfunc",
64
+ "mahalanobis", # is numerically unstable
65
+ # In order to support discrete distance metrics, we need to have a
66
+ # stable simultaneous sort which preserves the order of the indices
67
+ # because there generally is a lot of occurrences for a given values
68
+ # of distances in this case.
69
+ # TODO: implement a stable simultaneous_sort.
70
+ "hamming",
71
+ *BOOL_METRICS,
72
+ }
73
+ return sorted(({"sqeuclidean"} | set(METRIC_MAPPING.keys())) - excluded)
74
+
75
+ @classmethod
76
+ def is_usable_for(cls, X, Y, metric) -> bool:
77
+ """Return True if the dispatcher can be used for the
78
+ given parameters.
79
+
80
+ Parameters
81
+ ----------
82
+ X : {ndarray, sparse matrix} of shape (n_samples_X, n_features)
83
+ Input data.
84
+
85
+ Y : {ndarray, sparse matrix} of shape (n_samples_Y, n_features)
86
+ Input data.
87
+
88
+ metric : str, default='euclidean'
89
+ The distance metric to use.
90
+ For a list of available metrics, see the documentation of
91
+ :class:`~sklearn.metrics.DistanceMetric`.
92
+
93
+ Returns
94
+ -------
95
+ True if the dispatcher can be used, else False.
96
+ """
97
+
98
+ def is_numpy_c_ordered(X):
99
+ return hasattr(X, "flags") and X.flags.c_contiguous
100
+
101
+ def is_valid_sparse_matrix(X):
102
+ return (
103
+ isspmatrix_csr(X)
104
+ and
105
+ # TODO: support CSR matrices without non-zeros elements
106
+ X.nnz > 0
107
+ and
108
+ # TODO: support CSR matrices with int64 indices and indptr
109
+ # See: https://github.com/scikit-learn/scikit-learn/issues/23653
110
+ X.indices.dtype == X.indptr.dtype == np.int32
111
+ )
112
+
113
+ is_usable = (
114
+ get_config().get("enable_cython_pairwise_dist", True)
115
+ and (is_numpy_c_ordered(X) or is_valid_sparse_matrix(X))
116
+ and (is_numpy_c_ordered(Y) or is_valid_sparse_matrix(Y))
117
+ and X.dtype == Y.dtype
118
+ and X.dtype in (np.float32, np.float64)
119
+ and metric in cls.valid_metrics()
120
+ )
121
+
122
+ # The other joblib-based back-end might be more efficient on fused sparse-dense
123
+ # datasets' pairs on metric="(sq)euclidean" for some configurations because it
124
+ # uses the Squared Euclidean matrix decomposition, i.e.:
125
+ #
126
+ # ||X_c_i - Y_c_j||² = ||X_c_i||² - 2 X_c_i.Y_c_j^T + ||Y_c_j||²
127
+ #
128
+ # calling efficient sparse-dense routines for matrix and vectors multiplication
129
+ # implemented in SciPy we do not use yet here.
130
+ # See: https://github.com/scikit-learn/scikit-learn/pull/23585#issuecomment-1247996669 # noqa
131
+ # TODO: implement specialisation for (sq)euclidean on fused sparse-dense
132
+ # using sparse-dense routines for matrix-vector multiplications.
133
+ # Currently, only dense-dense and sparse-sparse are optimized for
134
+ # the Euclidean case.
135
+ fused_sparse_dense_euclidean_case_guard = not (
136
+ (is_valid_sparse_matrix(X) ^ is_valid_sparse_matrix(Y)) # "^" is XOR
137
+ and isinstance(metric, str)
138
+ and "euclidean" in metric
139
+ )
140
+
141
+ return is_usable and fused_sparse_dense_euclidean_case_guard
142
+
143
+ @classmethod
144
+ @abstractmethod
145
+ def compute(
146
+ cls,
147
+ X,
148
+ Y,
149
+ **kwargs,
150
+ ):
151
+ """Compute the reduction.
152
+
153
+ Parameters
154
+ ----------
155
+ X : ndarray or CSR matrix of shape (n_samples_X, n_features)
156
+ Input data.
157
+
158
+ Y : ndarray or CSR matrix of shape (n_samples_Y, n_features)
159
+ Input data.
160
+
161
+ **kwargs : additional parameters for the reduction
162
+
163
+ Notes
164
+ -----
165
+ This method is an abstract class method: it has to be implemented
166
+ for all subclasses.
167
+ """
168
+
169
+
170
+ class ArgKmin(BaseDistancesReductionDispatcher):
171
+ """Compute the argkmin of row vectors of X on the ones of Y.
172
+
173
+ For each row vector of X, computes the indices of k first the rows
174
+ vectors of Y with the smallest distances.
175
+
176
+ ArgKmin is typically used to perform
177
+ bruteforce k-nearest neighbors queries.
178
+
179
+ This class is not meant to be instanciated, one should only use
180
+ its :meth:`compute` classmethod which handles allocation and
181
+ deallocation consistently.
182
+ """
183
+
184
+ @classmethod
185
+ def compute(
186
+ cls,
187
+ X,
188
+ Y,
189
+ k,
190
+ metric="euclidean",
191
+ chunk_size=None,
192
+ metric_kwargs=None,
193
+ strategy=None,
194
+ return_distance=False,
195
+ ):
196
+ """Compute the argkmin reduction.
197
+
198
+ Parameters
199
+ ----------
200
+ X : ndarray or CSR matrix of shape (n_samples_X, n_features)
201
+ Input data.
202
+
203
+ Y : ndarray or CSR matrix of shape (n_samples_Y, n_features)
204
+ Input data.
205
+
206
+ k : int
207
+ The k for the argkmin reduction.
208
+
209
+ metric : str, default='euclidean'
210
+ The distance metric to use for argkmin.
211
+ For a list of available metrics, see the documentation of
212
+ :class:`~sklearn.metrics.DistanceMetric`.
213
+
214
+ chunk_size : int, default=None,
215
+ The number of vectors per chunk. If None (default) looks-up in
216
+ scikit-learn configuration for `pairwise_dist_chunk_size`,
217
+ and use 256 if it is not set.
218
+
219
+ metric_kwargs : dict, default=None
220
+ Keyword arguments to pass to specified metric function.
221
+
222
+ strategy : str, {'auto', 'parallel_on_X', 'parallel_on_Y'}, default=None
223
+ The chunking strategy defining which dataset parallelization are made on.
224
+
225
+ For both strategies the computations happens with two nested loops,
226
+ respectively on chunks of X and chunks of Y.
227
+ Strategies differs on which loop (outer or inner) is made to run
228
+ in parallel with the Cython `prange` construct:
229
+
230
+ - 'parallel_on_X' dispatches chunks of X uniformly on threads.
231
+ Each thread then iterates on all the chunks of Y. This strategy is
232
+ embarrassingly parallel and comes with no datastructures
233
+ synchronisation.
234
+
235
+ - 'parallel_on_Y' dispatches chunks of Y uniformly on threads.
236
+ Each thread processes all the chunks of X in turn. This strategy is
237
+ a sequence of embarrassingly parallel subtasks (the inner loop on Y
238
+ chunks) with intermediate datastructures synchronisation at each
239
+ iteration of the sequential outer loop on X chunks.
240
+
241
+ - 'auto' relies on a simple heuristic to choose between
242
+ 'parallel_on_X' and 'parallel_on_Y': when `X.shape[0]` is large enough,
243
+ 'parallel_on_X' is usually the most efficient strategy.
244
+ When `X.shape[0]` is small but `Y.shape[0]` is large, 'parallel_on_Y'
245
+ brings more opportunity for parallelism and is therefore more efficient
246
+
247
+ - None (default) looks-up in scikit-learn configuration for
248
+ `pairwise_dist_parallel_strategy`, and use 'auto' if it is not set.
249
+
250
+ return_distance : boolean, default=False
251
+ Return distances between each X vector and its
252
+ argkmin if set to True.
253
+
254
+ Returns
255
+ -------
256
+ If return_distance=False:
257
+ - argkmin_indices : ndarray of shape (n_samples_X, k)
258
+ Indices of the argkmin for each vector in X.
259
+
260
+ If return_distance=True:
261
+ - argkmin_distances : ndarray of shape (n_samples_X, k)
262
+ Distances to the argkmin for each vector in X.
263
+ - argkmin_indices : ndarray of shape (n_samples_X, k)
264
+ Indices of the argkmin for each vector in X.
265
+
266
+ Notes
267
+ -----
268
+ This classmethod inspects the arguments values to dispatch to the
269
+ dtype-specialized implementation of :class:`ArgKmin`.
270
+
271
+ This allows decoupling the API entirely from the implementation details
272
+ whilst maintaining RAII: all temporarily allocated datastructures necessary
273
+ for the concrete implementation are therefore freed when this classmethod
274
+ returns.
275
+ """
276
+ if X.dtype == Y.dtype == np.float64:
277
+ return ArgKmin64.compute(
278
+ X=X,
279
+ Y=Y,
280
+ k=k,
281
+ metric=metric,
282
+ chunk_size=chunk_size,
283
+ metric_kwargs=metric_kwargs,
284
+ strategy=strategy,
285
+ return_distance=return_distance,
286
+ )
287
+
288
+ if X.dtype == Y.dtype == np.float32:
289
+ return ArgKmin32.compute(
290
+ X=X,
291
+ Y=Y,
292
+ k=k,
293
+ metric=metric,
294
+ chunk_size=chunk_size,
295
+ metric_kwargs=metric_kwargs,
296
+ strategy=strategy,
297
+ return_distance=return_distance,
298
+ )
299
+
300
+ raise ValueError(
301
+ "Only float64 or float32 datasets pairs are supported at this time, "
302
+ f"got: X.dtype={X.dtype} and Y.dtype={Y.dtype}."
303
+ )
304
+
305
+
306
+ class RadiusNeighbors(BaseDistancesReductionDispatcher):
307
+ """Compute radius-based neighbors for two sets of vectors.
308
+
309
+ For each row-vector X[i] of the queries X, find all the indices j of
310
+ row-vectors in Y such that:
311
+
312
+ dist(X[i], Y[j]) <= radius
313
+
314
+ The distance function `dist` depends on the values of the `metric`
315
+ and `metric_kwargs` parameters.
316
+
317
+ This class is not meant to be instanciated, one should only use
318
+ its :meth:`compute` classmethod which handles allocation and
319
+ deallocation consistently.
320
+ """
321
+
322
+ @classmethod
323
+ def compute(
324
+ cls,
325
+ X,
326
+ Y,
327
+ radius,
328
+ metric="euclidean",
329
+ chunk_size=None,
330
+ metric_kwargs=None,
331
+ strategy=None,
332
+ return_distance=False,
333
+ sort_results=False,
334
+ ):
335
+ """Return the results of the reduction for the given arguments.
336
+
337
+ Parameters
338
+ ----------
339
+ X : ndarray or CSR matrix of shape (n_samples_X, n_features)
340
+ Input data.
341
+
342
+ Y : ndarray or CSR matrix of shape (n_samples_Y, n_features)
343
+ Input data.
344
+
345
+ radius : float
346
+ The radius defining the neighborhood.
347
+
348
+ metric : str, default='euclidean'
349
+ The distance metric to use.
350
+ For a list of available metrics, see the documentation of
351
+ :class:`~sklearn.metrics.DistanceMetric`.
352
+
353
+ chunk_size : int, default=None,
354
+ The number of vectors per chunk. If None (default) looks-up in
355
+ scikit-learn configuration for `pairwise_dist_chunk_size`,
356
+ and use 256 if it is not set.
357
+
358
+ metric_kwargs : dict, default=None
359
+ Keyword arguments to pass to specified metric function.
360
+
361
+ strategy : str, {'auto', 'parallel_on_X', 'parallel_on_Y'}, default=None
362
+ The chunking strategy defining which dataset parallelization are made on.
363
+
364
+ For both strategies the computations happens with two nested loops,
365
+ respectively on chunks of X and chunks of Y.
366
+ Strategies differs on which loop (outer or inner) is made to run
367
+ in parallel with the Cython `prange` construct:
368
+
369
+ - 'parallel_on_X' dispatches chunks of X uniformly on threads.
370
+ Each thread then iterates on all the chunks of Y. This strategy is
371
+ embarrassingly parallel and comes with no datastructures
372
+ synchronisation.
373
+
374
+ - 'parallel_on_Y' dispatches chunks of Y uniformly on threads.
375
+ Each thread processes all the chunks of X in turn. This strategy is
376
+ a sequence of embarrassingly parallel subtasks (the inner loop on Y
377
+ chunks) with intermediate datastructures synchronisation at each
378
+ iteration of the sequential outer loop on X chunks.
379
+
380
+ - 'auto' relies on a simple heuristic to choose between
381
+ 'parallel_on_X' and 'parallel_on_Y': when `X.shape[0]` is large enough,
382
+ 'parallel_on_X' is usually the most efficient strategy.
383
+ When `X.shape[0]` is small but `Y.shape[0]` is large, 'parallel_on_Y'
384
+ brings more opportunity for parallelism and is therefore more efficient
385
+ despite the synchronization step at each iteration of the outer loop
386
+ on chunks of `X`.
387
+
388
+ - None (default) looks-up in scikit-learn configuration for
389
+ `pairwise_dist_parallel_strategy`, and use 'auto' if it is not set.
390
+
391
+ return_distance : boolean, default=False
392
+ Return distances between each X vector and its neighbors if set to True.
393
+
394
+ sort_results : boolean, default=False
395
+ Sort results with respect to distances between each X vector and its
396
+ neighbors if set to True.
397
+
398
+ Returns
399
+ -------
400
+ If return_distance=False:
401
+ - neighbors_indices : ndarray of n_samples_X ndarray
402
+ Indices of the neighbors for each vector in X.
403
+
404
+ If return_distance=True:
405
+ - neighbors_indices : ndarray of n_samples_X ndarray
406
+ Indices of the neighbors for each vector in X.
407
+ - neighbors_distances : ndarray of n_samples_X ndarray
408
+ Distances to the neighbors for each vector in X.
409
+
410
+ Notes
411
+ -----
412
+ This classmethod inspects the arguments values to dispatch to the
413
+ dtype-specialized implementation of :class:`RadiusNeighbors`.
414
+
415
+ This allows decoupling the API entirely from the implementation details
416
+ whilst maintaining RAII: all temporarily allocated datastructures necessary
417
+ for the concrete implementation are therefore freed when this classmethod
418
+ returns.
419
+ """
420
+ if X.dtype == Y.dtype == np.float64:
421
+ return RadiusNeighbors64.compute(
422
+ X=X,
423
+ Y=Y,
424
+ radius=radius,
425
+ metric=metric,
426
+ chunk_size=chunk_size,
427
+ metric_kwargs=metric_kwargs,
428
+ strategy=strategy,
429
+ sort_results=sort_results,
430
+ return_distance=return_distance,
431
+ )
432
+
433
+ if X.dtype == Y.dtype == np.float32:
434
+ return RadiusNeighbors32.compute(
435
+ X=X,
436
+ Y=Y,
437
+ radius=radius,
438
+ metric=metric,
439
+ chunk_size=chunk_size,
440
+ metric_kwargs=metric_kwargs,
441
+ strategy=strategy,
442
+ sort_results=sort_results,
443
+ return_distance=return_distance,
444
+ )
445
+
446
+ raise ValueError(
447
+ "Only float64 or float32 datasets pairs are supported at this time, "
448
+ f"got: X.dtype={X.dtype} and Y.dtype={Y.dtype}."
449
+ )
videollama2/lib/python3.10/site-packages/sklearn/metrics/_ranking.py ADDED
@@ -0,0 +1,1826 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Metrics to assess performance on classification task given scores.
2
+
3
+ Functions named as ``*_score`` return a scalar value to maximize: the higher
4
+ the better.
5
+
6
+ Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize:
7
+ the lower the better.
8
+ """
9
+
10
+ # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
11
+ # Mathieu Blondel <mathieu@mblondel.org>
12
+ # Olivier Grisel <olivier.grisel@ensta.org>
13
+ # Arnaud Joly <a.joly@ulg.ac.be>
14
+ # Jochen Wersdorfer <jochen@wersdoerfer.de>
15
+ # Lars Buitinck
16
+ # Joel Nothman <joel.nothman@gmail.com>
17
+ # Noel Dawe <noel@dawe.me>
18
+ # Michal Karbownik <michakarbownik@gmail.com>
19
+ # License: BSD 3 clause
20
+
21
+
22
+ import warnings
23
+ from functools import partial
24
+
25
+ import numpy as np
26
+ from scipy.sparse import csr_matrix, issparse
27
+ from scipy.stats import rankdata
28
+
29
+ from ..utils import assert_all_finite
30
+ from ..utils import check_consistent_length
31
+ from ..utils.validation import _check_sample_weight
32
+ from ..utils import column_or_1d, check_array
33
+ from ..utils.multiclass import type_of_target
34
+ from ..utils.extmath import stable_cumsum
35
+ from ..utils.sparsefuncs import count_nonzero
36
+ from ..exceptions import UndefinedMetricWarning
37
+ from ..preprocessing import label_binarize
38
+ from ..utils._encode import _encode, _unique
39
+
40
+ from ._base import (
41
+ _average_binary_score,
42
+ _average_multiclass_ovo_score,
43
+ _check_pos_label_consistency,
44
+ )
45
+
46
+
47
+ def auc(x, y):
48
+ """Compute Area Under the Curve (AUC) using the trapezoidal rule.
49
+
50
+ This is a general function, given points on a curve. For computing the
51
+ area under the ROC-curve, see :func:`roc_auc_score`. For an alternative
52
+ way to summarize a precision-recall curve, see
53
+ :func:`average_precision_score`.
54
+
55
+ Parameters
56
+ ----------
57
+ x : ndarray of shape (n,)
58
+ X coordinates. These must be either monotonic increasing or monotonic
59
+ decreasing.
60
+ y : ndarray of shape, (n,)
61
+ Y coordinates.
62
+
63
+ Returns
64
+ -------
65
+ auc : float
66
+ Area Under the Curve.
67
+
68
+ See Also
69
+ --------
70
+ roc_auc_score : Compute the area under the ROC curve.
71
+ average_precision_score : Compute average precision from prediction scores.
72
+ precision_recall_curve : Compute precision-recall pairs for different
73
+ probability thresholds.
74
+
75
+ Examples
76
+ --------
77
+ >>> import numpy as np
78
+ >>> from sklearn import metrics
79
+ >>> y = np.array([1, 1, 2, 2])
80
+ >>> pred = np.array([0.1, 0.4, 0.35, 0.8])
81
+ >>> fpr, tpr, thresholds = metrics.roc_curve(y, pred, pos_label=2)
82
+ >>> metrics.auc(fpr, tpr)
83
+ 0.75
84
+ """
85
+ check_consistent_length(x, y)
86
+ x = column_or_1d(x)
87
+ y = column_or_1d(y)
88
+
89
+ if x.shape[0] < 2:
90
+ raise ValueError(
91
+ "At least 2 points are needed to compute area under curve, but x.shape = %s"
92
+ % x.shape
93
+ )
94
+
95
+ direction = 1
96
+ dx = np.diff(x)
97
+ if np.any(dx < 0):
98
+ if np.all(dx <= 0):
99
+ direction = -1
100
+ else:
101
+ raise ValueError("x is neither increasing nor decreasing : {}.".format(x))
102
+
103
+ area = direction * np.trapz(y, x)
104
+ if isinstance(area, np.memmap):
105
+ # Reductions such as .sum used internally in np.trapz do not return a
106
+ # scalar by default for numpy.memmap instances contrary to
107
+ # regular numpy.ndarray instances.
108
+ area = area.dtype.type(area)
109
+ return area
110
+
111
+
112
+ def average_precision_score(
113
+ y_true, y_score, *, average="macro", pos_label=1, sample_weight=None
114
+ ):
115
+ """Compute average precision (AP) from prediction scores.
116
+
117
+ AP summarizes a precision-recall curve as the weighted mean of precisions
118
+ achieved at each threshold, with the increase in recall from the previous
119
+ threshold used as the weight:
120
+
121
+ .. math::
122
+ \\text{AP} = \\sum_n (R_n - R_{n-1}) P_n
123
+
124
+ where :math:`P_n` and :math:`R_n` are the precision and recall at the nth
125
+ threshold [1]_. This implementation is not interpolated and is different
126
+ from computing the area under the precision-recall curve with the
127
+ trapezoidal rule, which uses linear interpolation and can be too
128
+ optimistic.
129
+
130
+ Note: this implementation is restricted to the binary classification task
131
+ or multilabel classification task.
132
+
133
+ Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`.
134
+
135
+ Parameters
136
+ ----------
137
+ y_true : ndarray of shape (n_samples,) or (n_samples, n_classes)
138
+ True binary labels or binary label indicators.
139
+
140
+ y_score : ndarray of shape (n_samples,) or (n_samples, n_classes)
141
+ Target scores, can either be probability estimates of the positive
142
+ class, confidence values, or non-thresholded measure of decisions
143
+ (as returned by :term:`decision_function` on some classifiers).
144
+
145
+ average : {'micro', 'samples', 'weighted', 'macro'} or None, \
146
+ default='macro'
147
+ If ``None``, the scores for each class are returned. Otherwise,
148
+ this determines the type of averaging performed on the data:
149
+
150
+ ``'micro'``:
151
+ Calculate metrics globally by considering each element of the label
152
+ indicator matrix as a label.
153
+ ``'macro'``:
154
+ Calculate metrics for each label, and find their unweighted
155
+ mean. This does not take label imbalance into account.
156
+ ``'weighted'``:
157
+ Calculate metrics for each label, and find their average, weighted
158
+ by support (the number of true instances for each label).
159
+ ``'samples'``:
160
+ Calculate metrics for each instance, and find their average.
161
+
162
+ Will be ignored when ``y_true`` is binary.
163
+
164
+ pos_label : int or str, default=1
165
+ The label of the positive class. Only applied to binary ``y_true``.
166
+ For multilabel-indicator ``y_true``, ``pos_label`` is fixed to 1.
167
+
168
+ sample_weight : array-like of shape (n_samples,), default=None
169
+ Sample weights.
170
+
171
+ Returns
172
+ -------
173
+ average_precision : float
174
+ Average precision score.
175
+
176
+ See Also
177
+ --------
178
+ roc_auc_score : Compute the area under the ROC curve.
179
+ precision_recall_curve : Compute precision-recall pairs for different
180
+ probability thresholds.
181
+
182
+ Notes
183
+ -----
184
+ .. versionchanged:: 0.19
185
+ Instead of linearly interpolating between operating points, precisions
186
+ are weighted by the change in recall since the last operating point.
187
+
188
+ References
189
+ ----------
190
+ .. [1] `Wikipedia entry for the Average precision
191
+ <https://en.wikipedia.org/w/index.php?title=Information_retrieval&
192
+ oldid=793358396#Average_precision>`_
193
+
194
+ Examples
195
+ --------
196
+ >>> import numpy as np
197
+ >>> from sklearn.metrics import average_precision_score
198
+ >>> y_true = np.array([0, 0, 1, 1])
199
+ >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8])
200
+ >>> average_precision_score(y_true, y_scores)
201
+ 0.83...
202
+ """
203
+
204
+ def _binary_uninterpolated_average_precision(
205
+ y_true, y_score, pos_label=1, sample_weight=None
206
+ ):
207
+ precision, recall, _ = precision_recall_curve(
208
+ y_true, y_score, pos_label=pos_label, sample_weight=sample_weight
209
+ )
210
+ # Return the step function integral
211
+ # The following works because the last entry of precision is
212
+ # guaranteed to be 1, as returned by precision_recall_curve
213
+ return -np.sum(np.diff(recall) * np.array(precision)[:-1])
214
+
215
+ y_type = type_of_target(y_true, input_name="y_true")
216
+ if y_type == "multilabel-indicator" and pos_label != 1:
217
+ raise ValueError(
218
+ "Parameter pos_label is fixed to 1 for "
219
+ "multilabel-indicator y_true. Do not set "
220
+ "pos_label or set pos_label to 1."
221
+ )
222
+ elif y_type == "binary":
223
+ # Convert to Python primitive type to avoid NumPy type / Python str
224
+ # comparison. See https://github.com/numpy/numpy/issues/6784
225
+ present_labels = np.unique(y_true).tolist()
226
+ if len(present_labels) == 2 and pos_label not in present_labels:
227
+ raise ValueError(
228
+ f"pos_label={pos_label} is not a valid label. It should be "
229
+ f"one of {present_labels}"
230
+ )
231
+ average_precision = partial(
232
+ _binary_uninterpolated_average_precision, pos_label=pos_label
233
+ )
234
+ return _average_binary_score(
235
+ average_precision, y_true, y_score, average, sample_weight=sample_weight
236
+ )
237
+
238
+
239
+ def det_curve(y_true, y_score, pos_label=None, sample_weight=None):
240
+ """Compute error rates for different probability thresholds.
241
+
242
+ .. note::
243
+ This metric is used for evaluation of ranking and error tradeoffs of
244
+ a binary classification task.
245
+
246
+ Read more in the :ref:`User Guide <det_curve>`.
247
+
248
+ .. versionadded:: 0.24
249
+
250
+ Parameters
251
+ ----------
252
+ y_true : ndarray of shape (n_samples,)
253
+ True binary labels. If labels are not either {-1, 1} or {0, 1}, then
254
+ pos_label should be explicitly given.
255
+
256
+ y_score : ndarray of shape of (n_samples,)
257
+ Target scores, can either be probability estimates of the positive
258
+ class, confidence values, or non-thresholded measure of decisions
259
+ (as returned by "decision_function" on some classifiers).
260
+
261
+ pos_label : int or str, default=None
262
+ The label of the positive class.
263
+ When ``pos_label=None``, if `y_true` is in {-1, 1} or {0, 1},
264
+ ``pos_label`` is set to 1, otherwise an error will be raised.
265
+
266
+ sample_weight : array-like of shape (n_samples,), default=None
267
+ Sample weights.
268
+
269
+ Returns
270
+ -------
271
+ fpr : ndarray of shape (n_thresholds,)
272
+ False positive rate (FPR) such that element i is the false positive
273
+ rate of predictions with score >= thresholds[i]. This is occasionally
274
+ referred to as false acceptance propability or fall-out.
275
+
276
+ fnr : ndarray of shape (n_thresholds,)
277
+ False negative rate (FNR) such that element i is the false negative
278
+ rate of predictions with score >= thresholds[i]. This is occasionally
279
+ referred to as false rejection or miss rate.
280
+
281
+ thresholds : ndarray of shape (n_thresholds,)
282
+ Decreasing score values.
283
+
284
+ See Also
285
+ --------
286
+ DetCurveDisplay.from_estimator : Plot DET curve given an estimator and
287
+ some data.
288
+ DetCurveDisplay.from_predictions : Plot DET curve given the true and
289
+ predicted labels.
290
+ DetCurveDisplay : DET curve visualization.
291
+ roc_curve : Compute Receiver operating characteristic (ROC) curve.
292
+ precision_recall_curve : Compute precision-recall curve.
293
+
294
+ Examples
295
+ --------
296
+ >>> import numpy as np
297
+ >>> from sklearn.metrics import det_curve
298
+ >>> y_true = np.array([0, 0, 1, 1])
299
+ >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8])
300
+ >>> fpr, fnr, thresholds = det_curve(y_true, y_scores)
301
+ >>> fpr
302
+ array([0.5, 0.5, 0. ])
303
+ >>> fnr
304
+ array([0. , 0.5, 0.5])
305
+ >>> thresholds
306
+ array([0.35, 0.4 , 0.8 ])
307
+ """
308
+ fps, tps, thresholds = _binary_clf_curve(
309
+ y_true, y_score, pos_label=pos_label, sample_weight=sample_weight
310
+ )
311
+
312
+ if len(np.unique(y_true)) != 2:
313
+ raise ValueError(
314
+ "Only one class present in y_true. Detection error "
315
+ "tradeoff curve is not defined in that case."
316
+ )
317
+
318
+ fns = tps[-1] - tps
319
+ p_count = tps[-1]
320
+ n_count = fps[-1]
321
+
322
+ # start with false positives zero
323
+ first_ind = (
324
+ fps.searchsorted(fps[0], side="right") - 1
325
+ if fps.searchsorted(fps[0], side="right") > 0
326
+ else None
327
+ )
328
+ # stop with false negatives zero
329
+ last_ind = tps.searchsorted(tps[-1]) + 1
330
+ sl = slice(first_ind, last_ind)
331
+
332
+ # reverse the output such that list of false positives is decreasing
333
+ return (fps[sl][::-1] / n_count, fns[sl][::-1] / p_count, thresholds[sl][::-1])
334
+
335
+
336
+ def _binary_roc_auc_score(y_true, y_score, sample_weight=None, max_fpr=None):
337
+ """Binary roc auc score."""
338
+ if len(np.unique(y_true)) != 2:
339
+ raise ValueError(
340
+ "Only one class present in y_true. ROC AUC score "
341
+ "is not defined in that case."
342
+ )
343
+
344
+ fpr, tpr, _ = roc_curve(y_true, y_score, sample_weight=sample_weight)
345
+ if max_fpr is None or max_fpr == 1:
346
+ return auc(fpr, tpr)
347
+ if max_fpr <= 0 or max_fpr > 1:
348
+ raise ValueError("Expected max_fpr in range (0, 1], got: %r" % max_fpr)
349
+
350
+ # Add a single point at max_fpr by linear interpolation
351
+ stop = np.searchsorted(fpr, max_fpr, "right")
352
+ x_interp = [fpr[stop - 1], fpr[stop]]
353
+ y_interp = [tpr[stop - 1], tpr[stop]]
354
+ tpr = np.append(tpr[:stop], np.interp(max_fpr, x_interp, y_interp))
355
+ fpr = np.append(fpr[:stop], max_fpr)
356
+ partial_auc = auc(fpr, tpr)
357
+
358
+ # McClish correction: standardize result to be 0.5 if non-discriminant
359
+ # and 1 if maximal
360
+ min_area = 0.5 * max_fpr**2
361
+ max_area = max_fpr
362
+ return 0.5 * (1 + (partial_auc - min_area) / (max_area - min_area))
363
+
364
+
365
+ def roc_auc_score(
366
+ y_true,
367
+ y_score,
368
+ *,
369
+ average="macro",
370
+ sample_weight=None,
371
+ max_fpr=None,
372
+ multi_class="raise",
373
+ labels=None,
374
+ ):
375
+ """Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) \
376
+ from prediction scores.
377
+
378
+ Note: this implementation can be used with binary, multiclass and
379
+ multilabel classification, but some restrictions apply (see Parameters).
380
+
381
+ Read more in the :ref:`User Guide <roc_metrics>`.
382
+
383
+ Parameters
384
+ ----------
385
+ y_true : array-like of shape (n_samples,) or (n_samples, n_classes)
386
+ True labels or binary label indicators. The binary and multiclass cases
387
+ expect labels with shape (n_samples,) while the multilabel case expects
388
+ binary label indicators with shape (n_samples, n_classes).
389
+
390
+ y_score : array-like of shape (n_samples,) or (n_samples, n_classes)
391
+ Target scores.
392
+
393
+ * In the binary case, it corresponds to an array of shape
394
+ `(n_samples,)`. Both probability estimates and non-thresholded
395
+ decision values can be provided. The probability estimates correspond
396
+ to the **probability of the class with the greater label**,
397
+ i.e. `estimator.classes_[1]` and thus
398
+ `estimator.predict_proba(X, y)[:, 1]`. The decision values
399
+ corresponds to the output of `estimator.decision_function(X, y)`.
400
+ See more information in the :ref:`User guide <roc_auc_binary>`;
401
+ * In the multiclass case, it corresponds to an array of shape
402
+ `(n_samples, n_classes)` of probability estimates provided by the
403
+ `predict_proba` method. The probability estimates **must**
404
+ sum to 1 across the possible classes. In addition, the order of the
405
+ class scores must correspond to the order of ``labels``,
406
+ if provided, or else to the numerical or lexicographical order of
407
+ the labels in ``y_true``. See more information in the
408
+ :ref:`User guide <roc_auc_multiclass>`;
409
+ * In the multilabel case, it corresponds to an array of shape
410
+ `(n_samples, n_classes)`. Probability estimates are provided by the
411
+ `predict_proba` method and the non-thresholded decision values by
412
+ the `decision_function` method. The probability estimates correspond
413
+ to the **probability of the class with the greater label for each
414
+ output** of the classifier. See more information in the
415
+ :ref:`User guide <roc_auc_multilabel>`.
416
+
417
+ average : {'micro', 'macro', 'samples', 'weighted'} or None, \
418
+ default='macro'
419
+ If ``None``, the scores for each class are returned.
420
+ Otherwise, this determines the type of averaging performed on the data.
421
+ Note: multiclass ROC AUC currently only handles the 'macro' and
422
+ 'weighted' averages. For multiclass targets, `average=None` is only
423
+ implemented for `multi_class='ovr'` and `average='micro'` is only
424
+ implemented for `multi_class='ovr'`.
425
+
426
+ ``'micro'``:
427
+ Calculate metrics globally by considering each element of the label
428
+ indicator matrix as a label.
429
+ ``'macro'``:
430
+ Calculate metrics for each label, and find their unweighted
431
+ mean. This does not take label imbalance into account.
432
+ ``'weighted'``:
433
+ Calculate metrics for each label, and find their average, weighted
434
+ by support (the number of true instances for each label).
435
+ ``'samples'``:
436
+ Calculate metrics for each instance, and find their average.
437
+
438
+ Will be ignored when ``y_true`` is binary.
439
+
440
+ sample_weight : array-like of shape (n_samples,), default=None
441
+ Sample weights.
442
+
443
+ max_fpr : float > 0 and <= 1, default=None
444
+ If not ``None``, the standardized partial AUC [2]_ over the range
445
+ [0, max_fpr] is returned. For the multiclass case, ``max_fpr``,
446
+ should be either equal to ``None`` or ``1.0`` as AUC ROC partial
447
+ computation currently is not supported for multiclass.
448
+
449
+ multi_class : {'raise', 'ovr', 'ovo'}, default='raise'
450
+ Only used for multiclass targets. Determines the type of configuration
451
+ to use. The default value raises an error, so either
452
+ ``'ovr'`` or ``'ovo'`` must be passed explicitly.
453
+
454
+ ``'ovr'``:
455
+ Stands for One-vs-rest. Computes the AUC of each class
456
+ against the rest [3]_ [4]_. This
457
+ treats the multiclass case in the same way as the multilabel case.
458
+ Sensitive to class imbalance even when ``average == 'macro'``,
459
+ because class imbalance affects the composition of each of the
460
+ 'rest' groupings.
461
+ ``'ovo'``:
462
+ Stands for One-vs-one. Computes the average AUC of all
463
+ possible pairwise combinations of classes [5]_.
464
+ Insensitive to class imbalance when
465
+ ``average == 'macro'``.
466
+
467
+ labels : array-like of shape (n_classes,), default=None
468
+ Only used for multiclass targets. List of labels that index the
469
+ classes in ``y_score``. If ``None``, the numerical or lexicographical
470
+ order of the labels in ``y_true`` is used.
471
+
472
+ Returns
473
+ -------
474
+ auc : float
475
+ Area Under the Curve score.
476
+
477
+ See Also
478
+ --------
479
+ average_precision_score : Area under the precision-recall curve.
480
+ roc_curve : Compute Receiver operating characteristic (ROC) curve.
481
+ RocCurveDisplay.from_estimator : Plot Receiver Operating Characteristic
482
+ (ROC) curve given an estimator and some data.
483
+ RocCurveDisplay.from_predictions : Plot Receiver Operating Characteristic
484
+ (ROC) curve given the true and predicted values.
485
+
486
+ References
487
+ ----------
488
+ .. [1] `Wikipedia entry for the Receiver operating characteristic
489
+ <https://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_
490
+
491
+ .. [2] `Analyzing a portion of the ROC curve. McClish, 1989
492
+ <https://www.ncbi.nlm.nih.gov/pubmed/2668680>`_
493
+
494
+ .. [3] Provost, F., Domingos, P. (2000). Well-trained PETs: Improving
495
+ probability estimation trees (Section 6.2), CeDER Working Paper
496
+ #IS-00-04, Stern School of Business, New York University.
497
+
498
+ .. [4] `Fawcett, T. (2006). An introduction to ROC analysis. Pattern
499
+ Recognition Letters, 27(8), 861-874.
500
+ <https://www.sciencedirect.com/science/article/pii/S016786550500303X>`_
501
+
502
+ .. [5] `Hand, D.J., Till, R.J. (2001). A Simple Generalisation of the Area
503
+ Under the ROC Curve for Multiple Class Classification Problems.
504
+ Machine Learning, 45(2), 171-186.
505
+ <http://link.springer.com/article/10.1023/A:1010920819831>`_
506
+
507
+ Examples
508
+ --------
509
+ Binary case:
510
+
511
+ >>> from sklearn.datasets import load_breast_cancer
512
+ >>> from sklearn.linear_model import LogisticRegression
513
+ >>> from sklearn.metrics import roc_auc_score
514
+ >>> X, y = load_breast_cancer(return_X_y=True)
515
+ >>> clf = LogisticRegression(solver="liblinear", random_state=0).fit(X, y)
516
+ >>> roc_auc_score(y, clf.predict_proba(X)[:, 1])
517
+ 0.99...
518
+ >>> roc_auc_score(y, clf.decision_function(X))
519
+ 0.99...
520
+
521
+ Multiclass case:
522
+
523
+ >>> from sklearn.datasets import load_iris
524
+ >>> X, y = load_iris(return_X_y=True)
525
+ >>> clf = LogisticRegression(solver="liblinear").fit(X, y)
526
+ >>> roc_auc_score(y, clf.predict_proba(X), multi_class='ovr')
527
+ 0.99...
528
+
529
+ Multilabel case:
530
+
531
+ >>> import numpy as np
532
+ >>> from sklearn.datasets import make_multilabel_classification
533
+ >>> from sklearn.multioutput import MultiOutputClassifier
534
+ >>> X, y = make_multilabel_classification(random_state=0)
535
+ >>> clf = MultiOutputClassifier(clf).fit(X, y)
536
+ >>> # get a list of n_output containing probability arrays of shape
537
+ >>> # (n_samples, n_classes)
538
+ >>> y_pred = clf.predict_proba(X)
539
+ >>> # extract the positive columns for each output
540
+ >>> y_pred = np.transpose([pred[:, 1] for pred in y_pred])
541
+ >>> roc_auc_score(y, y_pred, average=None)
542
+ array([0.82..., 0.86..., 0.94..., 0.85... , 0.94...])
543
+ >>> from sklearn.linear_model import RidgeClassifierCV
544
+ >>> clf = RidgeClassifierCV().fit(X, y)
545
+ >>> roc_auc_score(y, clf.decision_function(X), average=None)
546
+ array([0.81..., 0.84... , 0.93..., 0.87..., 0.94...])
547
+ """
548
+
549
+ y_type = type_of_target(y_true, input_name="y_true")
550
+ y_true = check_array(y_true, ensure_2d=False, dtype=None)
551
+ y_score = check_array(y_score, ensure_2d=False)
552
+
553
+ if y_type == "multiclass" or (
554
+ y_type == "binary" and y_score.ndim == 2 and y_score.shape[1] > 2
555
+ ):
556
+ # do not support partial ROC computation for multiclass
557
+ if max_fpr is not None and max_fpr != 1.0:
558
+ raise ValueError(
559
+ "Partial AUC computation not available in "
560
+ "multiclass setting, 'max_fpr' must be"
561
+ " set to `None`, received `max_fpr={0}` "
562
+ "instead".format(max_fpr)
563
+ )
564
+ if multi_class == "raise":
565
+ raise ValueError("multi_class must be in ('ovo', 'ovr')")
566
+ return _multiclass_roc_auc_score(
567
+ y_true, y_score, labels, multi_class, average, sample_weight
568
+ )
569
+ elif y_type == "binary":
570
+ labels = np.unique(y_true)
571
+ y_true = label_binarize(y_true, classes=labels)[:, 0]
572
+ return _average_binary_score(
573
+ partial(_binary_roc_auc_score, max_fpr=max_fpr),
574
+ y_true,
575
+ y_score,
576
+ average,
577
+ sample_weight=sample_weight,
578
+ )
579
+ else: # multilabel-indicator
580
+ return _average_binary_score(
581
+ partial(_binary_roc_auc_score, max_fpr=max_fpr),
582
+ y_true,
583
+ y_score,
584
+ average,
585
+ sample_weight=sample_weight,
586
+ )
587
+
588
+
589
+ def _multiclass_roc_auc_score(
590
+ y_true, y_score, labels, multi_class, average, sample_weight
591
+ ):
592
+ """Multiclass roc auc score.
593
+
594
+ Parameters
595
+ ----------
596
+ y_true : array-like of shape (n_samples,)
597
+ True multiclass labels.
598
+
599
+ y_score : array-like of shape (n_samples, n_classes)
600
+ Target scores corresponding to probability estimates of a sample
601
+ belonging to a particular class
602
+
603
+ labels : array-like of shape (n_classes,) or None
604
+ List of labels to index ``y_score`` used for multiclass. If ``None``,
605
+ the lexical order of ``y_true`` is used to index ``y_score``.
606
+
607
+ multi_class : {'ovr', 'ovo'}
608
+ Determines the type of multiclass configuration to use.
609
+ ``'ovr'``:
610
+ Calculate metrics for the multiclass case using the one-vs-rest
611
+ approach.
612
+ ``'ovo'``:
613
+ Calculate metrics for the multiclass case using the one-vs-one
614
+ approach.
615
+
616
+ average : {'micro', 'macro', 'weighted'}
617
+ Determines the type of averaging performed on the pairwise binary
618
+ metric scores
619
+ ``'micro'``:
620
+ Calculate metrics for the binarized-raveled classes. Only supported
621
+ for `multi_class='ovr'`.
622
+
623
+ .. versionadded:: 1.2
624
+
625
+ ``'macro'``:
626
+ Calculate metrics for each label, and find their unweighted
627
+ mean. This does not take label imbalance into account. Classes
628
+ are assumed to be uniformly distributed.
629
+ ``'weighted'``:
630
+ Calculate metrics for each label, taking into account the
631
+ prevalence of the classes.
632
+
633
+ sample_weight : array-like of shape (n_samples,) or None
634
+ Sample weights.
635
+
636
+ """
637
+ # validation of the input y_score
638
+ if not np.allclose(1, y_score.sum(axis=1)):
639
+ raise ValueError(
640
+ "Target scores need to be probabilities for multiclass "
641
+ "roc_auc, i.e. they should sum up to 1.0 over classes"
642
+ )
643
+
644
+ # validation for multiclass parameter specifications
645
+ average_options = ("macro", "weighted", None)
646
+ if multi_class == "ovr":
647
+ average_options = ("micro",) + average_options
648
+ if average not in average_options:
649
+ raise ValueError(
650
+ "average must be one of {0} for multiclass problems".format(average_options)
651
+ )
652
+
653
+ multiclass_options = ("ovo", "ovr")
654
+ if multi_class not in multiclass_options:
655
+ raise ValueError(
656
+ "multi_class='{0}' is not supported "
657
+ "for multiclass ROC AUC, multi_class must be "
658
+ "in {1}".format(multi_class, multiclass_options)
659
+ )
660
+
661
+ if average is None and multi_class == "ovo":
662
+ raise NotImplementedError(
663
+ "average=None is not implemented for multi_class='ovo'."
664
+ )
665
+
666
+ if labels is not None:
667
+ labels = column_or_1d(labels)
668
+ classes = _unique(labels)
669
+ if len(classes) != len(labels):
670
+ raise ValueError("Parameter 'labels' must be unique")
671
+ if not np.array_equal(classes, labels):
672
+ raise ValueError("Parameter 'labels' must be ordered")
673
+ if len(classes) != y_score.shape[1]:
674
+ raise ValueError(
675
+ "Number of given labels, {0}, not equal to the number "
676
+ "of columns in 'y_score', {1}".format(len(classes), y_score.shape[1])
677
+ )
678
+ if len(np.setdiff1d(y_true, classes)):
679
+ raise ValueError("'y_true' contains labels not in parameter 'labels'")
680
+ else:
681
+ classes = _unique(y_true)
682
+ if len(classes) != y_score.shape[1]:
683
+ raise ValueError(
684
+ "Number of classes in y_true not equal to the number of "
685
+ "columns in 'y_score'"
686
+ )
687
+
688
+ if multi_class == "ovo":
689
+ if sample_weight is not None:
690
+ raise ValueError(
691
+ "sample_weight is not supported "
692
+ "for multiclass one-vs-one ROC AUC, "
693
+ "'sample_weight' must be None in this case."
694
+ )
695
+ y_true_encoded = _encode(y_true, uniques=classes)
696
+ # Hand & Till (2001) implementation (ovo)
697
+ return _average_multiclass_ovo_score(
698
+ _binary_roc_auc_score, y_true_encoded, y_score, average=average
699
+ )
700
+ else:
701
+ # ovr is same as multi-label
702
+ y_true_multilabel = label_binarize(y_true, classes=classes)
703
+ return _average_binary_score(
704
+ _binary_roc_auc_score,
705
+ y_true_multilabel,
706
+ y_score,
707
+ average,
708
+ sample_weight=sample_weight,
709
+ )
710
+
711
+
712
+ def _binary_clf_curve(y_true, y_score, pos_label=None, sample_weight=None):
713
+ """Calculate true and false positives per binary classification threshold.
714
+
715
+ Parameters
716
+ ----------
717
+ y_true : ndarray of shape (n_samples,)
718
+ True targets of binary classification.
719
+
720
+ y_score : ndarray of shape (n_samples,)
721
+ Estimated probabilities or output of a decision function.
722
+
723
+ pos_label : int or str, default=None
724
+ The label of the positive class.
725
+
726
+ sample_weight : array-like of shape (n_samples,), default=None
727
+ Sample weights.
728
+
729
+ Returns
730
+ -------
731
+ fps : ndarray of shape (n_thresholds,)
732
+ A count of false positives, at index i being the number of negative
733
+ samples assigned a score >= thresholds[i]. The total number of
734
+ negative samples is equal to fps[-1] (thus true negatives are given by
735
+ fps[-1] - fps).
736
+
737
+ tps : ndarray of shape (n_thresholds,)
738
+ An increasing count of true positives, at index i being the number
739
+ of positive samples assigned a score >= thresholds[i]. The total
740
+ number of positive samples is equal to tps[-1] (thus false negatives
741
+ are given by tps[-1] - tps).
742
+
743
+ thresholds : ndarray of shape (n_thresholds,)
744
+ Decreasing score values.
745
+ """
746
+ # Check to make sure y_true is valid
747
+ y_type = type_of_target(y_true, input_name="y_true")
748
+ if not (y_type == "binary" or (y_type == "multiclass" and pos_label is not None)):
749
+ raise ValueError("{0} format is not supported".format(y_type))
750
+
751
+ check_consistent_length(y_true, y_score, sample_weight)
752
+ y_true = column_or_1d(y_true)
753
+ y_score = column_or_1d(y_score)
754
+ assert_all_finite(y_true)
755
+ assert_all_finite(y_score)
756
+
757
+ # Filter out zero-weighted samples, as they should not impact the result
758
+ if sample_weight is not None:
759
+ sample_weight = column_or_1d(sample_weight)
760
+ sample_weight = _check_sample_weight(sample_weight, y_true)
761
+ nonzero_weight_mask = sample_weight != 0
762
+ y_true = y_true[nonzero_weight_mask]
763
+ y_score = y_score[nonzero_weight_mask]
764
+ sample_weight = sample_weight[nonzero_weight_mask]
765
+
766
+ pos_label = _check_pos_label_consistency(pos_label, y_true)
767
+
768
+ # make y_true a boolean vector
769
+ y_true = y_true == pos_label
770
+
771
+ # sort scores and corresponding truth values
772
+ desc_score_indices = np.argsort(y_score, kind="mergesort")[::-1]
773
+ y_score = y_score[desc_score_indices]
774
+ y_true = y_true[desc_score_indices]
775
+ if sample_weight is not None:
776
+ weight = sample_weight[desc_score_indices]
777
+ else:
778
+ weight = 1.0
779
+
780
+ # y_score typically has many tied values. Here we extract
781
+ # the indices associated with the distinct values. We also
782
+ # concatenate a value for the end of the curve.
783
+ distinct_value_indices = np.where(np.diff(y_score))[0]
784
+ threshold_idxs = np.r_[distinct_value_indices, y_true.size - 1]
785
+
786
+ # accumulate the true positives with decreasing threshold
787
+ tps = stable_cumsum(y_true * weight)[threshold_idxs]
788
+ if sample_weight is not None:
789
+ # express fps as a cumsum to ensure fps is increasing even in
790
+ # the presence of floating point errors
791
+ fps = stable_cumsum((1 - y_true) * weight)[threshold_idxs]
792
+ else:
793
+ fps = 1 + threshold_idxs - tps
794
+ return fps, tps, y_score[threshold_idxs]
795
+
796
+
797
+ def precision_recall_curve(y_true, probas_pred, *, pos_label=None, sample_weight=None):
798
+ """Compute precision-recall pairs for different probability thresholds.
799
+
800
+ Note: this implementation is restricted to the binary classification task.
801
+
802
+ The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of
803
+ true positives and ``fp`` the number of false positives. The precision is
804
+ intuitively the ability of the classifier not to label as positive a sample
805
+ that is negative.
806
+
807
+ The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of
808
+ true positives and ``fn`` the number of false negatives. The recall is
809
+ intuitively the ability of the classifier to find all the positive samples.
810
+
811
+ The last precision and recall values are 1. and 0. respectively and do not
812
+ have a corresponding threshold. This ensures that the graph starts on the
813
+ y axis.
814
+
815
+ The first precision and recall values are precision=class balance and recall=1.0
816
+ which corresponds to a classifier that always predicts the positive class.
817
+
818
+ Read more in the :ref:`User Guide <precision_recall_f_measure_metrics>`.
819
+
820
+ Parameters
821
+ ----------
822
+ y_true : ndarray of shape (n_samples,)
823
+ True binary labels. If labels are not either {-1, 1} or {0, 1}, then
824
+ pos_label should be explicitly given.
825
+
826
+ probas_pred : ndarray of shape (n_samples,)
827
+ Target scores, can either be probability estimates of the positive
828
+ class, or non-thresholded measure of decisions (as returned by
829
+ `decision_function` on some classifiers).
830
+
831
+ pos_label : int or str, default=None
832
+ The label of the positive class.
833
+ When ``pos_label=None``, if y_true is in {-1, 1} or {0, 1},
834
+ ``pos_label`` is set to 1, otherwise an error will be raised.
835
+
836
+ sample_weight : array-like of shape (n_samples,), default=None
837
+ Sample weights.
838
+
839
+ Returns
840
+ -------
841
+ precision : ndarray of shape (n_thresholds + 1,)
842
+ Precision values such that element i is the precision of
843
+ predictions with score >= thresholds[i] and the last element is 1.
844
+
845
+ recall : ndarray of shape (n_thresholds + 1,)
846
+ Decreasing recall values such that element i is the recall of
847
+ predictions with score >= thresholds[i] and the last element is 0.
848
+
849
+ thresholds : ndarray of shape (n_thresholds,)
850
+ Increasing thresholds on the decision function used to compute
851
+ precision and recall where `n_thresholds = len(np.unique(probas_pred))`.
852
+
853
+ See Also
854
+ --------
855
+ PrecisionRecallDisplay.from_estimator : Plot Precision Recall Curve given
856
+ a binary classifier.
857
+ PrecisionRecallDisplay.from_predictions : Plot Precision Recall Curve
858
+ using predictions from a binary classifier.
859
+ average_precision_score : Compute average precision from prediction scores.
860
+ det_curve: Compute error rates for different probability thresholds.
861
+ roc_curve : Compute Receiver operating characteristic (ROC) curve.
862
+
863
+ Examples
864
+ --------
865
+ >>> import numpy as np
866
+ >>> from sklearn.metrics import precision_recall_curve
867
+ >>> y_true = np.array([0, 0, 1, 1])
868
+ >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8])
869
+ >>> precision, recall, thresholds = precision_recall_curve(
870
+ ... y_true, y_scores)
871
+ >>> precision
872
+ array([0.5 , 0.66666667, 0.5 , 1. , 1. ])
873
+ >>> recall
874
+ array([1. , 1. , 0.5, 0.5, 0. ])
875
+ >>> thresholds
876
+ array([0.1 , 0.35, 0.4 , 0.8 ])
877
+ """
878
+ fps, tps, thresholds = _binary_clf_curve(
879
+ y_true, probas_pred, pos_label=pos_label, sample_weight=sample_weight
880
+ )
881
+
882
+ ps = tps + fps
883
+ # Initialize the result array with zeros to make sure that precision[ps == 0]
884
+ # does not contain uninitialized values.
885
+ precision = np.zeros_like(tps)
886
+ np.divide(tps, ps, out=precision, where=(ps != 0))
887
+
888
+ # When no positive label in y_true, recall is set to 1 for all thresholds
889
+ # tps[-1] == 0 <=> y_true == all negative labels
890
+ if tps[-1] == 0:
891
+ warnings.warn(
892
+ "No positive class found in y_true, "
893
+ "recall is set to one for all thresholds."
894
+ )
895
+ recall = np.ones_like(tps)
896
+ else:
897
+ recall = tps / tps[-1]
898
+
899
+ # reverse the outputs so recall is decreasing
900
+ sl = slice(None, None, -1)
901
+ return np.hstack((precision[sl], 1)), np.hstack((recall[sl], 0)), thresholds[sl]
902
+
903
+
904
+ def roc_curve(
905
+ y_true, y_score, *, pos_label=None, sample_weight=None, drop_intermediate=True
906
+ ):
907
+ """Compute Receiver operating characteristic (ROC).
908
+
909
+ Note: this implementation is restricted to the binary classification task.
910
+
911
+ Read more in the :ref:`User Guide <roc_metrics>`.
912
+
913
+ Parameters
914
+ ----------
915
+ y_true : ndarray of shape (n_samples,)
916
+ True binary labels. If labels are not either {-1, 1} or {0, 1}, then
917
+ pos_label should be explicitly given.
918
+
919
+ y_score : ndarray of shape (n_samples,)
920
+ Target scores, can either be probability estimates of the positive
921
+ class, confidence values, or non-thresholded measure of decisions
922
+ (as returned by "decision_function" on some classifiers).
923
+
924
+ pos_label : int or str, default=None
925
+ The label of the positive class.
926
+ When ``pos_label=None``, if `y_true` is in {-1, 1} or {0, 1},
927
+ ``pos_label`` is set to 1, otherwise an error will be raised.
928
+
929
+ sample_weight : array-like of shape (n_samples,), default=None
930
+ Sample weights.
931
+
932
+ drop_intermediate : bool, default=True
933
+ Whether to drop some suboptimal thresholds which would not appear
934
+ on a plotted ROC curve. This is useful in order to create lighter
935
+ ROC curves.
936
+
937
+ .. versionadded:: 0.17
938
+ parameter *drop_intermediate*.
939
+
940
+ Returns
941
+ -------
942
+ fpr : ndarray of shape (>2,)
943
+ Increasing false positive rates such that element i is the false
944
+ positive rate of predictions with score >= `thresholds[i]`.
945
+
946
+ tpr : ndarray of shape (>2,)
947
+ Increasing true positive rates such that element `i` is the true
948
+ positive rate of predictions with score >= `thresholds[i]`.
949
+
950
+ thresholds : ndarray of shape = (n_thresholds,)
951
+ Decreasing thresholds on the decision function used to compute
952
+ fpr and tpr. `thresholds[0]` represents no instances being predicted
953
+ and is arbitrarily set to `max(y_score) + 1`.
954
+
955
+ See Also
956
+ --------
957
+ RocCurveDisplay.from_estimator : Plot Receiver Operating Characteristic
958
+ (ROC) curve given an estimator and some data.
959
+ RocCurveDisplay.from_predictions : Plot Receiver Operating Characteristic
960
+ (ROC) curve given the true and predicted values.
961
+ det_curve: Compute error rates for different probability thresholds.
962
+ roc_auc_score : Compute the area under the ROC curve.
963
+
964
+ Notes
965
+ -----
966
+ Since the thresholds are sorted from low to high values, they
967
+ are reversed upon returning them to ensure they correspond to both ``fpr``
968
+ and ``tpr``, which are sorted in reversed order during their calculation.
969
+
970
+ References
971
+ ----------
972
+ .. [1] `Wikipedia entry for the Receiver operating characteristic
973
+ <https://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_
974
+
975
+ .. [2] Fawcett T. An introduction to ROC analysis[J]. Pattern Recognition
976
+ Letters, 2006, 27(8):861-874.
977
+
978
+ Examples
979
+ --------
980
+ >>> import numpy as np
981
+ >>> from sklearn import metrics
982
+ >>> y = np.array([1, 1, 2, 2])
983
+ >>> scores = np.array([0.1, 0.4, 0.35, 0.8])
984
+ >>> fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2)
985
+ >>> fpr
986
+ array([0. , 0. , 0.5, 0.5, 1. ])
987
+ >>> tpr
988
+ array([0. , 0.5, 0.5, 1. , 1. ])
989
+ >>> thresholds
990
+ array([1.8 , 0.8 , 0.4 , 0.35, 0.1 ])
991
+ """
992
+ fps, tps, thresholds = _binary_clf_curve(
993
+ y_true, y_score, pos_label=pos_label, sample_weight=sample_weight
994
+ )
995
+
996
+ # Attempt to drop thresholds corresponding to points in between and
997
+ # collinear with other points. These are always suboptimal and do not
998
+ # appear on a plotted ROC curve (and thus do not affect the AUC).
999
+ # Here np.diff(_, 2) is used as a "second derivative" to tell if there
1000
+ # is a corner at the point. Both fps and tps must be tested to handle
1001
+ # thresholds with multiple data points (which are combined in
1002
+ # _binary_clf_curve). This keeps all cases where the point should be kept,
1003
+ # but does not drop more complicated cases like fps = [1, 3, 7],
1004
+ # tps = [1, 2, 4]; there is no harm in keeping too many thresholds.
1005
+ if drop_intermediate and len(fps) > 2:
1006
+ optimal_idxs = np.where(
1007
+ np.r_[True, np.logical_or(np.diff(fps, 2), np.diff(tps, 2)), True]
1008
+ )[0]
1009
+ fps = fps[optimal_idxs]
1010
+ tps = tps[optimal_idxs]
1011
+ thresholds = thresholds[optimal_idxs]
1012
+
1013
+ # Add an extra threshold position
1014
+ # to make sure that the curve starts at (0, 0)
1015
+ tps = np.r_[0, tps]
1016
+ fps = np.r_[0, fps]
1017
+ thresholds = np.r_[thresholds[0] + 1, thresholds]
1018
+
1019
+ if fps[-1] <= 0:
1020
+ warnings.warn(
1021
+ "No negative samples in y_true, false positive value should be meaningless",
1022
+ UndefinedMetricWarning,
1023
+ )
1024
+ fpr = np.repeat(np.nan, fps.shape)
1025
+ else:
1026
+ fpr = fps / fps[-1]
1027
+
1028
+ if tps[-1] <= 0:
1029
+ warnings.warn(
1030
+ "No positive samples in y_true, true positive value should be meaningless",
1031
+ UndefinedMetricWarning,
1032
+ )
1033
+ tpr = np.repeat(np.nan, tps.shape)
1034
+ else:
1035
+ tpr = tps / tps[-1]
1036
+
1037
+ return fpr, tpr, thresholds
1038
+
1039
+
1040
+ def label_ranking_average_precision_score(y_true, y_score, *, sample_weight=None):
1041
+ """Compute ranking-based average precision.
1042
+
1043
+ Label ranking average precision (LRAP) is the average over each ground
1044
+ truth label assigned to each sample, of the ratio of true vs. total
1045
+ labels with lower score.
1046
+
1047
+ This metric is used in multilabel ranking problem, where the goal
1048
+ is to give better rank to the labels associated to each sample.
1049
+
1050
+ The obtained score is always strictly greater than 0 and
1051
+ the best value is 1.
1052
+
1053
+ Read more in the :ref:`User Guide <label_ranking_average_precision>`.
1054
+
1055
+ Parameters
1056
+ ----------
1057
+ y_true : {ndarray, sparse matrix} of shape (n_samples, n_labels)
1058
+ True binary labels in binary indicator format.
1059
+
1060
+ y_score : ndarray of shape (n_samples, n_labels)
1061
+ Target scores, can either be probability estimates of the positive
1062
+ class, confidence values, or non-thresholded measure of decisions
1063
+ (as returned by "decision_function" on some classifiers).
1064
+
1065
+ sample_weight : array-like of shape (n_samples,), default=None
1066
+ Sample weights.
1067
+
1068
+ .. versionadded:: 0.20
1069
+
1070
+ Returns
1071
+ -------
1072
+ score : float
1073
+ Ranking-based average precision score.
1074
+
1075
+ Examples
1076
+ --------
1077
+ >>> import numpy as np
1078
+ >>> from sklearn.metrics import label_ranking_average_precision_score
1079
+ >>> y_true = np.array([[1, 0, 0], [0, 0, 1]])
1080
+ >>> y_score = np.array([[0.75, 0.5, 1], [1, 0.2, 0.1]])
1081
+ >>> label_ranking_average_precision_score(y_true, y_score)
1082
+ 0.416...
1083
+ """
1084
+ check_consistent_length(y_true, y_score, sample_weight)
1085
+ y_true = check_array(y_true, ensure_2d=False, accept_sparse="csr")
1086
+ y_score = check_array(y_score, ensure_2d=False)
1087
+
1088
+ if y_true.shape != y_score.shape:
1089
+ raise ValueError("y_true and y_score have different shape")
1090
+
1091
+ # Handle badly formatted array and the degenerate case with one label
1092
+ y_type = type_of_target(y_true, input_name="y_true")
1093
+ if y_type != "multilabel-indicator" and not (
1094
+ y_type == "binary" and y_true.ndim == 2
1095
+ ):
1096
+ raise ValueError("{0} format is not supported".format(y_type))
1097
+
1098
+ if not issparse(y_true):
1099
+ y_true = csr_matrix(y_true)
1100
+
1101
+ y_score = -y_score
1102
+
1103
+ n_samples, n_labels = y_true.shape
1104
+
1105
+ out = 0.0
1106
+ for i, (start, stop) in enumerate(zip(y_true.indptr, y_true.indptr[1:])):
1107
+ relevant = y_true.indices[start:stop]
1108
+
1109
+ if relevant.size == 0 or relevant.size == n_labels:
1110
+ # If all labels are relevant or unrelevant, the score is also
1111
+ # equal to 1. The label ranking has no meaning.
1112
+ aux = 1.0
1113
+ else:
1114
+ scores_i = y_score[i]
1115
+ rank = rankdata(scores_i, "max")[relevant]
1116
+ L = rankdata(scores_i[relevant], "max")
1117
+ aux = (L / rank).mean()
1118
+
1119
+ if sample_weight is not None:
1120
+ aux = aux * sample_weight[i]
1121
+ out += aux
1122
+
1123
+ if sample_weight is None:
1124
+ out /= n_samples
1125
+ else:
1126
+ out /= np.sum(sample_weight)
1127
+
1128
+ return out
1129
+
1130
+
1131
+ def coverage_error(y_true, y_score, *, sample_weight=None):
1132
+ """Coverage error measure.
1133
+
1134
+ Compute how far we need to go through the ranked scores to cover all
1135
+ true labels. The best value is equal to the average number
1136
+ of labels in ``y_true`` per sample.
1137
+
1138
+ Ties in ``y_scores`` are broken by giving maximal rank that would have
1139
+ been assigned to all tied values.
1140
+
1141
+ Note: Our implementation's score is 1 greater than the one given in
1142
+ Tsoumakas et al., 2010. This extends it to handle the degenerate case
1143
+ in which an instance has 0 true labels.
1144
+
1145
+ Read more in the :ref:`User Guide <coverage_error>`.
1146
+
1147
+ Parameters
1148
+ ----------
1149
+ y_true : ndarray of shape (n_samples, n_labels)
1150
+ True binary labels in binary indicator format.
1151
+
1152
+ y_score : ndarray of shape (n_samples, n_labels)
1153
+ Target scores, can either be probability estimates of the positive
1154
+ class, confidence values, or non-thresholded measure of decisions
1155
+ (as returned by "decision_function" on some classifiers).
1156
+
1157
+ sample_weight : array-like of shape (n_samples,), default=None
1158
+ Sample weights.
1159
+
1160
+ Returns
1161
+ -------
1162
+ coverage_error : float
1163
+ The coverage error.
1164
+
1165
+ References
1166
+ ----------
1167
+ .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010).
1168
+ Mining multi-label data. In Data mining and knowledge discovery
1169
+ handbook (pp. 667-685). Springer US.
1170
+ """
1171
+ y_true = check_array(y_true, ensure_2d=True)
1172
+ y_score = check_array(y_score, ensure_2d=True)
1173
+ check_consistent_length(y_true, y_score, sample_weight)
1174
+
1175
+ y_type = type_of_target(y_true, input_name="y_true")
1176
+ if y_type != "multilabel-indicator":
1177
+ raise ValueError("{0} format is not supported".format(y_type))
1178
+
1179
+ if y_true.shape != y_score.shape:
1180
+ raise ValueError("y_true and y_score have different shape")
1181
+
1182
+ y_score_mask = np.ma.masked_array(y_score, mask=np.logical_not(y_true))
1183
+ y_min_relevant = y_score_mask.min(axis=1).reshape((-1, 1))
1184
+ coverage = (y_score >= y_min_relevant).sum(axis=1)
1185
+ coverage = coverage.filled(0)
1186
+
1187
+ return np.average(coverage, weights=sample_weight)
1188
+
1189
+
1190
+ def label_ranking_loss(y_true, y_score, *, sample_weight=None):
1191
+ """Compute Ranking loss measure.
1192
+
1193
+ Compute the average number of label pairs that are incorrectly ordered
1194
+ given y_score weighted by the size of the label set and the number of
1195
+ labels not in the label set.
1196
+
1197
+ This is similar to the error set size, but weighted by the number of
1198
+ relevant and irrelevant labels. The best performance is achieved with
1199
+ a ranking loss of zero.
1200
+
1201
+ Read more in the :ref:`User Guide <label_ranking_loss>`.
1202
+
1203
+ .. versionadded:: 0.17
1204
+ A function *label_ranking_loss*
1205
+
1206
+ Parameters
1207
+ ----------
1208
+ y_true : {ndarray, sparse matrix} of shape (n_samples, n_labels)
1209
+ True binary labels in binary indicator format.
1210
+
1211
+ y_score : ndarray of shape (n_samples, n_labels)
1212
+ Target scores, can either be probability estimates of the positive
1213
+ class, confidence values, or non-thresholded measure of decisions
1214
+ (as returned by "decision_function" on some classifiers).
1215
+
1216
+ sample_weight : array-like of shape (n_samples,), default=None
1217
+ Sample weights.
1218
+
1219
+ Returns
1220
+ -------
1221
+ loss : float
1222
+ Average number of label pairs that are incorrectly ordered given
1223
+ y_score weighted by the size of the label set and the number of labels not
1224
+ in the label set.
1225
+
1226
+ References
1227
+ ----------
1228
+ .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010).
1229
+ Mining multi-label data. In Data mining and knowledge discovery
1230
+ handbook (pp. 667-685). Springer US.
1231
+ """
1232
+ y_true = check_array(y_true, ensure_2d=False, accept_sparse="csr")
1233
+ y_score = check_array(y_score, ensure_2d=False)
1234
+ check_consistent_length(y_true, y_score, sample_weight)
1235
+
1236
+ y_type = type_of_target(y_true, input_name="y_true")
1237
+ if y_type not in ("multilabel-indicator",):
1238
+ raise ValueError("{0} format is not supported".format(y_type))
1239
+
1240
+ if y_true.shape != y_score.shape:
1241
+ raise ValueError("y_true and y_score have different shape")
1242
+
1243
+ n_samples, n_labels = y_true.shape
1244
+
1245
+ y_true = csr_matrix(y_true)
1246
+
1247
+ loss = np.zeros(n_samples)
1248
+ for i, (start, stop) in enumerate(zip(y_true.indptr, y_true.indptr[1:])):
1249
+ # Sort and bin the label scores
1250
+ unique_scores, unique_inverse = np.unique(y_score[i], return_inverse=True)
1251
+ true_at_reversed_rank = np.bincount(
1252
+ unique_inverse[y_true.indices[start:stop]], minlength=len(unique_scores)
1253
+ )
1254
+ all_at_reversed_rank = np.bincount(unique_inverse, minlength=len(unique_scores))
1255
+ false_at_reversed_rank = all_at_reversed_rank - true_at_reversed_rank
1256
+
1257
+ # if the scores are ordered, it's possible to count the number of
1258
+ # incorrectly ordered paires in linear time by cumulatively counting
1259
+ # how many false labels of a given score have a score higher than the
1260
+ # accumulated true labels with lower score.
1261
+ loss[i] = np.dot(true_at_reversed_rank.cumsum(), false_at_reversed_rank)
1262
+
1263
+ n_positives = count_nonzero(y_true, axis=1)
1264
+ with np.errstate(divide="ignore", invalid="ignore"):
1265
+ loss /= (n_labels - n_positives) * n_positives
1266
+
1267
+ # When there is no positive or no negative labels, those values should
1268
+ # be consider as correct, i.e. the ranking doesn't matter.
1269
+ loss[np.logical_or(n_positives == 0, n_positives == n_labels)] = 0.0
1270
+
1271
+ return np.average(loss, weights=sample_weight)
1272
+
1273
+
1274
+ def _dcg_sample_scores(y_true, y_score, k=None, log_base=2, ignore_ties=False):
1275
+ """Compute Discounted Cumulative Gain.
1276
+
1277
+ Sum the true scores ranked in the order induced by the predicted scores,
1278
+ after applying a logarithmic discount.
1279
+
1280
+ This ranking metric yields a high value if true labels are ranked high by
1281
+ ``y_score``.
1282
+
1283
+ Parameters
1284
+ ----------
1285
+ y_true : ndarray of shape (n_samples, n_labels)
1286
+ True targets of multilabel classification, or true scores of entities
1287
+ to be ranked.
1288
+
1289
+ y_score : ndarray of shape (n_samples, n_labels)
1290
+ Target scores, can either be probability estimates, confidence values,
1291
+ or non-thresholded measure of decisions (as returned by
1292
+ "decision_function" on some classifiers).
1293
+
1294
+ k : int, default=None
1295
+ Only consider the highest k scores in the ranking. If `None`, use all
1296
+ outputs.
1297
+
1298
+ log_base : float, default=2
1299
+ Base of the logarithm used for the discount. A low value means a
1300
+ sharper discount (top results are more important).
1301
+
1302
+ ignore_ties : bool, default=False
1303
+ Assume that there are no ties in y_score (which is likely to be the
1304
+ case if y_score is continuous) for efficiency gains.
1305
+
1306
+ Returns
1307
+ -------
1308
+ discounted_cumulative_gain : ndarray of shape (n_samples,)
1309
+ The DCG score for each sample.
1310
+
1311
+ See Also
1312
+ --------
1313
+ ndcg_score : The Discounted Cumulative Gain divided by the Ideal Discounted
1314
+ Cumulative Gain (the DCG obtained for a perfect ranking), in order to
1315
+ have a score between 0 and 1.
1316
+ """
1317
+ discount = 1 / (np.log(np.arange(y_true.shape[1]) + 2) / np.log(log_base))
1318
+ if k is not None:
1319
+ discount[k:] = 0
1320
+ if ignore_ties:
1321
+ ranking = np.argsort(y_score)[:, ::-1]
1322
+ ranked = y_true[np.arange(ranking.shape[0])[:, np.newaxis], ranking]
1323
+ cumulative_gains = discount.dot(ranked.T)
1324
+ else:
1325
+ discount_cumsum = np.cumsum(discount)
1326
+ cumulative_gains = [
1327
+ _tie_averaged_dcg(y_t, y_s, discount_cumsum)
1328
+ for y_t, y_s in zip(y_true, y_score)
1329
+ ]
1330
+ cumulative_gains = np.asarray(cumulative_gains)
1331
+ return cumulative_gains
1332
+
1333
+
1334
+ def _tie_averaged_dcg(y_true, y_score, discount_cumsum):
1335
+ """
1336
+ Compute DCG by averaging over possible permutations of ties.
1337
+
1338
+ The gain (`y_true`) of an index falling inside a tied group (in the order
1339
+ induced by `y_score`) is replaced by the average gain within this group.
1340
+ The discounted gain for a tied group is then the average `y_true` within
1341
+ this group times the sum of discounts of the corresponding ranks.
1342
+
1343
+ This amounts to averaging scores for all possible orderings of the tied
1344
+ groups.
1345
+
1346
+ (note in the case of dcg@k the discount is 0 after index k)
1347
+
1348
+ Parameters
1349
+ ----------
1350
+ y_true : ndarray
1351
+ The true relevance scores.
1352
+
1353
+ y_score : ndarray
1354
+ Predicted scores.
1355
+
1356
+ discount_cumsum : ndarray
1357
+ Precomputed cumulative sum of the discounts.
1358
+
1359
+ Returns
1360
+ -------
1361
+ discounted_cumulative_gain : float
1362
+ The discounted cumulative gain.
1363
+
1364
+ References
1365
+ ----------
1366
+ McSherry, F., & Najork, M. (2008, March). Computing information retrieval
1367
+ performance measures efficiently in the presence of tied scores. In
1368
+ European conference on information retrieval (pp. 414-421). Springer,
1369
+ Berlin, Heidelberg.
1370
+ """
1371
+ _, inv, counts = np.unique(-y_score, return_inverse=True, return_counts=True)
1372
+ ranked = np.zeros(len(counts))
1373
+ np.add.at(ranked, inv, y_true)
1374
+ ranked /= counts
1375
+ groups = np.cumsum(counts) - 1
1376
+ discount_sums = np.empty(len(counts))
1377
+ discount_sums[0] = discount_cumsum[groups[0]]
1378
+ discount_sums[1:] = np.diff(discount_cumsum[groups])
1379
+ return (ranked * discount_sums).sum()
1380
+
1381
+
1382
+ def _check_dcg_target_type(y_true):
1383
+ y_type = type_of_target(y_true, input_name="y_true")
1384
+ supported_fmt = (
1385
+ "multilabel-indicator",
1386
+ "continuous-multioutput",
1387
+ "multiclass-multioutput",
1388
+ )
1389
+ if y_type not in supported_fmt:
1390
+ raise ValueError(
1391
+ "Only {} formats are supported. Got {} instead".format(
1392
+ supported_fmt, y_type
1393
+ )
1394
+ )
1395
+
1396
+
1397
+ def dcg_score(
1398
+ y_true, y_score, *, k=None, log_base=2, sample_weight=None, ignore_ties=False
1399
+ ):
1400
+ """Compute Discounted Cumulative Gain.
1401
+
1402
+ Sum the true scores ranked in the order induced by the predicted scores,
1403
+ after applying a logarithmic discount.
1404
+
1405
+ This ranking metric yields a high value if true labels are ranked high by
1406
+ ``y_score``.
1407
+
1408
+ Usually the Normalized Discounted Cumulative Gain (NDCG, computed by
1409
+ ndcg_score) is preferred.
1410
+
1411
+ Parameters
1412
+ ----------
1413
+ y_true : ndarray of shape (n_samples, n_labels)
1414
+ True targets of multilabel classification, or true scores of entities
1415
+ to be ranked.
1416
+
1417
+ y_score : ndarray of shape (n_samples, n_labels)
1418
+ Target scores, can either be probability estimates, confidence values,
1419
+ or non-thresholded measure of decisions (as returned by
1420
+ "decision_function" on some classifiers).
1421
+
1422
+ k : int, default=None
1423
+ Only consider the highest k scores in the ranking. If None, use all
1424
+ outputs.
1425
+
1426
+ log_base : float, default=2
1427
+ Base of the logarithm used for the discount. A low value means a
1428
+ sharper discount (top results are more important).
1429
+
1430
+ sample_weight : ndarray of shape (n_samples,), default=None
1431
+ Sample weights. If `None`, all samples are given the same weight.
1432
+
1433
+ ignore_ties : bool, default=False
1434
+ Assume that there are no ties in y_score (which is likely to be the
1435
+ case if y_score is continuous) for efficiency gains.
1436
+
1437
+ Returns
1438
+ -------
1439
+ discounted_cumulative_gain : float
1440
+ The averaged sample DCG scores.
1441
+
1442
+ See Also
1443
+ --------
1444
+ ndcg_score : The Discounted Cumulative Gain divided by the Ideal Discounted
1445
+ Cumulative Gain (the DCG obtained for a perfect ranking), in order to
1446
+ have a score between 0 and 1.
1447
+
1448
+ References
1449
+ ----------
1450
+ `Wikipedia entry for Discounted Cumulative Gain
1451
+ <https://en.wikipedia.org/wiki/Discounted_cumulative_gain>`_.
1452
+
1453
+ Jarvelin, K., & Kekalainen, J. (2002).
1454
+ Cumulated gain-based evaluation of IR techniques. ACM Transactions on
1455
+ Information Systems (TOIS), 20(4), 422-446.
1456
+
1457
+ Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May).
1458
+ A theoretical analysis of NDCG ranking measures. In Proceedings of the 26th
1459
+ Annual Conference on Learning Theory (COLT 2013).
1460
+
1461
+ McSherry, F., & Najork, M. (2008, March). Computing information retrieval
1462
+ performance measures efficiently in the presence of tied scores. In
1463
+ European conference on information retrieval (pp. 414-421). Springer,
1464
+ Berlin, Heidelberg.
1465
+
1466
+ Examples
1467
+ --------
1468
+ >>> import numpy as np
1469
+ >>> from sklearn.metrics import dcg_score
1470
+ >>> # we have groud-truth relevance of some answers to a query:
1471
+ >>> true_relevance = np.asarray([[10, 0, 0, 1, 5]])
1472
+ >>> # we predict scores for the answers
1473
+ >>> scores = np.asarray([[.1, .2, .3, 4, 70]])
1474
+ >>> dcg_score(true_relevance, scores)
1475
+ 9.49...
1476
+ >>> # we can set k to truncate the sum; only top k answers contribute
1477
+ >>> dcg_score(true_relevance, scores, k=2)
1478
+ 5.63...
1479
+ >>> # now we have some ties in our prediction
1480
+ >>> scores = np.asarray([[1, 0, 0, 0, 1]])
1481
+ >>> # by default ties are averaged, so here we get the average true
1482
+ >>> # relevance of our top predictions: (10 + 5) / 2 = 7.5
1483
+ >>> dcg_score(true_relevance, scores, k=1)
1484
+ 7.5
1485
+ >>> # we can choose to ignore ties for faster results, but only
1486
+ >>> # if we know there aren't ties in our scores, otherwise we get
1487
+ >>> # wrong results:
1488
+ >>> dcg_score(true_relevance,
1489
+ ... scores, k=1, ignore_ties=True)
1490
+ 5.0
1491
+ """
1492
+ y_true = check_array(y_true, ensure_2d=False)
1493
+ y_score = check_array(y_score, ensure_2d=False)
1494
+ check_consistent_length(y_true, y_score, sample_weight)
1495
+ _check_dcg_target_type(y_true)
1496
+ return np.average(
1497
+ _dcg_sample_scores(
1498
+ y_true, y_score, k=k, log_base=log_base, ignore_ties=ignore_ties
1499
+ ),
1500
+ weights=sample_weight,
1501
+ )
1502
+
1503
+
1504
+ def _ndcg_sample_scores(y_true, y_score, k=None, ignore_ties=False):
1505
+ """Compute Normalized Discounted Cumulative Gain.
1506
+
1507
+ Sum the true scores ranked in the order induced by the predicted scores,
1508
+ after applying a logarithmic discount. Then divide by the best possible
1509
+ score (Ideal DCG, obtained for a perfect ranking) to obtain a score between
1510
+ 0 and 1.
1511
+
1512
+ This ranking metric yields a high value if true labels are ranked high by
1513
+ ``y_score``.
1514
+
1515
+ Parameters
1516
+ ----------
1517
+ y_true : ndarray of shape (n_samples, n_labels)
1518
+ True targets of multilabel classification, or true scores of entities
1519
+ to be ranked.
1520
+
1521
+ y_score : ndarray of shape (n_samples, n_labels)
1522
+ Target scores, can either be probability estimates, confidence values,
1523
+ or non-thresholded measure of decisions (as returned by
1524
+ "decision_function" on some classifiers).
1525
+
1526
+ k : int, default=None
1527
+ Only consider the highest k scores in the ranking. If None, use all
1528
+ outputs.
1529
+
1530
+ ignore_ties : bool, default=False
1531
+ Assume that there are no ties in y_score (which is likely to be the
1532
+ case if y_score is continuous) for efficiency gains.
1533
+
1534
+ Returns
1535
+ -------
1536
+ normalized_discounted_cumulative_gain : ndarray of shape (n_samples,)
1537
+ The NDCG score for each sample (float in [0., 1.]).
1538
+
1539
+ See Also
1540
+ --------
1541
+ dcg_score : Discounted Cumulative Gain (not normalized).
1542
+
1543
+ """
1544
+ gain = _dcg_sample_scores(y_true, y_score, k, ignore_ties=ignore_ties)
1545
+ # Here we use the order induced by y_true so we can ignore ties since
1546
+ # the gain associated to tied indices is the same (permuting ties doesn't
1547
+ # change the value of the re-ordered y_true)
1548
+ normalizing_gain = _dcg_sample_scores(y_true, y_true, k, ignore_ties=True)
1549
+ all_irrelevant = normalizing_gain == 0
1550
+ gain[all_irrelevant] = 0
1551
+ gain[~all_irrelevant] /= normalizing_gain[~all_irrelevant]
1552
+ return gain
1553
+
1554
+
1555
+ def ndcg_score(y_true, y_score, *, k=None, sample_weight=None, ignore_ties=False):
1556
+ """Compute Normalized Discounted Cumulative Gain.
1557
+
1558
+ Sum the true scores ranked in the order induced by the predicted scores,
1559
+ after applying a logarithmic discount. Then divide by the best possible
1560
+ score (Ideal DCG, obtained for a perfect ranking) to obtain a score between
1561
+ 0 and 1.
1562
+
1563
+ This ranking metric returns a high value if true labels are ranked high by
1564
+ ``y_score``.
1565
+
1566
+ Parameters
1567
+ ----------
1568
+ y_true : ndarray of shape (n_samples, n_labels)
1569
+ True targets of multilabel classification, or true scores of entities
1570
+ to be ranked. Negative values in `y_true` may result in an output
1571
+ that is not between 0 and 1.
1572
+
1573
+ .. versionchanged:: 1.2
1574
+ These negative values are deprecated, and will raise an error in v1.4.
1575
+
1576
+ y_score : ndarray of shape (n_samples, n_labels)
1577
+ Target scores, can either be probability estimates, confidence values,
1578
+ or non-thresholded measure of decisions (as returned by
1579
+ "decision_function" on some classifiers).
1580
+
1581
+ k : int, default=None
1582
+ Only consider the highest k scores in the ranking. If `None`, use all
1583
+ outputs.
1584
+
1585
+ sample_weight : ndarray of shape (n_samples,), default=None
1586
+ Sample weights. If `None`, all samples are given the same weight.
1587
+
1588
+ ignore_ties : bool, default=False
1589
+ Assume that there are no ties in y_score (which is likely to be the
1590
+ case if y_score is continuous) for efficiency gains.
1591
+
1592
+ Returns
1593
+ -------
1594
+ normalized_discounted_cumulative_gain : float in [0., 1.]
1595
+ The averaged NDCG scores for all samples.
1596
+
1597
+ See Also
1598
+ --------
1599
+ dcg_score : Discounted Cumulative Gain (not normalized).
1600
+
1601
+ References
1602
+ ----------
1603
+ `Wikipedia entry for Discounted Cumulative Gain
1604
+ <https://en.wikipedia.org/wiki/Discounted_cumulative_gain>`_
1605
+
1606
+ Jarvelin, K., & Kekalainen, J. (2002).
1607
+ Cumulated gain-based evaluation of IR techniques. ACM Transactions on
1608
+ Information Systems (TOIS), 20(4), 422-446.
1609
+
1610
+ Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May).
1611
+ A theoretical analysis of NDCG ranking measures. In Proceedings of the 26th
1612
+ Annual Conference on Learning Theory (COLT 2013)
1613
+
1614
+ McSherry, F., & Najork, M. (2008, March). Computing information retrieval
1615
+ performance measures efficiently in the presence of tied scores. In
1616
+ European conference on information retrieval (pp. 414-421). Springer,
1617
+ Berlin, Heidelberg.
1618
+
1619
+ Examples
1620
+ --------
1621
+ >>> import numpy as np
1622
+ >>> from sklearn.metrics import ndcg_score
1623
+ >>> # we have groud-truth relevance of some answers to a query:
1624
+ >>> true_relevance = np.asarray([[10, 0, 0, 1, 5]])
1625
+ >>> # we predict some scores (relevance) for the answers
1626
+ >>> scores = np.asarray([[.1, .2, .3, 4, 70]])
1627
+ >>> ndcg_score(true_relevance, scores)
1628
+ 0.69...
1629
+ >>> scores = np.asarray([[.05, 1.1, 1., .5, .0]])
1630
+ >>> ndcg_score(true_relevance, scores)
1631
+ 0.49...
1632
+ >>> # we can set k to truncate the sum; only top k answers contribute.
1633
+ >>> ndcg_score(true_relevance, scores, k=4)
1634
+ 0.35...
1635
+ >>> # the normalization takes k into account so a perfect answer
1636
+ >>> # would still get 1.0
1637
+ >>> ndcg_score(true_relevance, true_relevance, k=4)
1638
+ 1.0...
1639
+ >>> # now we have some ties in our prediction
1640
+ >>> scores = np.asarray([[1, 0, 0, 0, 1]])
1641
+ >>> # by default ties are averaged, so here we get the average (normalized)
1642
+ >>> # true relevance of our top predictions: (10 / 10 + 5 / 10) / 2 = .75
1643
+ >>> ndcg_score(true_relevance, scores, k=1)
1644
+ 0.75...
1645
+ >>> # we can choose to ignore ties for faster results, but only
1646
+ >>> # if we know there aren't ties in our scores, otherwise we get
1647
+ >>> # wrong results:
1648
+ >>> ndcg_score(true_relevance,
1649
+ ... scores, k=1, ignore_ties=True)
1650
+ 0.5...
1651
+ """
1652
+ y_true = check_array(y_true, ensure_2d=False)
1653
+ y_score = check_array(y_score, ensure_2d=False)
1654
+ check_consistent_length(y_true, y_score, sample_weight)
1655
+
1656
+ if y_true.min() < 0:
1657
+ # TODO(1.4): Replace warning w/ ValueError
1658
+ warnings.warn(
1659
+ "ndcg_score should not be used on negative y_true values. ndcg_score will"
1660
+ " raise a ValueError on negative y_true values starting from version 1.4.",
1661
+ FutureWarning,
1662
+ )
1663
+ _check_dcg_target_type(y_true)
1664
+ gain = _ndcg_sample_scores(y_true, y_score, k=k, ignore_ties=ignore_ties)
1665
+ return np.average(gain, weights=sample_weight)
1666
+
1667
+
1668
+ def top_k_accuracy_score(
1669
+ y_true, y_score, *, k=2, normalize=True, sample_weight=None, labels=None
1670
+ ):
1671
+ """Top-k Accuracy classification score.
1672
+
1673
+ This metric computes the number of times where the correct label is among
1674
+ the top `k` labels predicted (ranked by predicted scores). Note that the
1675
+ multilabel case isn't covered here.
1676
+
1677
+ Read more in the :ref:`User Guide <top_k_accuracy_score>`
1678
+
1679
+ Parameters
1680
+ ----------
1681
+ y_true : array-like of shape (n_samples,)
1682
+ True labels.
1683
+
1684
+ y_score : array-like of shape (n_samples,) or (n_samples, n_classes)
1685
+ Target scores. These can be either probability estimates or
1686
+ non-thresholded decision values (as returned by
1687
+ :term:`decision_function` on some classifiers).
1688
+ The binary case expects scores with shape (n_samples,) while the
1689
+ multiclass case expects scores with shape (n_samples, n_classes).
1690
+ In the multiclass case, the order of the class scores must
1691
+ correspond to the order of ``labels``, if provided, or else to
1692
+ the numerical or lexicographical order of the labels in ``y_true``.
1693
+ If ``y_true`` does not contain all the labels, ``labels`` must be
1694
+ provided.
1695
+
1696
+ k : int, default=2
1697
+ Number of most likely outcomes considered to find the correct label.
1698
+
1699
+ normalize : bool, default=True
1700
+ If `True`, return the fraction of correctly classified samples.
1701
+ Otherwise, return the number of correctly classified samples.
1702
+
1703
+ sample_weight : array-like of shape (n_samples,), default=None
1704
+ Sample weights. If `None`, all samples are given the same weight.
1705
+
1706
+ labels : array-like of shape (n_classes,), default=None
1707
+ Multiclass only. List of labels that index the classes in ``y_score``.
1708
+ If ``None``, the numerical or lexicographical order of the labels in
1709
+ ``y_true`` is used. If ``y_true`` does not contain all the labels,
1710
+ ``labels`` must be provided.
1711
+
1712
+ Returns
1713
+ -------
1714
+ score : float
1715
+ The top-k accuracy score. The best performance is 1 with
1716
+ `normalize == True` and the number of samples with
1717
+ `normalize == False`.
1718
+
1719
+ See Also
1720
+ --------
1721
+ accuracy_score : Compute the accuracy score. By default, the function will
1722
+ return the fraction of correct predictions divided by the total number
1723
+ of predictions.
1724
+
1725
+ Notes
1726
+ -----
1727
+ In cases where two or more labels are assigned equal predicted scores,
1728
+ the labels with the highest indices will be chosen first. This might
1729
+ impact the result if the correct label falls after the threshold because
1730
+ of that.
1731
+
1732
+ Examples
1733
+ --------
1734
+ >>> import numpy as np
1735
+ >>> from sklearn.metrics import top_k_accuracy_score
1736
+ >>> y_true = np.array([0, 1, 2, 2])
1737
+ >>> y_score = np.array([[0.5, 0.2, 0.2], # 0 is in top 2
1738
+ ... [0.3, 0.4, 0.2], # 1 is in top 2
1739
+ ... [0.2, 0.4, 0.3], # 2 is in top 2
1740
+ ... [0.7, 0.2, 0.1]]) # 2 isn't in top 2
1741
+ >>> top_k_accuracy_score(y_true, y_score, k=2)
1742
+ 0.75
1743
+ >>> # Not normalizing gives the number of "correctly" classified samples
1744
+ >>> top_k_accuracy_score(y_true, y_score, k=2, normalize=False)
1745
+ 3
1746
+ """
1747
+ y_true = check_array(y_true, ensure_2d=False, dtype=None)
1748
+ y_true = column_or_1d(y_true)
1749
+ y_type = type_of_target(y_true, input_name="y_true")
1750
+ if y_type == "binary" and labels is not None and len(labels) > 2:
1751
+ y_type = "multiclass"
1752
+ if y_type not in {"binary", "multiclass"}:
1753
+ raise ValueError(
1754
+ f"y type must be 'binary' or 'multiclass', got '{y_type}' instead."
1755
+ )
1756
+ y_score = check_array(y_score, ensure_2d=False)
1757
+ if y_type == "binary":
1758
+ if y_score.ndim == 2 and y_score.shape[1] != 1:
1759
+ raise ValueError(
1760
+ "`y_true` is binary while y_score is 2d with"
1761
+ f" {y_score.shape[1]} classes. If `y_true` does not contain all the"
1762
+ " labels, `labels` must be provided."
1763
+ )
1764
+ y_score = column_or_1d(y_score)
1765
+
1766
+ check_consistent_length(y_true, y_score, sample_weight)
1767
+ y_score_n_classes = y_score.shape[1] if y_score.ndim == 2 else 2
1768
+
1769
+ if labels is None:
1770
+ classes = _unique(y_true)
1771
+ n_classes = len(classes)
1772
+
1773
+ if n_classes != y_score_n_classes:
1774
+ raise ValueError(
1775
+ f"Number of classes in 'y_true' ({n_classes}) not equal "
1776
+ f"to the number of classes in 'y_score' ({y_score_n_classes})."
1777
+ "You can provide a list of all known classes by assigning it "
1778
+ "to the `labels` parameter."
1779
+ )
1780
+ else:
1781
+ labels = column_or_1d(labels)
1782
+ classes = _unique(labels)
1783
+ n_labels = len(labels)
1784
+ n_classes = len(classes)
1785
+
1786
+ if n_classes != n_labels:
1787
+ raise ValueError("Parameter 'labels' must be unique.")
1788
+
1789
+ if not np.array_equal(classes, labels):
1790
+ raise ValueError("Parameter 'labels' must be ordered.")
1791
+
1792
+ if n_classes != y_score_n_classes:
1793
+ raise ValueError(
1794
+ f"Number of given labels ({n_classes}) not equal to the "
1795
+ f"number of classes in 'y_score' ({y_score_n_classes})."
1796
+ )
1797
+
1798
+ if len(np.setdiff1d(y_true, classes)):
1799
+ raise ValueError("'y_true' contains labels not in parameter 'labels'.")
1800
+
1801
+ if k >= n_classes:
1802
+ warnings.warn(
1803
+ f"'k' ({k}) greater than or equal to 'n_classes' ({n_classes}) "
1804
+ "will result in a perfect score and is therefore meaningless.",
1805
+ UndefinedMetricWarning,
1806
+ )
1807
+
1808
+ y_true_encoded = _encode(y_true, uniques=classes)
1809
+
1810
+ if y_type == "binary":
1811
+ if k == 1:
1812
+ threshold = 0.5 if y_score.min() >= 0 and y_score.max() <= 1 else 0
1813
+ y_pred = (y_score > threshold).astype(np.int64)
1814
+ hits = y_pred == y_true_encoded
1815
+ else:
1816
+ hits = np.ones_like(y_score, dtype=np.bool_)
1817
+ elif y_type == "multiclass":
1818
+ sorted_pred = np.argsort(y_score, axis=1, kind="mergesort")[:, ::-1]
1819
+ hits = (y_true_encoded == sorted_pred[:, :k].T).any(axis=0)
1820
+
1821
+ if normalize:
1822
+ return np.average(hits, weights=sample_weight)
1823
+ elif sample_weight is None:
1824
+ return np.sum(hits)
1825
+ else:
1826
+ return np.dot(hits, sample_weight)
videollama2/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f61b3136021cc79f20389c80b3c58dc74558c0604ae25ee04ebbe6bdd3db52b0
3
+ size 241201
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_available_if.cpython-310.pyc ADDED
Binary file (2.92 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_encode.cpython-310.pyc ADDED
Binary file (10.2 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_mask.cpython-310.pyc ADDED
Binary file (1.65 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_mocking.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_set_output.cpython-310.pyc ADDED
Binary file (7.71 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_show_versions.cpython-310.pyc ADDED
Binary file (2.27 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_tags.cpython-310.pyc ADDED
Binary file (1.98 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_testing.cpython-310.pyc ADDED
Binary file (30.7 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/deprecation.cpython-310.pyc ADDED
Binary file (3.3 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/estimator_checks.cpython-310.pyc ADDED
Binary file (94.6 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/extmath.cpython-310.pyc ADDED
Binary file (33.8 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/fixes.cpython-310.pyc ADDED
Binary file (5.53 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/graph.cpython-310.pyc ADDED
Binary file (4.64 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/multiclass.cpython-310.pyc ADDED
Binary file (14.1 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/optimize.cpython-310.pyc ADDED
Binary file (5.96 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/stats.cpython-310.pyc ADDED
Binary file (2.13 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/validation.cpython-310.pyc ADDED
Binary file (57.9 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/_estimator_html_repr.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import closing
2
+ from io import StringIO
3
+ from inspect import isclass
4
+ from string import Template
5
+ import html
6
+
7
+ from .. import config_context
8
+
9
+
10
+ class _IDCounter:
11
+ """Generate sequential ids with a prefix."""
12
+
13
+ def __init__(self, prefix):
14
+ self.prefix = prefix
15
+ self.count = 0
16
+
17
+ def get_id(self):
18
+ self.count += 1
19
+ return f"{self.prefix}-{self.count}"
20
+
21
+
22
+ _CONTAINER_ID_COUNTER = _IDCounter("sk-container-id")
23
+ _ESTIMATOR_ID_COUNTER = _IDCounter("sk-estimator-id")
24
+
25
+
26
+ class _VisualBlock:
27
+ """HTML Representation of Estimator
28
+
29
+ Parameters
30
+ ----------
31
+ kind : {'serial', 'parallel', 'single'}
32
+ kind of HTML block
33
+
34
+ estimators : list of estimators or `_VisualBlock`s or a single estimator
35
+ If kind != 'single', then `estimators` is a list of
36
+ estimators.
37
+ If kind == 'single', then `estimators` is a single estimator.
38
+
39
+ names : list of str, default=None
40
+ If kind != 'single', then `names` corresponds to estimators.
41
+ If kind == 'single', then `names` is a single string corresponding to
42
+ the single estimator.
43
+
44
+ name_details : list of str, str, or None, default=None
45
+ If kind != 'single', then `name_details` corresponds to `names`.
46
+ If kind == 'single', then `name_details` is a single string
47
+ corresponding to the single estimator.
48
+
49
+ dash_wrapped : bool, default=True
50
+ If true, wrapped HTML element will be wrapped with a dashed border.
51
+ Only active when kind != 'single'.
52
+ """
53
+
54
+ def __init__(
55
+ self, kind, estimators, *, names=None, name_details=None, dash_wrapped=True
56
+ ):
57
+ self.kind = kind
58
+ self.estimators = estimators
59
+ self.dash_wrapped = dash_wrapped
60
+
61
+ if self.kind in ("parallel", "serial"):
62
+ if names is None:
63
+ names = (None,) * len(estimators)
64
+ if name_details is None:
65
+ name_details = (None,) * len(estimators)
66
+
67
+ self.names = names
68
+ self.name_details = name_details
69
+
70
+ def _sk_visual_block_(self):
71
+ return self
72
+
73
+
74
+ def _write_label_html(
75
+ out,
76
+ name,
77
+ name_details,
78
+ outer_class="sk-label-container",
79
+ inner_class="sk-label",
80
+ checked=False,
81
+ ):
82
+ """Write labeled html with or without a dropdown with named details"""
83
+ out.write(f'<div class="{outer_class}"><div class="{inner_class} sk-toggleable">')
84
+ name = html.escape(name)
85
+
86
+ if name_details is not None:
87
+ name_details = html.escape(str(name_details))
88
+ label_class = "sk-toggleable__label sk-toggleable__label-arrow"
89
+
90
+ checked_str = "checked" if checked else ""
91
+ est_id = _ESTIMATOR_ID_COUNTER.get_id()
92
+ out.write(
93
+ '<input class="sk-toggleable__control sk-hidden--visually" '
94
+ f'id="{est_id}" type="checkbox" {checked_str}>'
95
+ f'<label for="{est_id}" class="{label_class}">{name}</label>'
96
+ f'<div class="sk-toggleable__content"><pre>{name_details}'
97
+ "</pre></div>"
98
+ )
99
+ else:
100
+ out.write(f"<label>{name}</label>")
101
+ out.write("</div></div>") # outer_class inner_class
102
+
103
+
104
+ def _get_visual_block(estimator):
105
+ """Generate information about how to display an estimator."""
106
+ if hasattr(estimator, "_sk_visual_block_"):
107
+ try:
108
+ return estimator._sk_visual_block_()
109
+ except Exception:
110
+ return _VisualBlock(
111
+ "single",
112
+ estimator,
113
+ names=estimator.__class__.__name__,
114
+ name_details=str(estimator),
115
+ )
116
+
117
+ if isinstance(estimator, str):
118
+ return _VisualBlock(
119
+ "single", estimator, names=estimator, name_details=estimator
120
+ )
121
+ elif estimator is None:
122
+ return _VisualBlock("single", estimator, names="None", name_details="None")
123
+
124
+ # check if estimator looks like a meta estimator wraps estimators
125
+ if hasattr(estimator, "get_params") and not isclass(estimator):
126
+ estimators = [
127
+ (key, est)
128
+ for key, est in estimator.get_params(deep=False).items()
129
+ if hasattr(est, "get_params") and hasattr(est, "fit") and not isclass(est)
130
+ ]
131
+ if estimators:
132
+ return _VisualBlock(
133
+ "parallel",
134
+ [est for _, est in estimators],
135
+ names=[f"{key}: {est.__class__.__name__}" for key, est in estimators],
136
+ name_details=[str(est) for _, est in estimators],
137
+ )
138
+
139
+ return _VisualBlock(
140
+ "single",
141
+ estimator,
142
+ names=estimator.__class__.__name__,
143
+ name_details=str(estimator),
144
+ )
145
+
146
+
147
+ def _write_estimator_html(
148
+ out, estimator, estimator_label, estimator_label_details, first_call=False
149
+ ):
150
+ """Write estimator to html in serial, parallel, or by itself (single)."""
151
+ if first_call:
152
+ est_block = _get_visual_block(estimator)
153
+ else:
154
+ with config_context(print_changed_only=True):
155
+ est_block = _get_visual_block(estimator)
156
+
157
+ if est_block.kind in ("serial", "parallel"):
158
+ dashed_wrapped = first_call or est_block.dash_wrapped
159
+ dash_cls = " sk-dashed-wrapped" if dashed_wrapped else ""
160
+ out.write(f'<div class="sk-item{dash_cls}">')
161
+
162
+ if estimator_label:
163
+ _write_label_html(out, estimator_label, estimator_label_details)
164
+
165
+ kind = est_block.kind
166
+ out.write(f'<div class="sk-{kind}">')
167
+ est_infos = zip(est_block.estimators, est_block.names, est_block.name_details)
168
+
169
+ for est, name, name_details in est_infos:
170
+ if kind == "serial":
171
+ _write_estimator_html(out, est, name, name_details)
172
+ else: # parallel
173
+ out.write('<div class="sk-parallel-item">')
174
+ # wrap element in a serial visualblock
175
+ serial_block = _VisualBlock("serial", [est], dash_wrapped=False)
176
+ _write_estimator_html(out, serial_block, name, name_details)
177
+ out.write("</div>") # sk-parallel-item
178
+
179
+ out.write("</div></div>")
180
+ elif est_block.kind == "single":
181
+ _write_label_html(
182
+ out,
183
+ est_block.names,
184
+ est_block.name_details,
185
+ outer_class="sk-item",
186
+ inner_class="sk-estimator",
187
+ checked=first_call,
188
+ )
189
+
190
+
191
+ _STYLE = """
192
+ #$id {
193
+ color: black;
194
+ background-color: white;
195
+ }
196
+ #$id pre{
197
+ padding: 0;
198
+ }
199
+ #$id div.sk-toggleable {
200
+ background-color: white;
201
+ }
202
+ #$id label.sk-toggleable__label {
203
+ cursor: pointer;
204
+ display: block;
205
+ width: 100%;
206
+ margin-bottom: 0;
207
+ padding: 0.3em;
208
+ box-sizing: border-box;
209
+ text-align: center;
210
+ }
211
+ #$id label.sk-toggleable__label-arrow:before {
212
+ content: "▸";
213
+ float: left;
214
+ margin-right: 0.25em;
215
+ color: #696969;
216
+ }
217
+ #$id label.sk-toggleable__label-arrow:hover:before {
218
+ color: black;
219
+ }
220
+ #$id div.sk-estimator:hover label.sk-toggleable__label-arrow:before {
221
+ color: black;
222
+ }
223
+ #$id div.sk-toggleable__content {
224
+ max-height: 0;
225
+ max-width: 0;
226
+ overflow: hidden;
227
+ text-align: left;
228
+ background-color: #f0f8ff;
229
+ }
230
+ #$id div.sk-toggleable__content pre {
231
+ margin: 0.2em;
232
+ color: black;
233
+ border-radius: 0.25em;
234
+ background-color: #f0f8ff;
235
+ }
236
+ #$id input.sk-toggleable__control:checked~div.sk-toggleable__content {
237
+ max-height: 200px;
238
+ max-width: 100%;
239
+ overflow: auto;
240
+ }
241
+ #$id input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {
242
+ content: "▾";
243
+ }
244
+ #$id div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {
245
+ background-color: #d4ebff;
246
+ }
247
+ #$id div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {
248
+ background-color: #d4ebff;
249
+ }
250
+ #$id input.sk-hidden--visually {
251
+ border: 0;
252
+ clip: rect(1px 1px 1px 1px);
253
+ clip: rect(1px, 1px, 1px, 1px);
254
+ height: 1px;
255
+ margin: -1px;
256
+ overflow: hidden;
257
+ padding: 0;
258
+ position: absolute;
259
+ width: 1px;
260
+ }
261
+ #$id div.sk-estimator {
262
+ font-family: monospace;
263
+ background-color: #f0f8ff;
264
+ border: 1px dotted black;
265
+ border-radius: 0.25em;
266
+ box-sizing: border-box;
267
+ margin-bottom: 0.5em;
268
+ }
269
+ #$id div.sk-estimator:hover {
270
+ background-color: #d4ebff;
271
+ }
272
+ #$id div.sk-parallel-item::after {
273
+ content: "";
274
+ width: 100%;
275
+ border-bottom: 1px solid gray;
276
+ flex-grow: 1;
277
+ }
278
+ #$id div.sk-label:hover label.sk-toggleable__label {
279
+ background-color: #d4ebff;
280
+ }
281
+ #$id div.sk-serial::before {
282
+ content: "";
283
+ position: absolute;
284
+ border-left: 1px solid gray;
285
+ box-sizing: border-box;
286
+ top: 0;
287
+ bottom: 0;
288
+ left: 50%;
289
+ z-index: 0;
290
+ }
291
+ #$id div.sk-serial {
292
+ display: flex;
293
+ flex-direction: column;
294
+ align-items: center;
295
+ background-color: white;
296
+ padding-right: 0.2em;
297
+ padding-left: 0.2em;
298
+ position: relative;
299
+ }
300
+ #$id div.sk-item {
301
+ position: relative;
302
+ z-index: 1;
303
+ }
304
+ #$id div.sk-parallel {
305
+ display: flex;
306
+ align-items: stretch;
307
+ justify-content: center;
308
+ background-color: white;
309
+ position: relative;
310
+ }
311
+ #$id div.sk-item::before, #$id div.sk-parallel-item::before {
312
+ content: "";
313
+ position: absolute;
314
+ border-left: 1px solid gray;
315
+ box-sizing: border-box;
316
+ top: 0;
317
+ bottom: 0;
318
+ left: 50%;
319
+ z-index: -1;
320
+ }
321
+ #$id div.sk-parallel-item {
322
+ display: flex;
323
+ flex-direction: column;
324
+ z-index: 1;
325
+ position: relative;
326
+ background-color: white;
327
+ }
328
+ #$id div.sk-parallel-item:first-child::after {
329
+ align-self: flex-end;
330
+ width: 50%;
331
+ }
332
+ #$id div.sk-parallel-item:last-child::after {
333
+ align-self: flex-start;
334
+ width: 50%;
335
+ }
336
+ #$id div.sk-parallel-item:only-child::after {
337
+ width: 0;
338
+ }
339
+ #$id div.sk-dashed-wrapped {
340
+ border: 1px dashed gray;
341
+ margin: 0 0.4em 0.5em 0.4em;
342
+ box-sizing: border-box;
343
+ padding-bottom: 0.4em;
344
+ background-color: white;
345
+ }
346
+ #$id div.sk-label label {
347
+ font-family: monospace;
348
+ font-weight: bold;
349
+ display: inline-block;
350
+ line-height: 1.2em;
351
+ }
352
+ #$id div.sk-label-container {
353
+ text-align: center;
354
+ }
355
+ #$id div.sk-container {
356
+ /* jupyter's `normalize.less` sets `[hidden] { display: none; }`
357
+ but bootstrap.min.css set `[hidden] { display: none !important; }`
358
+ so we also need the `!important` here to be able to override the
359
+ default hidden behavior on the sphinx rendered scikit-learn.org.
360
+ See: https://github.com/scikit-learn/scikit-learn/issues/21755 */
361
+ display: inline-block !important;
362
+ position: relative;
363
+ }
364
+ #$id div.sk-text-repr-fallback {
365
+ display: none;
366
+ }
367
+ """.replace(
368
+ " ", ""
369
+ ).replace(
370
+ "\n", ""
371
+ ) # noqa
372
+
373
+
374
+ def estimator_html_repr(estimator):
375
+ """Build a HTML representation of an estimator.
376
+
377
+ Read more in the :ref:`User Guide <visualizing_composite_estimators>`.
378
+
379
+ Parameters
380
+ ----------
381
+ estimator : estimator object
382
+ The estimator to visualize.
383
+
384
+ Returns
385
+ -------
386
+ html: str
387
+ HTML representation of estimator.
388
+ """
389
+ with closing(StringIO()) as out:
390
+ container_id = _CONTAINER_ID_COUNTER.get_id()
391
+ style_template = Template(_STYLE)
392
+ style_with_id = style_template.substitute(id=container_id)
393
+ estimator_str = str(estimator)
394
+
395
+ # The fallback message is shown by default and loading the CSS sets
396
+ # div.sk-text-repr-fallback to display: none to hide the fallback message.
397
+ #
398
+ # If the notebook is trusted, the CSS is loaded which hides the fallback
399
+ # message. If the notebook is not trusted, then the CSS is not loaded and the
400
+ # fallback message is shown by default.
401
+ #
402
+ # The reverse logic applies to HTML repr div.sk-container.
403
+ # div.sk-container is hidden by default and the loading the CSS displays it.
404
+ fallback_msg = (
405
+ "In a Jupyter environment, please rerun this cell to show the HTML"
406
+ " representation or trust the notebook. <br />On GitHub, the"
407
+ " HTML representation is unable to render, please try loading this page"
408
+ " with nbviewer.org."
409
+ )
410
+ out.write(
411
+ f"<style>{style_with_id}</style>"
412
+ f'<div id="{container_id}" class="sk-top-container">'
413
+ '<div class="sk-text-repr-fallback">'
414
+ f"<pre>{html.escape(estimator_str)}</pre><b>{fallback_msg}</b>"
415
+ "</div>"
416
+ '<div class="sk-container" hidden>'
417
+ )
418
+ _write_estimator_html(
419
+ out,
420
+ estimator,
421
+ estimator.__class__.__name__,
422
+ estimator_str,
423
+ first_call=True,
424
+ )
425
+ out.write("</div></div>")
426
+
427
+ html_output = out.getvalue()
428
+ return html_output
videollama2/lib/python3.10/site-packages/sklearn/utils/_fast_dict.pxd ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Author: Gael Varoquaux
2
+ # License: BSD
3
+ """
4
+ Uses C++ map containers for fast dict-like behavior with keys being
5
+ integers, and values float.
6
+ """
7
+
8
+ from libcpp.map cimport map as cpp_map
9
+
10
+ # Import the C-level symbols of numpy
11
+ cimport numpy as cnp
12
+
13
+ ctypedef cnp.float64_t DTYPE_t
14
+
15
+ ctypedef cnp.intp_t ITYPE_t
16
+
17
+ ###############################################################################
18
+ # An object to be used in Python
19
+
20
+ cdef class IntFloatDict:
21
+ cdef cpp_map[ITYPE_t, DTYPE_t] my_map
22
+ cdef _to_arrays(self, ITYPE_t [:] keys, DTYPE_t [:] values)
videollama2/lib/python3.10/site-packages/sklearn/utils/_isfinite.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6297f649f6414e2131de7a03bcbf7cea238832bb3bd1a13bfce9469a7aa2346d
3
+ size 253625
videollama2/lib/python3.10/site-packages/sklearn/utils/_random.pxd ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors: Arnaud Joly
2
+ #
3
+ # License: BSD 3 clause
4
+
5
+
6
+ cimport numpy as cnp
7
+ ctypedef cnp.npy_uint32 UINT32_t
8
+
9
+ cdef inline UINT32_t DEFAULT_SEED = 1
10
+
11
+ cdef enum:
12
+ # Max value for our rand_r replacement (near the bottom).
13
+ # We don't use RAND_MAX because it's different across platforms and
14
+ # particularly tiny on Windows/MSVC.
15
+ # It corresponds to the maximum representable value for
16
+ # 32-bit signed integers (i.e. 2^31 - 1).
17
+ RAND_R_MAX = 0x7FFFFFFF
18
+
19
+ cpdef sample_without_replacement(cnp.int_t n_population,
20
+ cnp.int_t n_samples,
21
+ method=*,
22
+ random_state=*)
23
+
24
+ # rand_r replacement using a 32bit XorShift generator
25
+ # See http://www.jstatsoft.org/v08/i14/paper for details
26
+ cdef inline UINT32_t our_rand_r(UINT32_t* seed) nogil:
27
+ """Generate a pseudo-random np.uint32 from a np.uint32 seed"""
28
+ # seed shouldn't ever be 0.
29
+ if (seed[0] == 0): seed[0] = DEFAULT_SEED
30
+
31
+ seed[0] ^= <UINT32_t>(seed[0] << 13)
32
+ seed[0] ^= <UINT32_t>(seed[0] >> 17)
33
+ seed[0] ^= <UINT32_t>(seed[0] << 5)
34
+
35
+ # Use the modulo to make sure that we don't return a values greater than the
36
+ # maximum representable value for signed 32bit integers (i.e. 2^31 - 1).
37
+ # Note that the parenthesis are needed to avoid overflow: here
38
+ # RAND_R_MAX is cast to UINT32_t before 1 is added.
39
+ return seed[0] % ((<UINT32_t>RAND_R_MAX) + 1)
videollama2/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.pxd ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #------------------------------------------------------------------------------
3
+
4
+ """
5
+ Dataset abstractions for sequential data access.
6
+ WARNING: Do not edit .pxd file directly, it is generated from .pxd.tp
7
+ """
8
+
9
+ cimport numpy as cnp
10
+
11
+ # SequentialDataset and its two concrete subclasses are (optionally randomized)
12
+ # iterators over the rows of a matrix X and corresponding target values y.
13
+
14
+
15
+ cdef class SequentialDataset64:
16
+ cdef int current_index
17
+ cdef cnp.ndarray index
18
+ cdef int *index_data_ptr
19
+ cdef Py_ssize_t n_samples
20
+ cdef cnp.uint32_t seed
21
+
22
+ cdef void shuffle(self, cnp.uint32_t seed) nogil
23
+ cdef int _get_next_index(self) nogil
24
+ cdef int _get_random_index(self) nogil
25
+
26
+ cdef void _sample(self, double **x_data_ptr, int **x_ind_ptr,
27
+ int *nnz, double *y, double *sample_weight,
28
+ int current_index) nogil
29
+ cdef void next(self, double **x_data_ptr, int **x_ind_ptr,
30
+ int *nnz, double *y, double *sample_weight) nogil
31
+ cdef int random(self, double **x_data_ptr, int **x_ind_ptr,
32
+ int *nnz, double *y, double *sample_weight) nogil
33
+
34
+
35
+ cdef class ArrayDataset64(SequentialDataset64):
36
+ cdef cnp.ndarray X
37
+ cdef cnp.ndarray Y
38
+ cdef cnp.ndarray sample_weights
39
+ cdef Py_ssize_t n_features
40
+ cdef cnp.npy_intp X_stride
41
+ cdef double *X_data_ptr
42
+ cdef double *Y_data_ptr
43
+ cdef cnp.ndarray feature_indices
44
+ cdef int *feature_indices_ptr
45
+ cdef double *sample_weight_data
46
+
47
+
48
+ cdef class CSRDataset64(SequentialDataset64):
49
+ cdef cnp.ndarray X_data
50
+ cdef cnp.ndarray X_indptr
51
+ cdef cnp.ndarray X_indices
52
+ cdef cnp.ndarray Y
53
+ cdef cnp.ndarray sample_weights
54
+ cdef double *X_data_ptr
55
+ cdef int *X_indptr_ptr
56
+ cdef int *X_indices_ptr
57
+ cdef double *Y_data_ptr
58
+ cdef double *sample_weight_data
59
+
60
+ #------------------------------------------------------------------------------
61
+
62
+ """
63
+ Dataset abstractions for sequential data access.
64
+ WARNING: Do not edit .pxd file directly, it is generated from .pxd.tp
65
+ """
66
+
67
+ cimport numpy as cnp
68
+
69
+ # SequentialDataset and its two concrete subclasses are (optionally randomized)
70
+ # iterators over the rows of a matrix X and corresponding target values y.
71
+
72
+
73
+ cdef class SequentialDataset32:
74
+ cdef int current_index
75
+ cdef cnp.ndarray index
76
+ cdef int *index_data_ptr
77
+ cdef Py_ssize_t n_samples
78
+ cdef cnp.uint32_t seed
79
+
80
+ cdef void shuffle(self, cnp.uint32_t seed) nogil
81
+ cdef int _get_next_index(self) nogil
82
+ cdef int _get_random_index(self) nogil
83
+
84
+ cdef void _sample(self, float **x_data_ptr, int **x_ind_ptr,
85
+ int *nnz, float *y, float *sample_weight,
86
+ int current_index) nogil
87
+ cdef void next(self, float **x_data_ptr, int **x_ind_ptr,
88
+ int *nnz, float *y, float *sample_weight) nogil
89
+ cdef int random(self, float **x_data_ptr, int **x_ind_ptr,
90
+ int *nnz, float *y, float *sample_weight) nogil
91
+
92
+
93
+ cdef class ArrayDataset32(SequentialDataset32):
94
+ cdef cnp.ndarray X
95
+ cdef cnp.ndarray Y
96
+ cdef cnp.ndarray sample_weights
97
+ cdef Py_ssize_t n_features
98
+ cdef cnp.npy_intp X_stride
99
+ cdef float *X_data_ptr
100
+ cdef float *Y_data_ptr
101
+ cdef cnp.ndarray feature_indices
102
+ cdef int *feature_indices_ptr
103
+ cdef float *sample_weight_data
104
+
105
+
106
+ cdef class CSRDataset32(SequentialDataset32):
107
+ cdef cnp.ndarray X_data
108
+ cdef cnp.ndarray X_indptr
109
+ cdef cnp.ndarray X_indices
110
+ cdef cnp.ndarray Y
111
+ cdef cnp.ndarray sample_weights
112
+ cdef float *X_data_ptr
113
+ cdef int *X_indptr_ptr
114
+ cdef int *X_indices_ptr
115
+ cdef float *Y_data_ptr
116
+ cdef float *sample_weight_data
videollama2/lib/python3.10/site-packages/sklearn/utils/_sorting.pxd ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from ._typedefs cimport DTYPE_t, ITYPE_t
2
+
3
+ from cython cimport floating
4
+
5
+ cdef int simultaneous_sort(
6
+ floating *dist,
7
+ ITYPE_t *idx,
8
+ ITYPE_t size,
9
+ ) nogil
videollama2/lib/python3.10/site-packages/sklearn/utils/_typedefs.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (38.7 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ad4d62de9cdbea5d9f4005dd26d8b9c59939b60a2f0ee27bd663a92ae288774
3
+ size 145705
videollama2/lib/python3.10/site-packages/sklearn/utils/deprecation.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ import functools
3
+
4
+
5
+ __all__ = ["deprecated"]
6
+
7
+
8
+ class deprecated:
9
+ """Decorator to mark a function or class as deprecated.
10
+
11
+ Issue a warning when the function is called/the class is instantiated and
12
+ adds a warning to the docstring.
13
+
14
+ The optional extra argument will be appended to the deprecation message
15
+ and the docstring. Note: to use this with the default value for extra, put
16
+ in an empty of parentheses:
17
+
18
+ >>> from sklearn.utils import deprecated
19
+ >>> deprecated()
20
+ <sklearn.utils.deprecation.deprecated object at ...>
21
+
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
+ # FIXME: we should probably reset __new__ for full generality
64
+ init = cls.__init__
65
+
66
+ def wrapped(*args, **kwargs):
67
+ warnings.warn(msg, category=FutureWarning)
68
+ return init(*args, **kwargs)
69
+
70
+ cls.__init__ = wrapped
71
+
72
+ wrapped.__name__ = "__init__"
73
+ wrapped.deprecated_original = init
74
+
75
+ return cls
76
+
77
+ def _decorate_fun(self, fun):
78
+ """Decorate function fun"""
79
+
80
+ msg = "Function %s is deprecated" % fun.__name__
81
+ if self.extra:
82
+ msg += "; %s" % self.extra
83
+
84
+ @functools.wraps(fun)
85
+ def wrapped(*args, **kwargs):
86
+ warnings.warn(msg, category=FutureWarning)
87
+ return fun(*args, **kwargs)
88
+
89
+ # Add a reference to the wrapped function so that we can introspect
90
+ # on function arguments in Python 2 (already works in Python 3)
91
+ wrapped.__wrapped__ = fun
92
+
93
+ return wrapped
94
+
95
+ def _decorate_property(self, prop):
96
+ msg = self.extra
97
+
98
+ @property
99
+ @functools.wraps(prop)
100
+ def wrapped(*args, **kwargs):
101
+ warnings.warn(msg, category=FutureWarning)
102
+ return prop.fget(*args, **kwargs)
103
+
104
+ return wrapped
105
+
106
+
107
+ def _is_deprecated(func):
108
+ """Helper to check if func is wrapped by our deprecated decorator"""
109
+ closures = getattr(func, "__closure__", [])
110
+ if closures is None:
111
+ closures = []
112
+ is_deprecated = "deprecated" in "".join(
113
+ [c.cell_contents for c in closures if isinstance(c.cell_contents, str)]
114
+ )
115
+ return is_deprecated
videollama2/lib/python3.10/site-packages/sklearn/utils/fixes.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compatibility fixes for older version of python, numpy and scipy
2
+
3
+ If you add content to this file, please give the version of the package
4
+ at which the fix is no longer needed.
5
+ """
6
+ # Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org>
7
+ # Gael Varoquaux <gael.varoquaux@normalesup.org>
8
+ # Fabian Pedregosa <fpedregosa@acm.org>
9
+ # Lars Buitinck
10
+ #
11
+ # License: BSD 3 clause
12
+
13
+ from importlib import resources
14
+ import sys
15
+
16
+ import sklearn
17
+ import numpy as np
18
+ import scipy
19
+ import scipy.stats
20
+ import threadpoolctl
21
+
22
+ from .deprecation import deprecated
23
+ from ..externals._packaging.version import parse as parse_version
24
+
25
+
26
+ np_version = parse_version(np.__version__)
27
+ sp_version = parse_version(scipy.__version__)
28
+
29
+
30
+ if sp_version >= parse_version("1.4"):
31
+ from scipy.sparse.linalg import lobpcg
32
+ else:
33
+ # Backport of lobpcg functionality from scipy 1.4.0, can be removed
34
+ # once support for sp_version < parse_version('1.4') is dropped
35
+ # mypy error: Name 'lobpcg' already defined (possibly by an import)
36
+ from ..externals._lobpcg import lobpcg # type: ignore # noqa
37
+
38
+ try:
39
+ from scipy.optimize._linesearch import line_search_wolfe2, line_search_wolfe1
40
+ except ImportError: # SciPy < 1.8
41
+ from scipy.optimize.linesearch import line_search_wolfe2, line_search_wolfe1 # type: ignore # noqa
42
+
43
+
44
+ def _object_dtype_isnan(X):
45
+ return X != X
46
+
47
+
48
+ class loguniform(scipy.stats.reciprocal):
49
+ """A class supporting log-uniform random variables.
50
+
51
+ Parameters
52
+ ----------
53
+ low : float
54
+ The minimum value
55
+ high : float
56
+ The maximum value
57
+
58
+ Methods
59
+ -------
60
+ rvs(self, size=None, random_state=None)
61
+ Generate log-uniform random variables
62
+
63
+ The most useful method for Scikit-learn usage is highlighted here.
64
+ For a full list, see
65
+ `scipy.stats.reciprocal
66
+ <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.reciprocal.html>`_.
67
+ This list includes all functions of ``scipy.stats`` continuous
68
+ distributions such as ``pdf``.
69
+
70
+ Notes
71
+ -----
72
+ This class generates values between ``low`` and ``high`` or
73
+
74
+ low <= loguniform(low, high).rvs() <= high
75
+
76
+ The logarithmic probability density function (PDF) is uniform. When
77
+ ``x`` is a uniformly distributed random variable between 0 and 1, ``10**x``
78
+ are random variables that are equally likely to be returned.
79
+
80
+ This class is an alias to ``scipy.stats.reciprocal``, which uses the
81
+ reciprocal distribution:
82
+ https://en.wikipedia.org/wiki/Reciprocal_distribution
83
+
84
+ Examples
85
+ --------
86
+
87
+ >>> from sklearn.utils.fixes import loguniform
88
+ >>> rv = loguniform(1e-3, 1e1)
89
+ >>> rvs = rv.rvs(random_state=42, size=1000)
90
+ >>> rvs.min() # doctest: +SKIP
91
+ 0.0010435856341129003
92
+ >>> rvs.max() # doctest: +SKIP
93
+ 9.97403052786026
94
+ """
95
+
96
+
97
+ # TODO: remove when the minimum scipy version is >= 1.5
98
+ if sp_version >= parse_version("1.5"):
99
+ from scipy.linalg import eigh as _eigh # noqa
100
+ else:
101
+
102
+ def _eigh(*args, **kwargs):
103
+ """Wrapper for `scipy.linalg.eigh` that handles the deprecation of `eigvals`."""
104
+ eigvals = kwargs.pop("subset_by_index", None)
105
+ return scipy.linalg.eigh(*args, eigvals=eigvals, **kwargs)
106
+
107
+
108
+ # Rename the `method` kwarg to `interpolation` for NumPy < 1.22, because
109
+ # `interpolation` kwarg was deprecated in favor of `method` in NumPy >= 1.22.
110
+ def _percentile(a, q, *, method="linear", **kwargs):
111
+ return np.percentile(a, q, interpolation=method, **kwargs)
112
+
113
+
114
+ if np_version < parse_version("1.22"):
115
+ percentile = _percentile
116
+ else: # >= 1.22
117
+ from numpy import percentile # type: ignore # noqa
118
+
119
+
120
+ # compatibility fix for threadpoolctl >= 3.0.0
121
+ # since version 3 it's possible to setup a global threadpool controller to avoid
122
+ # looping through all loaded shared libraries each time.
123
+ # the global controller is created during the first call to threadpoolctl.
124
+ def _get_threadpool_controller():
125
+ if not hasattr(threadpoolctl, "ThreadpoolController"):
126
+ return None
127
+
128
+ if not hasattr(sklearn, "_sklearn_threadpool_controller"):
129
+ sklearn._sklearn_threadpool_controller = threadpoolctl.ThreadpoolController()
130
+
131
+ return sklearn._sklearn_threadpool_controller
132
+
133
+
134
+ def threadpool_limits(limits=None, user_api=None):
135
+ controller = _get_threadpool_controller()
136
+ if controller is not None:
137
+ return controller.limit(limits=limits, user_api=user_api)
138
+ else:
139
+ return threadpoolctl.threadpool_limits(limits=limits, user_api=user_api)
140
+
141
+
142
+ threadpool_limits.__doc__ = threadpoolctl.threadpool_limits.__doc__
143
+
144
+
145
+ def threadpool_info():
146
+ controller = _get_threadpool_controller()
147
+ if controller is not None:
148
+ return controller.info()
149
+ else:
150
+ return threadpoolctl.threadpool_info()
151
+
152
+
153
+ threadpool_info.__doc__ = threadpoolctl.threadpool_info.__doc__
154
+
155
+
156
+ @deprecated(
157
+ "The function `delayed` has been moved from `sklearn.utils.fixes` to "
158
+ "`sklearn.utils.parallel`. This import path will be removed in 1.5."
159
+ )
160
+ def delayed(function):
161
+ from sklearn.utils.parallel import delayed
162
+
163
+ return delayed(function)
164
+
165
+
166
+ # TODO: Remove when SciPy 1.11 is the minimum supported version
167
+ def _mode(a, axis=0):
168
+ if sp_version >= parse_version("1.9.0"):
169
+ mode = scipy.stats.mode(a, axis=axis, keepdims=True)
170
+ if sp_version >= parse_version("1.10.999"):
171
+ # scipy.stats.mode has changed returned array shape with axis=None
172
+ # and keepdims=True, see https://github.com/scipy/scipy/pull/17561
173
+ if axis is None:
174
+ mode = np.ravel(mode)
175
+ return mode
176
+ return scipy.stats.mode(a, axis=axis)
177
+
178
+
179
+ ###############################################################################
180
+ # Backport of Python 3.9's importlib.resources
181
+ # TODO: Remove when Python 3.9 is the minimum supported version
182
+
183
+
184
+ def _open_text(data_module, data_file_name):
185
+ if sys.version_info >= (3, 9):
186
+ return resources.files(data_module).joinpath(data_file_name).open("r")
187
+ else:
188
+ return resources.open_text(data_module, data_file_name)
189
+
190
+
191
+ def _open_binary(data_module, data_file_name):
192
+ if sys.version_info >= (3, 9):
193
+ return resources.files(data_module).joinpath(data_file_name).open("rb")
194
+ else:
195
+ return resources.open_binary(data_module, data_file_name)
196
+
197
+
198
+ def _read_text(descr_module, descr_file_name):
199
+ if sys.version_info >= (3, 9):
200
+ return resources.files(descr_module).joinpath(descr_file_name).read_text()
201
+ else:
202
+ return resources.read_text(descr_module, descr_file_name)
203
+
204
+
205
+ def _path(data_module, data_file_name):
206
+ if sys.version_info >= (3, 9):
207
+ return resources.as_file(resources.files(data_module).joinpath(data_file_name))
208
+ else:
209
+ return resources.path(data_module, data_file_name)
210
+
211
+
212
+ def _is_resource(data_module, data_file_name):
213
+ if sys.version_info >= (3, 9):
214
+ return resources.files(data_module).joinpath(data_file_name).is_file()
215
+ else:
216
+ return resources.is_resource(data_module, data_file_name)
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (176 Bytes). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (425 Bytes). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_array_api.cpython-310.pyc ADDED
Binary file (6.77 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_arrayfuncs.cpython-310.pyc ADDED
Binary file (900 Bytes). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_class_weight.cpython-310.pyc ADDED
Binary file (7.93 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_blas.cpython-310.pyc ADDED
Binary file (6.12 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_templating.cpython-310.pyc ADDED
Binary file (1.04 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_deprecation.cpython-310.pyc ADDED
Binary file (2.3 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_encode.cpython-310.pyc ADDED
Binary file (6.42 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc ADDED
Binary file (41.6 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_html_repr.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_fast_dict.cpython-310.pyc ADDED
Binary file (1.12 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_mocking.cpython-310.pyc ADDED
Binary file (4.94 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_murmurhash.cpython-310.pyc ADDED
Binary file (2.55 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc ADDED
Binary file (1.48 kB). View file