ZTWHHH commited on
Commit
7aeb328
·
verified ·
1 Parent(s): 6fa4311

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. videollama2/lib/python3.10/site-packages/sklearn/metrics/__init__.py +181 -0
  2. videollama2/lib/python3.10/site-packages/sklearn/metrics/_classification.py +0 -0
  3. videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__pycache__/__init__.cpython-310.pyc +0 -0
  4. videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__pycache__/_dispatcher.cpython-310.pyc +0 -0
  5. videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pxd +56 -0
  6. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__init__.py +0 -0
  7. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/roc_curve.cpython-310.pyc +0 -0
  8. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/base.py +116 -0
  9. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/confusion_matrix.py +482 -0
  10. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/det_curve.py +346 -0
  11. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/precision_recall_curve.py +393 -0
  12. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/regression.py +406 -0
  13. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/roc_curve.py +352 -0
  14. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__init__.py +0 -0
  15. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_common_curve_display.py +152 -0
  16. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py +407 -0
  17. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_precision_recall_display.py +292 -0
  18. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_predict_error_display.py +163 -0
  19. videollama2/lib/python3.10/site-packages/sklearn/metrics/_regression.py +1497 -0
  20. videollama2/lib/python3.10/site-packages/sklearn/metrics/_scorer.py +867 -0
  21. videollama2/lib/python3.10/site-packages/sklearn/metrics/pairwise.py +2205 -0
  22. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/__init__.cpython-310.pyc +0 -0
  23. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_arpack.cpython-310.pyc +0 -0
  24. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_array_api.cpython-310.pyc +0 -0
  25. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_bunch.cpython-310.pyc +0 -0
  26. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_estimator_html_repr.cpython-310.pyc +0 -0
  27. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_joblib.cpython-310.pyc +0 -0
  28. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_param_validation.cpython-310.pyc +0 -0
  29. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_pprint.cpython-310.pyc +0 -0
  30. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/class_weight.cpython-310.pyc +0 -0
  31. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/discovery.cpython-310.pyc +0 -0
  32. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/metaestimators.cpython-310.pyc +0 -0
  33. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/parallel.cpython-310.pyc +0 -0
  34. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/random.cpython-310.pyc +0 -0
  35. videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/sparsefuncs.cpython-310.pyc +0 -0
  36. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_assert_async_cpu_dispatch.h +24 -0
  37. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Char_compositeimplicitautograd_dispatch.h +23 -0
  38. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_copy_from_native.h +21 -0
  39. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_ops.h +39 -0
  40. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_tanh_ops.h +50 -0
  41. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sobol_engine_draw_ops.h +28 -0
  42. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_semi_structured_tile_ops.h +28 -0
  43. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell_cuda_dispatch.h +23 -0
  44. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/arccosh_native.h +23 -0
  45. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/batch_norm_update_stats.h +39 -0
  46. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy_with_logits_compositeexplicitautograd_dispatch.h +25 -0
  47. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/conv_transpose3d_compositeimplicitautograd_dispatch.h +24 -0
  48. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/corrcoef_native.h +21 -0
  49. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_convolution_add_relu.h +91 -0
  50. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/deg2rad.h +44 -0
videollama2/lib/python3.10/site-packages/sklearn/metrics/__init__.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The :mod:`sklearn.metrics` module includes score functions, performance metrics
3
+ and pairwise metrics and distance computations.
4
+ """
5
+
6
+
7
+ from ._ranking import auc
8
+ from ._ranking import average_precision_score
9
+ from ._ranking import coverage_error
10
+ from ._ranking import det_curve
11
+ from ._ranking import dcg_score
12
+ from ._ranking import label_ranking_average_precision_score
13
+ from ._ranking import label_ranking_loss
14
+ from ._ranking import ndcg_score
15
+ from ._ranking import precision_recall_curve
16
+ from ._ranking import roc_auc_score
17
+ from ._ranking import roc_curve
18
+ from ._ranking import top_k_accuracy_score
19
+
20
+ from ._classification import accuracy_score
21
+ from ._classification import balanced_accuracy_score
22
+ from ._classification import class_likelihood_ratios
23
+ from ._classification import classification_report
24
+ from ._classification import cohen_kappa_score
25
+ from ._classification import confusion_matrix
26
+ from ._classification import f1_score
27
+ from ._classification import fbeta_score
28
+ from ._classification import hamming_loss
29
+ from ._classification import hinge_loss
30
+ from ._classification import jaccard_score
31
+ from ._classification import log_loss
32
+ from ._classification import matthews_corrcoef
33
+ from ._classification import precision_recall_fscore_support
34
+ from ._classification import precision_score
35
+ from ._classification import recall_score
36
+ from ._classification import zero_one_loss
37
+ from ._classification import brier_score_loss
38
+ from ._classification import multilabel_confusion_matrix
39
+
40
+ from ._dist_metrics import DistanceMetric
41
+
42
+ from . import cluster
43
+ from .cluster import adjusted_mutual_info_score
44
+ from .cluster import adjusted_rand_score
45
+ from .cluster import rand_score
46
+ from .cluster import pair_confusion_matrix
47
+ from .cluster import completeness_score
48
+ from .cluster import consensus_score
49
+ from .cluster import homogeneity_completeness_v_measure
50
+ from .cluster import homogeneity_score
51
+ from .cluster import mutual_info_score
52
+ from .cluster import normalized_mutual_info_score
53
+ from .cluster import fowlkes_mallows_score
54
+ from .cluster import silhouette_samples
55
+ from .cluster import silhouette_score
56
+ from .cluster import calinski_harabasz_score
57
+ from .cluster import v_measure_score
58
+ from .cluster import davies_bouldin_score
59
+
60
+ from .pairwise import euclidean_distances
61
+ from .pairwise import nan_euclidean_distances
62
+ from .pairwise import pairwise_distances
63
+ from .pairwise import pairwise_distances_argmin
64
+ from .pairwise import pairwise_distances_argmin_min
65
+ from .pairwise import pairwise_kernels
66
+ from .pairwise import pairwise_distances_chunked
67
+
68
+ from ._regression import explained_variance_score
69
+ from ._regression import max_error
70
+ from ._regression import mean_absolute_error
71
+ from ._regression import mean_squared_error
72
+ from ._regression import mean_squared_log_error
73
+ from ._regression import median_absolute_error
74
+ from ._regression import mean_absolute_percentage_error
75
+ from ._regression import mean_pinball_loss
76
+ from ._regression import r2_score
77
+ from ._regression import mean_tweedie_deviance
78
+ from ._regression import mean_poisson_deviance
79
+ from ._regression import mean_gamma_deviance
80
+ from ._regression import d2_tweedie_score
81
+ from ._regression import d2_pinball_score
82
+ from ._regression import d2_absolute_error_score
83
+
84
+
85
+ from ._scorer import check_scoring
86
+ from ._scorer import make_scorer
87
+ from ._scorer import SCORERS
88
+ from ._scorer import get_scorer
89
+ from ._scorer import get_scorer_names
90
+
91
+
92
+ from ._plot.det_curve import DetCurveDisplay
93
+ from ._plot.roc_curve import RocCurveDisplay
94
+ from ._plot.precision_recall_curve import PrecisionRecallDisplay
95
+ from ._plot.confusion_matrix import ConfusionMatrixDisplay
96
+ from ._plot.regression import PredictionErrorDisplay
97
+
98
+
99
+ __all__ = [
100
+ "accuracy_score",
101
+ "adjusted_mutual_info_score",
102
+ "adjusted_rand_score",
103
+ "auc",
104
+ "average_precision_score",
105
+ "balanced_accuracy_score",
106
+ "calinski_harabasz_score",
107
+ "check_scoring",
108
+ "class_likelihood_ratios",
109
+ "classification_report",
110
+ "cluster",
111
+ "cohen_kappa_score",
112
+ "completeness_score",
113
+ "ConfusionMatrixDisplay",
114
+ "confusion_matrix",
115
+ "consensus_score",
116
+ "coverage_error",
117
+ "d2_tweedie_score",
118
+ "d2_absolute_error_score",
119
+ "d2_pinball_score",
120
+ "dcg_score",
121
+ "davies_bouldin_score",
122
+ "DetCurveDisplay",
123
+ "det_curve",
124
+ "DistanceMetric",
125
+ "euclidean_distances",
126
+ "explained_variance_score",
127
+ "f1_score",
128
+ "fbeta_score",
129
+ "fowlkes_mallows_score",
130
+ "get_scorer",
131
+ "hamming_loss",
132
+ "hinge_loss",
133
+ "homogeneity_completeness_v_measure",
134
+ "homogeneity_score",
135
+ "jaccard_score",
136
+ "label_ranking_average_precision_score",
137
+ "label_ranking_loss",
138
+ "log_loss",
139
+ "make_scorer",
140
+ "nan_euclidean_distances",
141
+ "matthews_corrcoef",
142
+ "max_error",
143
+ "mean_absolute_error",
144
+ "mean_squared_error",
145
+ "mean_squared_log_error",
146
+ "mean_pinball_loss",
147
+ "mean_poisson_deviance",
148
+ "mean_gamma_deviance",
149
+ "mean_tweedie_deviance",
150
+ "median_absolute_error",
151
+ "mean_absolute_percentage_error",
152
+ "multilabel_confusion_matrix",
153
+ "mutual_info_score",
154
+ "ndcg_score",
155
+ "normalized_mutual_info_score",
156
+ "pair_confusion_matrix",
157
+ "pairwise_distances",
158
+ "pairwise_distances_argmin",
159
+ "pairwise_distances_argmin_min",
160
+ "pairwise_distances_chunked",
161
+ "pairwise_kernels",
162
+ "PrecisionRecallDisplay",
163
+ "precision_recall_curve",
164
+ "precision_recall_fscore_support",
165
+ "precision_score",
166
+ "PredictionErrorDisplay",
167
+ "r2_score",
168
+ "rand_score",
169
+ "recall_score",
170
+ "RocCurveDisplay",
171
+ "roc_auc_score",
172
+ "roc_curve",
173
+ "SCORERS",
174
+ "get_scorer_names",
175
+ "silhouette_samples",
176
+ "silhouette_score",
177
+ "top_k_accuracy_score",
178
+ "v_measure_score",
179
+ "zero_one_loss",
180
+ "brier_score_loss",
181
+ ]
videollama2/lib/python3.10/site-packages/sklearn/metrics/_classification.py ADDED
The diff for this file is too large to render. See raw diff
 
videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (365 Bytes). View file
 
videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__pycache__/_dispatcher.cpython-310.pyc ADDED
Binary file (14.4 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pxd ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport numpy as cnp
2
+ from ...utils._typedefs cimport ITYPE_t, DTYPE_t
3
+
4
+ cnp.import_array()
5
+
6
+ from ._base cimport BaseDistancesReduction64
7
+ from ._middle_term_computer cimport MiddleTermComputer64
8
+
9
+ cdef class ArgKmin64(BaseDistancesReduction64):
10
+ """float64 implementation of the ArgKmin."""
11
+
12
+ cdef:
13
+ ITYPE_t k
14
+
15
+ ITYPE_t[:, ::1] argkmin_indices
16
+ DTYPE_t[:, ::1] argkmin_distances
17
+
18
+ # Used as array of pointers to private datastructures used in threads.
19
+ DTYPE_t ** heaps_r_distances_chunks
20
+ ITYPE_t ** heaps_indices_chunks
21
+
22
+
23
+ cdef class EuclideanArgKmin64(ArgKmin64):
24
+ """EuclideanDistance-specialisation of ArgKmin64."""
25
+ cdef:
26
+ MiddleTermComputer64 middle_term_computer
27
+ const DTYPE_t[::1] X_norm_squared
28
+ const DTYPE_t[::1] Y_norm_squared
29
+
30
+ bint use_squared_distances
31
+
32
+ from ._base cimport BaseDistancesReduction32
33
+ from ._middle_term_computer cimport MiddleTermComputer32
34
+
35
+ cdef class ArgKmin32(BaseDistancesReduction32):
36
+ """float32 implementation of the ArgKmin."""
37
+
38
+ cdef:
39
+ ITYPE_t k
40
+
41
+ ITYPE_t[:, ::1] argkmin_indices
42
+ DTYPE_t[:, ::1] argkmin_distances
43
+
44
+ # Used as array of pointers to private datastructures used in threads.
45
+ DTYPE_t ** heaps_r_distances_chunks
46
+ ITYPE_t ** heaps_indices_chunks
47
+
48
+
49
+ cdef class EuclideanArgKmin32(ArgKmin32):
50
+ """EuclideanDistance-specialisation of ArgKmin32."""
51
+ cdef:
52
+ MiddleTermComputer32 middle_term_computer
53
+ const DTYPE_t[::1] X_norm_squared
54
+ const DTYPE_t[::1] Y_norm_squared
55
+
56
+ bint use_squared_distances
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__init__.py ADDED
File without changes
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/roc_curve.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/base.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ...base import is_classifier
2
+
3
+
4
+ def _check_classifier_response_method(estimator, response_method):
5
+ """Return prediction method from the response_method
6
+
7
+ Parameters
8
+ ----------
9
+ estimator: object
10
+ Classifier to check
11
+
12
+ response_method: {'auto', 'predict_proba', 'decision_function'}
13
+ Specifies whether to use :term:`predict_proba` or
14
+ :term:`decision_function` as the target response. If set to 'auto',
15
+ :term:`predict_proba` is tried first and if it does not exist
16
+ :term:`decision_function` is tried next.
17
+
18
+ Returns
19
+ -------
20
+ prediction_method: callable
21
+ prediction method of estimator
22
+ """
23
+
24
+ if response_method not in ("predict_proba", "decision_function", "auto"):
25
+ raise ValueError(
26
+ "response_method must be 'predict_proba', 'decision_function' or 'auto'"
27
+ )
28
+
29
+ error_msg = "response method {} is not defined in {}"
30
+ if response_method != "auto":
31
+ prediction_method = getattr(estimator, response_method, None)
32
+ if prediction_method is None:
33
+ raise ValueError(
34
+ error_msg.format(response_method, estimator.__class__.__name__)
35
+ )
36
+ else:
37
+ predict_proba = getattr(estimator, "predict_proba", None)
38
+ decision_function = getattr(estimator, "decision_function", None)
39
+ prediction_method = predict_proba or decision_function
40
+ if prediction_method is None:
41
+ raise ValueError(
42
+ error_msg.format(
43
+ "decision_function or predict_proba", estimator.__class__.__name__
44
+ )
45
+ )
46
+
47
+ return prediction_method
48
+
49
+
50
+ def _get_response(X, estimator, response_method, pos_label=None):
51
+ """Return response and positive label.
52
+
53
+ Parameters
54
+ ----------
55
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
56
+ Input values.
57
+
58
+ estimator : estimator instance
59
+ Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline`
60
+ in which the last estimator is a classifier.
61
+
62
+ response_method: {'auto', 'predict_proba', 'decision_function'}
63
+ Specifies whether to use :term:`predict_proba` or
64
+ :term:`decision_function` as the target response. If set to 'auto',
65
+ :term:`predict_proba` is tried first and if it does not exist
66
+ :term:`decision_function` is tried next.
67
+
68
+ pos_label : str or int, default=None
69
+ The class considered as the positive class when computing
70
+ the metrics. By default, `estimators.classes_[1]` is
71
+ considered as the positive class.
72
+
73
+ Returns
74
+ -------
75
+ y_pred: ndarray of shape (n_samples,)
76
+ Target scores calculated from the provided response_method
77
+ and pos_label.
78
+
79
+ pos_label: str or int
80
+ The class considered as the positive class when computing
81
+ the metrics.
82
+ """
83
+ classification_error = (
84
+ "Expected 'estimator' to be a binary classifier, but got"
85
+ f" {estimator.__class__.__name__}"
86
+ )
87
+
88
+ if not is_classifier(estimator):
89
+ raise ValueError(classification_error)
90
+
91
+ prediction_method = _check_classifier_response_method(estimator, response_method)
92
+ y_pred = prediction_method(X)
93
+ if pos_label is not None:
94
+ try:
95
+ class_idx = estimator.classes_.tolist().index(pos_label)
96
+ except ValueError as e:
97
+ raise ValueError(
98
+ "The class provided by 'pos_label' is unknown. Got "
99
+ f"{pos_label} instead of one of {set(estimator.classes_)}"
100
+ ) from e
101
+ else:
102
+ class_idx = 1
103
+ pos_label = estimator.classes_[class_idx]
104
+
105
+ if y_pred.ndim != 1: # `predict_proba`
106
+ y_pred_shape = y_pred.shape[1]
107
+ if y_pred_shape != 2:
108
+ raise ValueError(
109
+ f"{classification_error} fit on multiclass ({y_pred_shape} classes)"
110
+ " data"
111
+ )
112
+ y_pred = y_pred[:, class_idx]
113
+ elif pos_label == estimator.classes_[0]: # `decision_function`
114
+ y_pred *= -1
115
+
116
+ return y_pred, pos_label
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/confusion_matrix.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import product
2
+
3
+ import numpy as np
4
+
5
+ from .. import confusion_matrix
6
+ from ...utils import check_matplotlib_support
7
+ from ...utils.multiclass import unique_labels
8
+ from ...base import is_classifier
9
+
10
+
11
+ class ConfusionMatrixDisplay:
12
+ """Confusion Matrix visualization.
13
+
14
+ It is recommend to use
15
+ :func:`~sklearn.metrics.ConfusionMatrixDisplay.from_estimator` or
16
+ :func:`~sklearn.metrics.ConfusionMatrixDisplay.from_predictions` to
17
+ create a :class:`ConfusionMatrixDisplay`. All parameters are stored as
18
+ attributes.
19
+
20
+ Read more in the :ref:`User Guide <visualizations>`.
21
+
22
+ Parameters
23
+ ----------
24
+ confusion_matrix : ndarray of shape (n_classes, n_classes)
25
+ Confusion matrix.
26
+
27
+ display_labels : ndarray of shape (n_classes,), default=None
28
+ Display labels for plot. If None, display labels are set from 0 to
29
+ `n_classes - 1`.
30
+
31
+ Attributes
32
+ ----------
33
+ im_ : matplotlib AxesImage
34
+ Image representing the confusion matrix.
35
+
36
+ text_ : ndarray of shape (n_classes, n_classes), dtype=matplotlib Text, \
37
+ or None
38
+ Array of matplotlib axes. `None` if `include_values` is false.
39
+
40
+ ax_ : matplotlib Axes
41
+ Axes with confusion matrix.
42
+
43
+ figure_ : matplotlib Figure
44
+ Figure containing the confusion matrix.
45
+
46
+ See Also
47
+ --------
48
+ confusion_matrix : Compute Confusion Matrix to evaluate the accuracy of a
49
+ classification.
50
+ ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix
51
+ given an estimator, the data, and the label.
52
+ ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix
53
+ given the true and predicted labels.
54
+
55
+ Examples
56
+ --------
57
+ >>> import matplotlib.pyplot as plt
58
+ >>> from sklearn.datasets import make_classification
59
+ >>> from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
60
+ >>> from sklearn.model_selection import train_test_split
61
+ >>> from sklearn.svm import SVC
62
+ >>> X, y = make_classification(random_state=0)
63
+ >>> X_train, X_test, y_train, y_test = train_test_split(X, y,
64
+ ... random_state=0)
65
+ >>> clf = SVC(random_state=0)
66
+ >>> clf.fit(X_train, y_train)
67
+ SVC(random_state=0)
68
+ >>> predictions = clf.predict(X_test)
69
+ >>> cm = confusion_matrix(y_test, predictions, labels=clf.classes_)
70
+ >>> disp = ConfusionMatrixDisplay(confusion_matrix=cm,
71
+ ... display_labels=clf.classes_)
72
+ >>> disp.plot()
73
+ <...>
74
+ >>> plt.show()
75
+ """
76
+
77
+ def __init__(self, confusion_matrix, *, display_labels=None):
78
+ self.confusion_matrix = confusion_matrix
79
+ self.display_labels = display_labels
80
+
81
+ def plot(
82
+ self,
83
+ *,
84
+ include_values=True,
85
+ cmap="viridis",
86
+ xticks_rotation="horizontal",
87
+ values_format=None,
88
+ ax=None,
89
+ colorbar=True,
90
+ im_kw=None,
91
+ text_kw=None,
92
+ ):
93
+ """Plot visualization.
94
+
95
+ Parameters
96
+ ----------
97
+ include_values : bool, default=True
98
+ Includes values in confusion matrix.
99
+
100
+ cmap : str or matplotlib Colormap, default='viridis'
101
+ Colormap recognized by matplotlib.
102
+
103
+ xticks_rotation : {'vertical', 'horizontal'} or float, \
104
+ default='horizontal'
105
+ Rotation of xtick labels.
106
+
107
+ values_format : str, default=None
108
+ Format specification for values in confusion matrix. If `None`,
109
+ the format specification is 'd' or '.2g' whichever is shorter.
110
+
111
+ ax : matplotlib axes, default=None
112
+ Axes object to plot on. If `None`, a new figure and axes is
113
+ created.
114
+
115
+ colorbar : bool, default=True
116
+ Whether or not to add a colorbar to the plot.
117
+
118
+ im_kw : dict, default=None
119
+ Dict with keywords passed to `matplotlib.pyplot.imshow` call.
120
+
121
+ text_kw : dict, default=None
122
+ Dict with keywords passed to `matplotlib.pyplot.text` call.
123
+
124
+ .. versionadded:: 1.2
125
+
126
+ Returns
127
+ -------
128
+ display : :class:`~sklearn.metrics.ConfusionMatrixDisplay`
129
+ Returns a :class:`~sklearn.metrics.ConfusionMatrixDisplay` instance
130
+ that contains all the information to plot the confusion matrix.
131
+ """
132
+ check_matplotlib_support("ConfusionMatrixDisplay.plot")
133
+ import matplotlib.pyplot as plt
134
+
135
+ if ax is None:
136
+ fig, ax = plt.subplots()
137
+ else:
138
+ fig = ax.figure
139
+
140
+ cm = self.confusion_matrix
141
+ n_classes = cm.shape[0]
142
+
143
+ default_im_kw = dict(interpolation="nearest", cmap=cmap)
144
+ im_kw = im_kw or {}
145
+ im_kw = {**default_im_kw, **im_kw}
146
+ text_kw = text_kw or {}
147
+
148
+ self.im_ = ax.imshow(cm, **im_kw)
149
+ self.text_ = None
150
+ cmap_min, cmap_max = self.im_.cmap(0), self.im_.cmap(1.0)
151
+
152
+ if include_values:
153
+ self.text_ = np.empty_like(cm, dtype=object)
154
+
155
+ # print text with appropriate color depending on background
156
+ thresh = (cm.max() + cm.min()) / 2.0
157
+
158
+ for i, j in product(range(n_classes), range(n_classes)):
159
+ color = cmap_max if cm[i, j] < thresh else cmap_min
160
+
161
+ if values_format is None:
162
+ text_cm = format(cm[i, j], ".2g")
163
+ if cm.dtype.kind != "f":
164
+ text_d = format(cm[i, j], "d")
165
+ if len(text_d) < len(text_cm):
166
+ text_cm = text_d
167
+ else:
168
+ text_cm = format(cm[i, j], values_format)
169
+
170
+ default_text_kwargs = dict(ha="center", va="center", color=color)
171
+ text_kwargs = {**default_text_kwargs, **text_kw}
172
+
173
+ self.text_[i, j] = ax.text(j, i, text_cm, **text_kwargs)
174
+
175
+ if self.display_labels is None:
176
+ display_labels = np.arange(n_classes)
177
+ else:
178
+ display_labels = self.display_labels
179
+ if colorbar:
180
+ fig.colorbar(self.im_, ax=ax)
181
+ ax.set(
182
+ xticks=np.arange(n_classes),
183
+ yticks=np.arange(n_classes),
184
+ xticklabels=display_labels,
185
+ yticklabels=display_labels,
186
+ ylabel="True label",
187
+ xlabel="Predicted label",
188
+ )
189
+
190
+ ax.set_ylim((n_classes - 0.5, -0.5))
191
+ plt.setp(ax.get_xticklabels(), rotation=xticks_rotation)
192
+
193
+ self.figure_ = fig
194
+ self.ax_ = ax
195
+ return self
196
+
197
+ @classmethod
198
+ def from_estimator(
199
+ cls,
200
+ estimator,
201
+ X,
202
+ y,
203
+ *,
204
+ labels=None,
205
+ sample_weight=None,
206
+ normalize=None,
207
+ display_labels=None,
208
+ include_values=True,
209
+ xticks_rotation="horizontal",
210
+ values_format=None,
211
+ cmap="viridis",
212
+ ax=None,
213
+ colorbar=True,
214
+ im_kw=None,
215
+ text_kw=None,
216
+ ):
217
+ """Plot Confusion Matrix given an estimator and some data.
218
+
219
+ Read more in the :ref:`User Guide <confusion_matrix>`.
220
+
221
+ .. versionadded:: 1.0
222
+
223
+ Parameters
224
+ ----------
225
+ estimator : estimator instance
226
+ Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline`
227
+ in which the last estimator is a classifier.
228
+
229
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
230
+ Input values.
231
+
232
+ y : array-like of shape (n_samples,)
233
+ Target values.
234
+
235
+ labels : array-like of shape (n_classes,), default=None
236
+ List of labels to index the confusion matrix. This may be used to
237
+ reorder or select a subset of labels. If `None` is given, those
238
+ that appear at least once in `y_true` or `y_pred` are used in
239
+ sorted order.
240
+
241
+ sample_weight : array-like of shape (n_samples,), default=None
242
+ Sample weights.
243
+
244
+ normalize : {'true', 'pred', 'all'}, default=None
245
+ Either to normalize the counts display in the matrix:
246
+
247
+ - if `'true'`, the confusion matrix is normalized over the true
248
+ conditions (e.g. rows);
249
+ - if `'pred'`, the confusion matrix is normalized over the
250
+ predicted conditions (e.g. columns);
251
+ - if `'all'`, the confusion matrix is normalized by the total
252
+ number of samples;
253
+ - if `None` (default), the confusion matrix will not be normalized.
254
+
255
+ display_labels : array-like of shape (n_classes,), default=None
256
+ Target names used for plotting. By default, `labels` will be used
257
+ if it is defined, otherwise the unique labels of `y_true` and
258
+ `y_pred` will be used.
259
+
260
+ include_values : bool, default=True
261
+ Includes values in confusion matrix.
262
+
263
+ xticks_rotation : {'vertical', 'horizontal'} or float, \
264
+ default='horizontal'
265
+ Rotation of xtick labels.
266
+
267
+ values_format : str, default=None
268
+ Format specification for values in confusion matrix. If `None`, the
269
+ format specification is 'd' or '.2g' whichever is shorter.
270
+
271
+ cmap : str or matplotlib Colormap, default='viridis'
272
+ Colormap recognized by matplotlib.
273
+
274
+ ax : matplotlib Axes, default=None
275
+ Axes object to plot on. If `None`, a new figure and axes is
276
+ created.
277
+
278
+ colorbar : bool, default=True
279
+ Whether or not to add a colorbar to the plot.
280
+
281
+ im_kw : dict, default=None
282
+ Dict with keywords passed to `matplotlib.pyplot.imshow` call.
283
+
284
+ text_kw : dict, default=None
285
+ Dict with keywords passed to `matplotlib.pyplot.text` call.
286
+
287
+ .. versionadded:: 1.2
288
+
289
+ Returns
290
+ -------
291
+ display : :class:`~sklearn.metrics.ConfusionMatrixDisplay`
292
+
293
+ See Also
294
+ --------
295
+ ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix
296
+ given the true and predicted labels.
297
+
298
+ Examples
299
+ --------
300
+ >>> import matplotlib.pyplot as plt
301
+ >>> from sklearn.datasets import make_classification
302
+ >>> from sklearn.metrics import ConfusionMatrixDisplay
303
+ >>> from sklearn.model_selection import train_test_split
304
+ >>> from sklearn.svm import SVC
305
+ >>> X, y = make_classification(random_state=0)
306
+ >>> X_train, X_test, y_train, y_test = train_test_split(
307
+ ... X, y, random_state=0)
308
+ >>> clf = SVC(random_state=0)
309
+ >>> clf.fit(X_train, y_train)
310
+ SVC(random_state=0)
311
+ >>> ConfusionMatrixDisplay.from_estimator(
312
+ ... clf, X_test, y_test)
313
+ <...>
314
+ >>> plt.show()
315
+ """
316
+ method_name = f"{cls.__name__}.from_estimator"
317
+ check_matplotlib_support(method_name)
318
+ if not is_classifier(estimator):
319
+ raise ValueError(f"{method_name} only supports classifiers")
320
+ y_pred = estimator.predict(X)
321
+
322
+ return cls.from_predictions(
323
+ y,
324
+ y_pred,
325
+ sample_weight=sample_weight,
326
+ labels=labels,
327
+ normalize=normalize,
328
+ display_labels=display_labels,
329
+ include_values=include_values,
330
+ cmap=cmap,
331
+ ax=ax,
332
+ xticks_rotation=xticks_rotation,
333
+ values_format=values_format,
334
+ colorbar=colorbar,
335
+ im_kw=im_kw,
336
+ text_kw=text_kw,
337
+ )
338
+
339
+ @classmethod
340
+ def from_predictions(
341
+ cls,
342
+ y_true,
343
+ y_pred,
344
+ *,
345
+ labels=None,
346
+ sample_weight=None,
347
+ normalize=None,
348
+ display_labels=None,
349
+ include_values=True,
350
+ xticks_rotation="horizontal",
351
+ values_format=None,
352
+ cmap="viridis",
353
+ ax=None,
354
+ colorbar=True,
355
+ im_kw=None,
356
+ text_kw=None,
357
+ ):
358
+ """Plot Confusion Matrix given true and predicted labels.
359
+
360
+ Read more in the :ref:`User Guide <confusion_matrix>`.
361
+
362
+ .. versionadded:: 1.0
363
+
364
+ Parameters
365
+ ----------
366
+ y_true : array-like of shape (n_samples,)
367
+ True labels.
368
+
369
+ y_pred : array-like of shape (n_samples,)
370
+ The predicted labels given by the method `predict` of an
371
+ classifier.
372
+
373
+ labels : array-like of shape (n_classes,), default=None
374
+ List of labels to index the confusion matrix. This may be used to
375
+ reorder or select a subset of labels. If `None` is given, those
376
+ that appear at least once in `y_true` or `y_pred` are used in
377
+ sorted order.
378
+
379
+ sample_weight : array-like of shape (n_samples,), default=None
380
+ Sample weights.
381
+
382
+ normalize : {'true', 'pred', 'all'}, default=None
383
+ Either to normalize the counts display in the matrix:
384
+
385
+ - if `'true'`, the confusion matrix is normalized over the true
386
+ conditions (e.g. rows);
387
+ - if `'pred'`, the confusion matrix is normalized over the
388
+ predicted conditions (e.g. columns);
389
+ - if `'all'`, the confusion matrix is normalized by the total
390
+ number of samples;
391
+ - if `None` (default), the confusion matrix will not be normalized.
392
+
393
+ display_labels : array-like of shape (n_classes,), default=None
394
+ Target names used for plotting. By default, `labels` will be used
395
+ if it is defined, otherwise the unique labels of `y_true` and
396
+ `y_pred` will be used.
397
+
398
+ include_values : bool, default=True
399
+ Includes values in confusion matrix.
400
+
401
+ xticks_rotation : {'vertical', 'horizontal'} or float, \
402
+ default='horizontal'
403
+ Rotation of xtick labels.
404
+
405
+ values_format : str, default=None
406
+ Format specification for values in confusion matrix. If `None`, the
407
+ format specification is 'd' or '.2g' whichever is shorter.
408
+
409
+ cmap : str or matplotlib Colormap, default='viridis'
410
+ Colormap recognized by matplotlib.
411
+
412
+ ax : matplotlib Axes, default=None
413
+ Axes object to plot on. If `None`, a new figure and axes is
414
+ created.
415
+
416
+ colorbar : bool, default=True
417
+ Whether or not to add a colorbar to the plot.
418
+
419
+ im_kw : dict, default=None
420
+ Dict with keywords passed to `matplotlib.pyplot.imshow` call.
421
+
422
+ text_kw : dict, default=None
423
+ Dict with keywords passed to `matplotlib.pyplot.text` call.
424
+
425
+ .. versionadded:: 1.2
426
+
427
+ Returns
428
+ -------
429
+ display : :class:`~sklearn.metrics.ConfusionMatrixDisplay`
430
+
431
+ See Also
432
+ --------
433
+ ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix
434
+ given an estimator, the data, and the label.
435
+
436
+ Examples
437
+ --------
438
+ >>> import matplotlib.pyplot as plt
439
+ >>> from sklearn.datasets import make_classification
440
+ >>> from sklearn.metrics import ConfusionMatrixDisplay
441
+ >>> from sklearn.model_selection import train_test_split
442
+ >>> from sklearn.svm import SVC
443
+ >>> X, y = make_classification(random_state=0)
444
+ >>> X_train, X_test, y_train, y_test = train_test_split(
445
+ ... X, y, random_state=0)
446
+ >>> clf = SVC(random_state=0)
447
+ >>> clf.fit(X_train, y_train)
448
+ SVC(random_state=0)
449
+ >>> y_pred = clf.predict(X_test)
450
+ >>> ConfusionMatrixDisplay.from_predictions(
451
+ ... y_test, y_pred)
452
+ <...>
453
+ >>> plt.show()
454
+ """
455
+ check_matplotlib_support(f"{cls.__name__}.from_predictions")
456
+
457
+ if display_labels is None:
458
+ if labels is None:
459
+ display_labels = unique_labels(y_true, y_pred)
460
+ else:
461
+ display_labels = labels
462
+
463
+ cm = confusion_matrix(
464
+ y_true,
465
+ y_pred,
466
+ sample_weight=sample_weight,
467
+ labels=labels,
468
+ normalize=normalize,
469
+ )
470
+
471
+ disp = cls(confusion_matrix=cm, display_labels=display_labels)
472
+
473
+ return disp.plot(
474
+ include_values=include_values,
475
+ cmap=cmap,
476
+ ax=ax,
477
+ xticks_rotation=xticks_rotation,
478
+ values_format=values_format,
479
+ colorbar=colorbar,
480
+ im_kw=im_kw,
481
+ text_kw=text_kw,
482
+ )
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/det_curve.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import scipy as sp
2
+
3
+ from .base import _get_response
4
+
5
+ from .. import det_curve
6
+ from .._base import _check_pos_label_consistency
7
+
8
+ from ...utils import check_matplotlib_support
9
+
10
+
11
+ class DetCurveDisplay:
12
+ """DET curve visualization.
13
+
14
+ It is recommend to use :func:`~sklearn.metrics.DetCurveDisplay.from_estimator`
15
+ or :func:`~sklearn.metrics.DetCurveDisplay.from_predictions` to create a
16
+ visualizer. All parameters are stored as attributes.
17
+
18
+ Read more in the :ref:`User Guide <visualizations>`.
19
+
20
+ .. versionadded:: 0.24
21
+
22
+ Parameters
23
+ ----------
24
+ fpr : ndarray
25
+ False positive rate.
26
+
27
+ fnr : ndarray
28
+ False negative rate.
29
+
30
+ estimator_name : str, default=None
31
+ Name of estimator. If None, the estimator name is not shown.
32
+
33
+ pos_label : str or int, default=None
34
+ The label of the positive class.
35
+
36
+ Attributes
37
+ ----------
38
+ line_ : matplotlib Artist
39
+ DET Curve.
40
+
41
+ ax_ : matplotlib Axes
42
+ Axes with DET Curve.
43
+
44
+ figure_ : matplotlib Figure
45
+ Figure containing the curve.
46
+
47
+ See Also
48
+ --------
49
+ det_curve : Compute error rates for different probability thresholds.
50
+ DetCurveDisplay.from_estimator : Plot DET curve given an estimator and
51
+ some data.
52
+ DetCurveDisplay.from_predictions : Plot DET curve given the true and
53
+ predicted labels.
54
+
55
+ Examples
56
+ --------
57
+ >>> import matplotlib.pyplot as plt
58
+ >>> from sklearn.datasets import make_classification
59
+ >>> from sklearn.metrics import det_curve, DetCurveDisplay
60
+ >>> from sklearn.model_selection import train_test_split
61
+ >>> from sklearn.svm import SVC
62
+ >>> X, y = make_classification(n_samples=1000, random_state=0)
63
+ >>> X_train, X_test, y_train, y_test = train_test_split(
64
+ ... X, y, test_size=0.4, random_state=0)
65
+ >>> clf = SVC(random_state=0).fit(X_train, y_train)
66
+ >>> y_pred = clf.decision_function(X_test)
67
+ >>> fpr, fnr, _ = det_curve(y_test, y_pred)
68
+ >>> display = DetCurveDisplay(
69
+ ... fpr=fpr, fnr=fnr, estimator_name="SVC"
70
+ ... )
71
+ >>> display.plot()
72
+ <...>
73
+ >>> plt.show()
74
+ """
75
+
76
+ def __init__(self, *, fpr, fnr, estimator_name=None, pos_label=None):
77
+ self.fpr = fpr
78
+ self.fnr = fnr
79
+ self.estimator_name = estimator_name
80
+ self.pos_label = pos_label
81
+
82
+ @classmethod
83
+ def from_estimator(
84
+ cls,
85
+ estimator,
86
+ X,
87
+ y,
88
+ *,
89
+ sample_weight=None,
90
+ response_method="auto",
91
+ pos_label=None,
92
+ name=None,
93
+ ax=None,
94
+ **kwargs,
95
+ ):
96
+ """Plot DET curve given an estimator and data.
97
+
98
+ Read more in the :ref:`User Guide <visualizations>`.
99
+
100
+ .. versionadded:: 1.0
101
+
102
+ Parameters
103
+ ----------
104
+ estimator : estimator instance
105
+ Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline`
106
+ in which the last estimator is a classifier.
107
+
108
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
109
+ Input values.
110
+
111
+ y : array-like of shape (n_samples,)
112
+ Target values.
113
+
114
+ sample_weight : array-like of shape (n_samples,), default=None
115
+ Sample weights.
116
+
117
+ response_method : {'predict_proba', 'decision_function', 'auto'} \
118
+ default='auto'
119
+ Specifies whether to use :term:`predict_proba` or
120
+ :term:`decision_function` as the predicted target response. If set
121
+ to 'auto', :term:`predict_proba` is tried first and if it does not
122
+ exist :term:`decision_function` is tried next.
123
+
124
+ pos_label : str or int, default=None
125
+ The label of the positive class. When `pos_label=None`, if `y_true`
126
+ is in {-1, 1} or {0, 1}, `pos_label` is set to 1, otherwise an
127
+ error will be raised.
128
+
129
+ name : str, default=None
130
+ Name of DET curve for labeling. If `None`, use the name of the
131
+ estimator.
132
+
133
+ ax : matplotlib axes, default=None
134
+ Axes object to plot on. If `None`, a new figure and axes is
135
+ created.
136
+
137
+ **kwargs : dict
138
+ Additional keywords arguments passed to matplotlib `plot` function.
139
+
140
+ Returns
141
+ -------
142
+ display : :class:`~sklearn.metrics.DetCurveDisplay`
143
+ Object that stores computed values.
144
+
145
+ See Also
146
+ --------
147
+ det_curve : Compute error rates for different probability thresholds.
148
+ DetCurveDisplay.from_predictions : Plot DET curve given the true and
149
+ predicted labels.
150
+
151
+ Examples
152
+ --------
153
+ >>> import matplotlib.pyplot as plt
154
+ >>> from sklearn.datasets import make_classification
155
+ >>> from sklearn.metrics import DetCurveDisplay
156
+ >>> from sklearn.model_selection import train_test_split
157
+ >>> from sklearn.svm import SVC
158
+ >>> X, y = make_classification(n_samples=1000, random_state=0)
159
+ >>> X_train, X_test, y_train, y_test = train_test_split(
160
+ ... X, y, test_size=0.4, random_state=0)
161
+ >>> clf = SVC(random_state=0).fit(X_train, y_train)
162
+ >>> DetCurveDisplay.from_estimator(
163
+ ... clf, X_test, y_test)
164
+ <...>
165
+ >>> plt.show()
166
+ """
167
+ check_matplotlib_support(f"{cls.__name__}.from_estimator")
168
+
169
+ name = estimator.__class__.__name__ if name is None else name
170
+
171
+ y_pred, pos_label = _get_response(
172
+ X,
173
+ estimator,
174
+ response_method,
175
+ pos_label=pos_label,
176
+ )
177
+
178
+ return cls.from_predictions(
179
+ y_true=y,
180
+ y_pred=y_pred,
181
+ sample_weight=sample_weight,
182
+ name=name,
183
+ ax=ax,
184
+ pos_label=pos_label,
185
+ **kwargs,
186
+ )
187
+
188
+ @classmethod
189
+ def from_predictions(
190
+ cls,
191
+ y_true,
192
+ y_pred,
193
+ *,
194
+ sample_weight=None,
195
+ pos_label=None,
196
+ name=None,
197
+ ax=None,
198
+ **kwargs,
199
+ ):
200
+ """Plot the DET curve given the true and predicted labels.
201
+
202
+ Read more in the :ref:`User Guide <visualizations>`.
203
+
204
+ .. versionadded:: 1.0
205
+
206
+ Parameters
207
+ ----------
208
+ y_true : array-like of shape (n_samples,)
209
+ True labels.
210
+
211
+ y_pred : array-like of shape (n_samples,)
212
+ Target scores, can either be probability estimates of the positive
213
+ class, confidence values, or non-thresholded measure of decisions
214
+ (as returned by `decision_function` on some classifiers).
215
+
216
+ sample_weight : array-like of shape (n_samples,), default=None
217
+ Sample weights.
218
+
219
+ pos_label : str or int, default=None
220
+ The label of the positive class. When `pos_label=None`, if `y_true`
221
+ is in {-1, 1} or {0, 1}, `pos_label` is set to 1, otherwise an
222
+ error will be raised.
223
+
224
+ name : str, default=None
225
+ Name of DET curve for labeling. If `None`, name will be set to
226
+ `"Classifier"`.
227
+
228
+ ax : matplotlib axes, default=None
229
+ Axes object to plot on. If `None`, a new figure and axes is
230
+ created.
231
+
232
+ **kwargs : dict
233
+ Additional keywords arguments passed to matplotlib `plot` function.
234
+
235
+ Returns
236
+ -------
237
+ display : :class:`~sklearn.metrics.DetCurveDisplay`
238
+ Object that stores computed values.
239
+
240
+ See Also
241
+ --------
242
+ det_curve : Compute error rates for different probability thresholds.
243
+ DetCurveDisplay.from_estimator : Plot DET curve given an estimator and
244
+ some data.
245
+
246
+ Examples
247
+ --------
248
+ >>> import matplotlib.pyplot as plt
249
+ >>> from sklearn.datasets import make_classification
250
+ >>> from sklearn.metrics import DetCurveDisplay
251
+ >>> from sklearn.model_selection import train_test_split
252
+ >>> from sklearn.svm import SVC
253
+ >>> X, y = make_classification(n_samples=1000, random_state=0)
254
+ >>> X_train, X_test, y_train, y_test = train_test_split(
255
+ ... X, y, test_size=0.4, random_state=0)
256
+ >>> clf = SVC(random_state=0).fit(X_train, y_train)
257
+ >>> y_pred = clf.decision_function(X_test)
258
+ >>> DetCurveDisplay.from_predictions(
259
+ ... y_test, y_pred)
260
+ <...>
261
+ >>> plt.show()
262
+ """
263
+ check_matplotlib_support(f"{cls.__name__}.from_predictions")
264
+ fpr, fnr, _ = det_curve(
265
+ y_true,
266
+ y_pred,
267
+ pos_label=pos_label,
268
+ sample_weight=sample_weight,
269
+ )
270
+
271
+ pos_label = _check_pos_label_consistency(pos_label, y_true)
272
+ name = "Classifier" if name is None else name
273
+
274
+ viz = DetCurveDisplay(
275
+ fpr=fpr,
276
+ fnr=fnr,
277
+ estimator_name=name,
278
+ pos_label=pos_label,
279
+ )
280
+
281
+ return viz.plot(ax=ax, name=name, **kwargs)
282
+
283
+ def plot(self, ax=None, *, name=None, **kwargs):
284
+ """Plot visualization.
285
+
286
+ Parameters
287
+ ----------
288
+ ax : matplotlib axes, default=None
289
+ Axes object to plot on. If `None`, a new figure and axes is
290
+ created.
291
+
292
+ name : str, default=None
293
+ Name of DET curve for labeling. If `None`, use `estimator_name` if
294
+ it is not `None`, otherwise no labeling is shown.
295
+
296
+ **kwargs : dict
297
+ Additional keywords arguments passed to matplotlib `plot` function.
298
+
299
+ Returns
300
+ -------
301
+ display : :class:`~sklearn.metrics.plot.DetCurveDisplay`
302
+ Object that stores computed values.
303
+ """
304
+ check_matplotlib_support("DetCurveDisplay.plot")
305
+
306
+ name = self.estimator_name if name is None else name
307
+ line_kwargs = {} if name is None else {"label": name}
308
+ line_kwargs.update(**kwargs)
309
+
310
+ import matplotlib.pyplot as plt
311
+
312
+ if ax is None:
313
+ _, ax = plt.subplots()
314
+
315
+ (self.line_,) = ax.plot(
316
+ sp.stats.norm.ppf(self.fpr),
317
+ sp.stats.norm.ppf(self.fnr),
318
+ **line_kwargs,
319
+ )
320
+ info_pos_label = (
321
+ f" (Positive label: {self.pos_label})" if self.pos_label is not None else ""
322
+ )
323
+
324
+ xlabel = "False Positive Rate" + info_pos_label
325
+ ylabel = "False Negative Rate" + info_pos_label
326
+ ax.set(xlabel=xlabel, ylabel=ylabel)
327
+
328
+ if "label" in line_kwargs:
329
+ ax.legend(loc="lower right")
330
+
331
+ ticks = [0.001, 0.01, 0.05, 0.20, 0.5, 0.80, 0.95, 0.99, 0.999]
332
+ tick_locations = sp.stats.norm.ppf(ticks)
333
+ tick_labels = [
334
+ "{:.0%}".format(s) if (100 * s).is_integer() else "{:.1%}".format(s)
335
+ for s in ticks
336
+ ]
337
+ ax.set_xticks(tick_locations)
338
+ ax.set_xticklabels(tick_labels)
339
+ ax.set_xlim(-3, 3)
340
+ ax.set_yticks(tick_locations)
341
+ ax.set_yticklabels(tick_labels)
342
+ ax.set_ylim(-3, 3)
343
+
344
+ self.ax_ = ax
345
+ self.figure_ = ax.figure
346
+ return self
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/precision_recall_curve.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sklearn.base import is_classifier
2
+ from .base import _get_response
3
+
4
+ from .. import average_precision_score
5
+ from .. import precision_recall_curve
6
+ from .._base import _check_pos_label_consistency
7
+ from .._classification import check_consistent_length
8
+
9
+ from ...utils import check_matplotlib_support
10
+
11
+
12
+ class PrecisionRecallDisplay:
13
+ """Precision Recall visualization.
14
+
15
+ It is recommend to use
16
+ :func:`~sklearn.metrics.PrecisionRecallDisplay.from_estimator` or
17
+ :func:`~sklearn.metrics.PrecisionRecallDisplay.from_predictions` to create
18
+ a :class:`~sklearn.metrics.PredictionRecallDisplay`. All parameters are
19
+ stored as attributes.
20
+
21
+ Read more in the :ref:`User Guide <visualizations>`.
22
+
23
+ Parameters
24
+ ----------
25
+ precision : ndarray
26
+ Precision values.
27
+
28
+ recall : ndarray
29
+ Recall values.
30
+
31
+ average_precision : float, default=None
32
+ Average precision. If None, the average precision is not shown.
33
+
34
+ estimator_name : str, default=None
35
+ Name of estimator. If None, then the estimator name is not shown.
36
+
37
+ pos_label : str or int, default=None
38
+ The class considered as the positive class. If None, the class will not
39
+ be shown in the legend.
40
+
41
+ .. versionadded:: 0.24
42
+
43
+ Attributes
44
+ ----------
45
+ line_ : matplotlib Artist
46
+ Precision recall curve.
47
+
48
+ ax_ : matplotlib Axes
49
+ Axes with precision recall curve.
50
+
51
+ figure_ : matplotlib Figure
52
+ Figure containing the curve.
53
+
54
+ See Also
55
+ --------
56
+ precision_recall_curve : Compute precision-recall pairs for different
57
+ probability thresholds.
58
+ PrecisionRecallDisplay.from_estimator : Plot Precision Recall Curve given
59
+ a binary classifier.
60
+ PrecisionRecallDisplay.from_predictions : Plot Precision Recall Curve
61
+ using predictions from a binary classifier.
62
+
63
+ Notes
64
+ -----
65
+ The average precision (cf. :func:`~sklearn.metrics.average_precision`) in
66
+ scikit-learn is computed without any interpolation. To be consistent with
67
+ this metric, the precision-recall curve is plotted without any
68
+ interpolation as well (step-wise style).
69
+
70
+ You can change this style by passing the keyword argument
71
+ `drawstyle="default"` in :meth:`plot`, :meth:`from_estimator`, or
72
+ :meth:`from_predictions`. However, the curve will not be strictly
73
+ consistent with the reported average precision.
74
+
75
+ Examples
76
+ --------
77
+ >>> import matplotlib.pyplot as plt
78
+ >>> from sklearn.datasets import make_classification
79
+ >>> from sklearn.metrics import (precision_recall_curve,
80
+ ... PrecisionRecallDisplay)
81
+ >>> from sklearn.model_selection import train_test_split
82
+ >>> from sklearn.svm import SVC
83
+ >>> X, y = make_classification(random_state=0)
84
+ >>> X_train, X_test, y_train, y_test = train_test_split(X, y,
85
+ ... random_state=0)
86
+ >>> clf = SVC(random_state=0)
87
+ >>> clf.fit(X_train, y_train)
88
+ SVC(random_state=0)
89
+ >>> predictions = clf.predict(X_test)
90
+ >>> precision, recall, _ = precision_recall_curve(y_test, predictions)
91
+ >>> disp = PrecisionRecallDisplay(precision=precision, recall=recall)
92
+ >>> disp.plot()
93
+ <...>
94
+ >>> plt.show()
95
+ """
96
+
97
+ def __init__(
98
+ self,
99
+ precision,
100
+ recall,
101
+ *,
102
+ average_precision=None,
103
+ estimator_name=None,
104
+ pos_label=None,
105
+ ):
106
+ self.estimator_name = estimator_name
107
+ self.precision = precision
108
+ self.recall = recall
109
+ self.average_precision = average_precision
110
+ self.pos_label = pos_label
111
+
112
+ def plot(self, ax=None, *, name=None, **kwargs):
113
+ """Plot visualization.
114
+
115
+ Extra keyword arguments will be passed to matplotlib's `plot`.
116
+
117
+ Parameters
118
+ ----------
119
+ ax : Matplotlib Axes, default=None
120
+ Axes object to plot on. If `None`, a new figure and axes is
121
+ created.
122
+
123
+ name : str, default=None
124
+ Name of precision recall curve for labeling. If `None`, use
125
+ `estimator_name` if not `None`, otherwise no labeling is shown.
126
+
127
+ **kwargs : dict
128
+ Keyword arguments to be passed to matplotlib's `plot`.
129
+
130
+ Returns
131
+ -------
132
+ display : :class:`~sklearn.metrics.PrecisionRecallDisplay`
133
+ Object that stores computed values.
134
+
135
+ Notes
136
+ -----
137
+ The average precision (cf. :func:`~sklearn.metrics.average_precision`)
138
+ in scikit-learn is computed without any interpolation. To be consistent
139
+ with this metric, the precision-recall curve is plotted without any
140
+ interpolation as well (step-wise style).
141
+
142
+ You can change this style by passing the keyword argument
143
+ `drawstyle="default"`. However, the curve will not be strictly
144
+ consistent with the reported average precision.
145
+ """
146
+ check_matplotlib_support("PrecisionRecallDisplay.plot")
147
+
148
+ name = self.estimator_name if name is None else name
149
+
150
+ line_kwargs = {"drawstyle": "steps-post"}
151
+ if self.average_precision is not None and name is not None:
152
+ line_kwargs["label"] = f"{name} (AP = {self.average_precision:0.2f})"
153
+ elif self.average_precision is not None:
154
+ line_kwargs["label"] = f"AP = {self.average_precision:0.2f}"
155
+ elif name is not None:
156
+ line_kwargs["label"] = name
157
+ line_kwargs.update(**kwargs)
158
+
159
+ import matplotlib.pyplot as plt
160
+
161
+ if ax is None:
162
+ fig, ax = plt.subplots()
163
+
164
+ (self.line_,) = ax.plot(self.recall, self.precision, **line_kwargs)
165
+ info_pos_label = (
166
+ f" (Positive label: {self.pos_label})" if self.pos_label is not None else ""
167
+ )
168
+
169
+ xlabel = "Recall" + info_pos_label
170
+ ylabel = "Precision" + info_pos_label
171
+ ax.set(xlabel=xlabel, ylabel=ylabel)
172
+
173
+ if "label" in line_kwargs:
174
+ ax.legend(loc="lower left")
175
+
176
+ self.ax_ = ax
177
+ self.figure_ = ax.figure
178
+ return self
179
+
180
+ @classmethod
181
+ def from_estimator(
182
+ cls,
183
+ estimator,
184
+ X,
185
+ y,
186
+ *,
187
+ sample_weight=None,
188
+ pos_label=None,
189
+ response_method="auto",
190
+ name=None,
191
+ ax=None,
192
+ **kwargs,
193
+ ):
194
+ """Plot precision-recall curve given an estimator and some data.
195
+
196
+ Parameters
197
+ ----------
198
+ estimator : estimator instance
199
+ Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline`
200
+ in which the last estimator is a classifier.
201
+
202
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
203
+ Input values.
204
+
205
+ y : array-like of shape (n_samples,)
206
+ Target values.
207
+
208
+ sample_weight : array-like of shape (n_samples,), default=None
209
+ Sample weights.
210
+
211
+ pos_label : str or int, default=None
212
+ The class considered as the positive class when computing the
213
+ precision and recall metrics. By default, `estimators.classes_[1]`
214
+ is considered as the positive class.
215
+
216
+ response_method : {'predict_proba', 'decision_function', 'auto'}, \
217
+ default='auto'
218
+ Specifies whether to use :term:`predict_proba` or
219
+ :term:`decision_function` as the target response. If set to 'auto',
220
+ :term:`predict_proba` is tried first and if it does not exist
221
+ :term:`decision_function` is tried next.
222
+
223
+ name : str, default=None
224
+ Name for labeling curve. If `None`, no name is used.
225
+
226
+ ax : matplotlib axes, default=None
227
+ Axes object to plot on. If `None`, a new figure and axes is created.
228
+
229
+ **kwargs : dict
230
+ Keyword arguments to be passed to matplotlib's `plot`.
231
+
232
+ Returns
233
+ -------
234
+ display : :class:`~sklearn.metrics.PrecisionRecallDisplay`
235
+
236
+ See Also
237
+ --------
238
+ PrecisionRecallDisplay.from_predictions : Plot precision-recall curve
239
+ using estimated probabilities or output of decision function.
240
+
241
+ Notes
242
+ -----
243
+ The average precision (cf. :func:`~sklearn.metrics.average_precision`)
244
+ in scikit-learn is computed without any interpolation. To be consistent
245
+ with this metric, the precision-recall curve is plotted without any
246
+ interpolation as well (step-wise style).
247
+
248
+ You can change this style by passing the keyword argument
249
+ `drawstyle="default"`. However, the curve will not be strictly
250
+ consistent with the reported average precision.
251
+
252
+ Examples
253
+ --------
254
+ >>> import matplotlib.pyplot as plt
255
+ >>> from sklearn.datasets import make_classification
256
+ >>> from sklearn.metrics import PrecisionRecallDisplay
257
+ >>> from sklearn.model_selection import train_test_split
258
+ >>> from sklearn.linear_model import LogisticRegression
259
+ >>> X, y = make_classification(random_state=0)
260
+ >>> X_train, X_test, y_train, y_test = train_test_split(
261
+ ... X, y, random_state=0)
262
+ >>> clf = LogisticRegression()
263
+ >>> clf.fit(X_train, y_train)
264
+ LogisticRegression()
265
+ >>> PrecisionRecallDisplay.from_estimator(
266
+ ... clf, X_test, y_test)
267
+ <...>
268
+ >>> plt.show()
269
+ """
270
+ method_name = f"{cls.__name__}.from_estimator"
271
+ check_matplotlib_support(method_name)
272
+ if not is_classifier(estimator):
273
+ raise ValueError(f"{method_name} only supports classifiers")
274
+ y_pred, pos_label = _get_response(
275
+ X,
276
+ estimator,
277
+ response_method,
278
+ pos_label=pos_label,
279
+ )
280
+
281
+ name = name if name is not None else estimator.__class__.__name__
282
+
283
+ return cls.from_predictions(
284
+ y,
285
+ y_pred,
286
+ sample_weight=sample_weight,
287
+ name=name,
288
+ pos_label=pos_label,
289
+ ax=ax,
290
+ **kwargs,
291
+ )
292
+
293
+ @classmethod
294
+ def from_predictions(
295
+ cls,
296
+ y_true,
297
+ y_pred,
298
+ *,
299
+ sample_weight=None,
300
+ pos_label=None,
301
+ name=None,
302
+ ax=None,
303
+ **kwargs,
304
+ ):
305
+ """Plot precision-recall curve given binary class predictions.
306
+
307
+ Parameters
308
+ ----------
309
+ y_true : array-like of shape (n_samples,)
310
+ True binary labels.
311
+
312
+ y_pred : array-like of shape (n_samples,)
313
+ Estimated probabilities or output of decision function.
314
+
315
+ sample_weight : array-like of shape (n_samples,), default=None
316
+ Sample weights.
317
+
318
+ pos_label : str or int, default=None
319
+ The class considered as the positive class when computing the
320
+ precision and recall metrics.
321
+
322
+ name : str, default=None
323
+ Name for labeling curve. If `None`, name will be set to
324
+ `"Classifier"`.
325
+
326
+ ax : matplotlib axes, default=None
327
+ Axes object to plot on. If `None`, a new figure and axes is created.
328
+
329
+ **kwargs : dict
330
+ Keyword arguments to be passed to matplotlib's `plot`.
331
+
332
+ Returns
333
+ -------
334
+ display : :class:`~sklearn.metrics.PrecisionRecallDisplay`
335
+
336
+ See Also
337
+ --------
338
+ PrecisionRecallDisplay.from_estimator : Plot precision-recall curve
339
+ using an estimator.
340
+
341
+ Notes
342
+ -----
343
+ The average precision (cf. :func:`~sklearn.metrics.average_precision`)
344
+ in scikit-learn is computed without any interpolation. To be consistent
345
+ with this metric, the precision-recall curve is plotted without any
346
+ interpolation as well (step-wise style).
347
+
348
+ You can change this style by passing the keyword argument
349
+ `drawstyle="default"`. However, the curve will not be strictly
350
+ consistent with the reported average precision.
351
+
352
+ Examples
353
+ --------
354
+ >>> import matplotlib.pyplot as plt
355
+ >>> from sklearn.datasets import make_classification
356
+ >>> from sklearn.metrics import PrecisionRecallDisplay
357
+ >>> from sklearn.model_selection import train_test_split
358
+ >>> from sklearn.linear_model import LogisticRegression
359
+ >>> X, y = make_classification(random_state=0)
360
+ >>> X_train, X_test, y_train, y_test = train_test_split(
361
+ ... X, y, random_state=0)
362
+ >>> clf = LogisticRegression()
363
+ >>> clf.fit(X_train, y_train)
364
+ LogisticRegression()
365
+ >>> y_pred = clf.predict_proba(X_test)[:, 1]
366
+ >>> PrecisionRecallDisplay.from_predictions(
367
+ ... y_test, y_pred)
368
+ <...>
369
+ >>> plt.show()
370
+ """
371
+ check_matplotlib_support(f"{cls.__name__}.from_predictions")
372
+
373
+ check_consistent_length(y_true, y_pred, sample_weight)
374
+ pos_label = _check_pos_label_consistency(pos_label, y_true)
375
+
376
+ precision, recall, _ = precision_recall_curve(
377
+ y_true, y_pred, pos_label=pos_label, sample_weight=sample_weight
378
+ )
379
+ average_precision = average_precision_score(
380
+ y_true, y_pred, pos_label=pos_label, sample_weight=sample_weight
381
+ )
382
+
383
+ name = name if name is not None else "Classifier"
384
+
385
+ viz = PrecisionRecallDisplay(
386
+ precision=precision,
387
+ recall=recall,
388
+ average_precision=average_precision,
389
+ estimator_name=name,
390
+ pos_label=pos_label,
391
+ )
392
+
393
+ return viz.plot(ax=ax, name=name, **kwargs)
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/regression.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numbers
2
+
3
+ import numpy as np
4
+
5
+ from ...utils import check_matplotlib_support
6
+ from ...utils import check_random_state
7
+ from ...utils import _safe_indexing
8
+
9
+
10
+ class PredictionErrorDisplay:
11
+ """Visualization of the prediction error of a regression model.
12
+
13
+ This tool can display "residuals vs predicted" or "actual vs predicted"
14
+ using scatter plots to qualitatively assess the behavior of a regressor,
15
+ preferably on held-out data points.
16
+
17
+ See the details in the docstrings of
18
+ :func:`~sklearn.metrics.PredictionErrorDisplay.from_estimator` or
19
+ :func:`~sklearn.metrics.PredictionErrorDisplay.from_predictions` to
20
+ create a visualizer. All parameters are stored as attributes.
21
+
22
+ For general information regarding `scikit-learn` visualization tools, read
23
+ more in the :ref:`Visualization Guide <visualizations>`.
24
+ For details regarding interpreting these plots, refer to the
25
+ :ref:`Model Evaluation Guide <visualization_regression_evaluation>`.
26
+
27
+ .. versionadded:: 1.2
28
+
29
+ Parameters
30
+ ----------
31
+ y_true : ndarray of shape (n_samples,)
32
+ True values.
33
+
34
+ y_pred : ndarray of shape (n_samples,)
35
+ Prediction values.
36
+
37
+ Attributes
38
+ ----------
39
+ line_ : matplotlib Artist
40
+ Optimal line representing `y_true == y_pred`. Therefore, it is a
41
+ diagonal line for `kind="predictions"` and a horizontal line for
42
+ `kind="residuals"`.
43
+
44
+ errors_lines_ : matplotlib Artist or None
45
+ Residual lines. If `with_errors=False`, then it is set to `None`.
46
+
47
+ scatter_ : matplotlib Artist
48
+ Scatter data points.
49
+
50
+ ax_ : matplotlib Axes
51
+ Axes with the different matplotlib axis.
52
+
53
+ figure_ : matplotlib Figure
54
+ Figure containing the scatter and lines.
55
+
56
+ See Also
57
+ --------
58
+ PredictionErrorDisplay.from_estimator : Prediction error visualization
59
+ given an estimator and some data.
60
+ PredictionErrorDisplay.from_predictions : Prediction error visualization
61
+ given the true and predicted targets.
62
+
63
+ Examples
64
+ --------
65
+ >>> import matplotlib.pyplot as plt
66
+ >>> from sklearn.datasets import load_diabetes
67
+ >>> from sklearn.linear_model import Ridge
68
+ >>> from sklearn.metrics import PredictionErrorDisplay
69
+ >>> X, y = load_diabetes(return_X_y=True)
70
+ >>> ridge = Ridge().fit(X, y)
71
+ >>> y_pred = ridge.predict(X)
72
+ >>> display = PredictionErrorDisplay(y_true=y, y_pred=y_pred)
73
+ >>> display.plot()
74
+ <...>
75
+ >>> plt.show()
76
+ """
77
+
78
+ def __init__(self, *, y_true, y_pred):
79
+ self.y_true = y_true
80
+ self.y_pred = y_pred
81
+
82
+ def plot(
83
+ self,
84
+ ax=None,
85
+ *,
86
+ kind="residual_vs_predicted",
87
+ scatter_kwargs=None,
88
+ line_kwargs=None,
89
+ ):
90
+ """Plot visualization.
91
+
92
+ Extra keyword arguments will be passed to matplotlib's ``plot``.
93
+
94
+ Parameters
95
+ ----------
96
+ ax : matplotlib axes, default=None
97
+ Axes object to plot on. If `None`, a new figure and axes is
98
+ created.
99
+
100
+ kind : {"actual_vs_predicted", "residual_vs_predicted"}, \
101
+ default="residual_vs_predicted"
102
+ The type of plot to draw:
103
+
104
+ - "actual_vs_predicted" draws the the observed values (y-axis) vs.
105
+ the predicted values (x-axis).
106
+ - "residual_vs_predicted" draws the residuals, i.e difference
107
+ between observed and predicted values, (y-axis) vs. the predicted
108
+ values (x-axis).
109
+
110
+ scatter_kwargs : dict, default=None
111
+ Dictionary with keywords passed to the `matplotlib.pyplot.scatter`
112
+ call.
113
+
114
+ line_kwargs : dict, default=None
115
+ Dictionary with keyword passed to the `matplotlib.pyplot.plot`
116
+ call to draw the optimal line.
117
+
118
+ Returns
119
+ -------
120
+ display : :class:`~sklearn.metrics.plot.PredictionErrorDisplay`
121
+ Object that stores computed values.
122
+ """
123
+ check_matplotlib_support(f"{self.__class__.__name__}.plot")
124
+
125
+ expected_kind = ("actual_vs_predicted", "residual_vs_predicted")
126
+ if kind not in expected_kind:
127
+ raise ValueError(
128
+ f"`kind` must be one of {', '.join(expected_kind)}. "
129
+ f"Got {kind!r} instead."
130
+ )
131
+
132
+ import matplotlib.pyplot as plt
133
+
134
+ if scatter_kwargs is None:
135
+ scatter_kwargs = {}
136
+ if line_kwargs is None:
137
+ line_kwargs = {}
138
+
139
+ default_scatter_kwargs = {"color": "tab:blue", "alpha": 0.8}
140
+ default_line_kwargs = {"color": "black", "alpha": 0.7, "linestyle": "--"}
141
+
142
+ scatter_kwargs = {**default_scatter_kwargs, **scatter_kwargs}
143
+ line_kwargs = {**default_line_kwargs, **line_kwargs}
144
+
145
+ if ax is None:
146
+ _, ax = plt.subplots()
147
+
148
+ if kind == "actual_vs_predicted":
149
+ max_value = max(np.max(self.y_true), np.max(self.y_pred))
150
+ min_value = min(np.min(self.y_true), np.min(self.y_pred))
151
+ self.line_ = ax.plot(
152
+ [min_value, max_value], [min_value, max_value], **line_kwargs
153
+ )[0]
154
+
155
+ x_data, y_data = self.y_pred, self.y_true
156
+ xlabel, ylabel = "Predicted values", "Actual values"
157
+
158
+ self.scatter_ = ax.scatter(x_data, y_data, **scatter_kwargs)
159
+
160
+ # force to have a squared axis
161
+ ax.set_aspect("equal", adjustable="datalim")
162
+ ax.set_xticks(np.linspace(min_value, max_value, num=5))
163
+ ax.set_yticks(np.linspace(min_value, max_value, num=5))
164
+ else: # kind == "residual_vs_predicted"
165
+ self.line_ = ax.plot(
166
+ [np.min(self.y_pred), np.max(self.y_pred)],
167
+ [0, 0],
168
+ **line_kwargs,
169
+ )[0]
170
+ self.scatter_ = ax.scatter(
171
+ self.y_pred, self.y_true - self.y_pred, **scatter_kwargs
172
+ )
173
+ xlabel, ylabel = "Predicted values", "Residuals (actual - predicted)"
174
+
175
+ ax.set(xlabel=xlabel, ylabel=ylabel)
176
+
177
+ self.ax_ = ax
178
+ self.figure_ = ax.figure
179
+
180
+ return self
181
+
182
+ @classmethod
183
+ def from_estimator(
184
+ cls,
185
+ estimator,
186
+ X,
187
+ y,
188
+ *,
189
+ kind="residual_vs_predicted",
190
+ subsample=1_000,
191
+ random_state=None,
192
+ ax=None,
193
+ scatter_kwargs=None,
194
+ line_kwargs=None,
195
+ ):
196
+ """Plot the prediction error given a regressor and some data.
197
+
198
+ For general information regarding `scikit-learn` visualization tools,
199
+ read more in the :ref:`Visualization Guide <visualizations>`.
200
+ For details regarding interpreting these plots, refer to the
201
+ :ref:`Model Evaluation Guide <visualization_regression_evaluation>`.
202
+
203
+ .. versionadded:: 1.2
204
+
205
+ Parameters
206
+ ----------
207
+ estimator : estimator instance
208
+ Fitted regressor or a fitted :class:`~sklearn.pipeline.Pipeline`
209
+ in which the last estimator is a regressor.
210
+
211
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
212
+ Input values.
213
+
214
+ y : array-like of shape (n_samples,)
215
+ Target values.
216
+
217
+ kind : {"actual_vs_predicted", "residual_vs_predicted"}, \
218
+ default="residual_vs_predicted"
219
+ The type of plot to draw:
220
+
221
+ - "actual_vs_predicted" draws the the observed values (y-axis) vs.
222
+ the predicted values (x-axis).
223
+ - "residual_vs_predicted" draws the residuals, i.e difference
224
+ between observed and predicted values, (y-axis) vs. the predicted
225
+ values (x-axis).
226
+
227
+ subsample : float, int or None, default=1_000
228
+ Sampling the samples to be shown on the scatter plot. If `float`,
229
+ it should be between 0 and 1 and represents the proportion of the
230
+ original dataset. If `int`, it represents the number of samples
231
+ display on the scatter plot. If `None`, no subsampling will be
232
+ applied. by default, a 1000 samples or less will be displayed.
233
+
234
+ random_state : int or RandomState, default=None
235
+ Controls the randomness when `subsample` is not `None`.
236
+ See :term:`Glossary <random_state>` for details.
237
+
238
+ ax : matplotlib axes, default=None
239
+ Axes object to plot on. If `None`, a new figure and axes is
240
+ created.
241
+
242
+ scatter_kwargs : dict, default=None
243
+ Dictionary with keywords passed to the `matplotlib.pyplot.scatter`
244
+ call.
245
+
246
+ line_kwargs : dict, default=None
247
+ Dictionary with keyword passed to the `matplotlib.pyplot.plot`
248
+ call to draw the optimal line.
249
+
250
+ Returns
251
+ -------
252
+ display : :class:`~sklearn.metrics.PredictionErrorDisplay`
253
+ Object that stores the computed values.
254
+
255
+ See Also
256
+ --------
257
+ PredictionErrorDisplay : Prediction error visualization for regression.
258
+ PredictionErrorDisplay.from_predictions : Prediction error visualization
259
+ given the true and predicted targets.
260
+
261
+ Examples
262
+ --------
263
+ >>> import matplotlib.pyplot as plt
264
+ >>> from sklearn.datasets import load_diabetes
265
+ >>> from sklearn.linear_model import Ridge
266
+ >>> from sklearn.metrics import PredictionErrorDisplay
267
+ >>> X, y = load_diabetes(return_X_y=True)
268
+ >>> ridge = Ridge().fit(X, y)
269
+ >>> disp = PredictionErrorDisplay.from_estimator(ridge, X, y)
270
+ >>> plt.show()
271
+ """
272
+ check_matplotlib_support(f"{cls.__name__}.from_estimator")
273
+
274
+ y_pred = estimator.predict(X)
275
+
276
+ return cls.from_predictions(
277
+ y_true=y,
278
+ y_pred=y_pred,
279
+ kind=kind,
280
+ subsample=subsample,
281
+ random_state=random_state,
282
+ ax=ax,
283
+ scatter_kwargs=scatter_kwargs,
284
+ line_kwargs=line_kwargs,
285
+ )
286
+
287
+ @classmethod
288
+ def from_predictions(
289
+ cls,
290
+ y_true,
291
+ y_pred,
292
+ *,
293
+ kind="residual_vs_predicted",
294
+ subsample=1_000,
295
+ random_state=None,
296
+ ax=None,
297
+ scatter_kwargs=None,
298
+ line_kwargs=None,
299
+ ):
300
+ """Plot the prediction error given the true and predicted targets.
301
+
302
+ For general information regarding `scikit-learn` visualization tools,
303
+ read more in the :ref:`Visualization Guide <visualizations>`.
304
+ For details regarding interpreting these plots, refer to the
305
+ :ref:`Model Evaluation Guide <visualization_regression_evaluation>`.
306
+
307
+ .. versionadded:: 1.2
308
+
309
+ Parameters
310
+ ----------
311
+ y_true : array-like of shape (n_samples,)
312
+ True target values.
313
+
314
+ y_pred : array-like of shape (n_samples,)
315
+ Predicted target values.
316
+
317
+ kind : {"actual_vs_predicted", "residual_vs_predicted"}, \
318
+ default="residual_vs_predicted"
319
+ The type of plot to draw:
320
+
321
+ - "actual_vs_predicted" draws the the observed values (y-axis) vs.
322
+ the predicted values (x-axis).
323
+ - "residual_vs_predicted" draws the residuals, i.e difference
324
+ between observed and predicted values, (y-axis) vs. the predicted
325
+ values (x-axis).
326
+
327
+ subsample : float, int or None, default=1_000
328
+ Sampling the samples to be shown on the scatter plot. If `float`,
329
+ it should be between 0 and 1 and represents the proportion of the
330
+ original dataset. If `int`, it represents the number of samples
331
+ display on the scatter plot. If `None`, no subsampling will be
332
+ applied. by default, a 1000 samples or less will be displayed.
333
+
334
+ random_state : int or RandomState, default=None
335
+ Controls the randomness when `subsample` is not `None`.
336
+ See :term:`Glossary <random_state>` for details.
337
+
338
+ ax : matplotlib axes, default=None
339
+ Axes object to plot on. If `None`, a new figure and axes is
340
+ created.
341
+
342
+ scatter_kwargs : dict, default=None
343
+ Dictionary with keywords passed to the `matplotlib.pyplot.scatter`
344
+ call.
345
+
346
+ line_kwargs : dict, default=None
347
+ Dictionary with keyword passed to the `matplotlib.pyplot.plot`
348
+ call to draw the optimal line.
349
+
350
+ Returns
351
+ -------
352
+ display : :class:`~sklearn.metrics.PredictionErrorDisplay`
353
+ Object that stores the computed values.
354
+
355
+ See Also
356
+ --------
357
+ PredictionErrorDisplay : Prediction error visualization for regression.
358
+ PredictionErrorDisplay.from_estimator : Prediction error visualization
359
+ given an estimator and some data.
360
+
361
+ Examples
362
+ --------
363
+ >>> import matplotlib.pyplot as plt
364
+ >>> from sklearn.datasets import load_diabetes
365
+ >>> from sklearn.linear_model import Ridge
366
+ >>> from sklearn.metrics import PredictionErrorDisplay
367
+ >>> X, y = load_diabetes(return_X_y=True)
368
+ >>> ridge = Ridge().fit(X, y)
369
+ >>> y_pred = ridge.predict(X)
370
+ >>> disp = PredictionErrorDisplay.from_predictions(y_true=y, y_pred=y_pred)
371
+ >>> plt.show()
372
+ """
373
+ check_matplotlib_support(f"{cls.__name__}.from_predictions")
374
+
375
+ random_state = check_random_state(random_state)
376
+
377
+ n_samples = len(y_true)
378
+ if isinstance(subsample, numbers.Integral):
379
+ if subsample <= 0:
380
+ raise ValueError(
381
+ f"When an integer, subsample={subsample} should be positive."
382
+ )
383
+ elif isinstance(subsample, numbers.Real):
384
+ if subsample <= 0 or subsample >= 1:
385
+ raise ValueError(
386
+ f"When a floating-point, subsample={subsample} should"
387
+ " be in the (0, 1) range."
388
+ )
389
+ subsample = int(n_samples * subsample)
390
+
391
+ if subsample is not None and subsample < n_samples:
392
+ indices = random_state.choice(np.arange(n_samples), size=subsample)
393
+ y_true = _safe_indexing(y_true, indices, axis=0)
394
+ y_pred = _safe_indexing(y_pred, indices, axis=0)
395
+
396
+ viz = PredictionErrorDisplay(
397
+ y_true=y_true,
398
+ y_pred=y_pred,
399
+ )
400
+
401
+ return viz.plot(
402
+ ax=ax,
403
+ kind=kind,
404
+ scatter_kwargs=scatter_kwargs,
405
+ line_kwargs=line_kwargs,
406
+ )
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/roc_curve.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .base import _get_response
2
+
3
+ from .. import auc
4
+ from .. import roc_curve
5
+ from .._base import _check_pos_label_consistency
6
+
7
+ from ...utils import check_matplotlib_support
8
+
9
+
10
+ class RocCurveDisplay:
11
+ """ROC Curve visualization.
12
+
13
+ It is recommend to use
14
+ :func:`~sklearn.metrics.RocCurveDisplay.from_estimator` or
15
+ :func:`~sklearn.metrics.RocCurveDisplay.from_predictions` to create
16
+ a :class:`~sklearn.metrics.RocCurveDisplay`. All parameters are
17
+ stored as attributes.
18
+
19
+ Read more in the :ref:`User Guide <visualizations>`.
20
+
21
+ Parameters
22
+ ----------
23
+ fpr : ndarray
24
+ False positive rate.
25
+
26
+ tpr : ndarray
27
+ True positive rate.
28
+
29
+ roc_auc : float, default=None
30
+ Area under ROC curve. If None, the roc_auc score is not shown.
31
+
32
+ estimator_name : str, default=None
33
+ Name of estimator. If None, the estimator name is not shown.
34
+
35
+ pos_label : str or int, default=None
36
+ The class considered as the positive class when computing the roc auc
37
+ metrics. By default, `estimators.classes_[1]` is considered
38
+ as the positive class.
39
+
40
+ .. versionadded:: 0.24
41
+
42
+ Attributes
43
+ ----------
44
+ line_ : matplotlib Artist
45
+ ROC Curve.
46
+
47
+ ax_ : matplotlib Axes
48
+ Axes with ROC Curve.
49
+
50
+ figure_ : matplotlib Figure
51
+ Figure containing the curve.
52
+
53
+ See Also
54
+ --------
55
+ roc_curve : Compute Receiver operating characteristic (ROC) curve.
56
+ RocCurveDisplay.from_estimator : Plot Receiver Operating Characteristic
57
+ (ROC) curve given an estimator and some data.
58
+ RocCurveDisplay.from_predictions : Plot Receiver Operating Characteristic
59
+ (ROC) curve given the true and predicted values.
60
+ roc_auc_score : Compute the area under the ROC curve.
61
+
62
+ Examples
63
+ --------
64
+ >>> import matplotlib.pyplot as plt
65
+ >>> import numpy as np
66
+ >>> from sklearn import metrics
67
+ >>> y = np.array([0, 0, 1, 1])
68
+ >>> pred = np.array([0.1, 0.4, 0.35, 0.8])
69
+ >>> fpr, tpr, thresholds = metrics.roc_curve(y, pred)
70
+ >>> roc_auc = metrics.auc(fpr, tpr)
71
+ >>> display = metrics.RocCurveDisplay(fpr=fpr, tpr=tpr, roc_auc=roc_auc,
72
+ ... estimator_name='example estimator')
73
+ >>> display.plot()
74
+ <...>
75
+ >>> plt.show()
76
+ """
77
+
78
+ def __init__(self, *, fpr, tpr, roc_auc=None, estimator_name=None, pos_label=None):
79
+ self.estimator_name = estimator_name
80
+ self.fpr = fpr
81
+ self.tpr = tpr
82
+ self.roc_auc = roc_auc
83
+ self.pos_label = pos_label
84
+
85
+ def plot(self, ax=None, *, name=None, **kwargs):
86
+ """Plot visualization.
87
+
88
+ Extra keyword arguments will be passed to matplotlib's ``plot``.
89
+
90
+ Parameters
91
+ ----------
92
+ ax : matplotlib axes, default=None
93
+ Axes object to plot on. If `None`, a new figure and axes is
94
+ created.
95
+
96
+ name : str, default=None
97
+ Name of ROC Curve for labeling. If `None`, use `estimator_name` if
98
+ not `None`, otherwise no labeling is shown.
99
+
100
+ **kwargs : dict
101
+ Keyword arguments to be passed to matplotlib's `plot`.
102
+
103
+ Returns
104
+ -------
105
+ display : :class:`~sklearn.metrics.plot.RocCurveDisplay`
106
+ Object that stores computed values.
107
+ """
108
+ check_matplotlib_support("RocCurveDisplay.plot")
109
+
110
+ name = self.estimator_name if name is None else name
111
+
112
+ line_kwargs = {}
113
+ if self.roc_auc is not None and name is not None:
114
+ line_kwargs["label"] = f"{name} (AUC = {self.roc_auc:0.2f})"
115
+ elif self.roc_auc is not None:
116
+ line_kwargs["label"] = f"AUC = {self.roc_auc:0.2f}"
117
+ elif name is not None:
118
+ line_kwargs["label"] = name
119
+
120
+ line_kwargs.update(**kwargs)
121
+
122
+ import matplotlib.pyplot as plt
123
+
124
+ if ax is None:
125
+ fig, ax = plt.subplots()
126
+
127
+ (self.line_,) = ax.plot(self.fpr, self.tpr, **line_kwargs)
128
+ info_pos_label = (
129
+ f" (Positive label: {self.pos_label})" if self.pos_label is not None else ""
130
+ )
131
+
132
+ xlabel = "False Positive Rate" + info_pos_label
133
+ ylabel = "True Positive Rate" + info_pos_label
134
+ ax.set(xlabel=xlabel, ylabel=ylabel)
135
+
136
+ if "label" in line_kwargs:
137
+ ax.legend(loc="lower right")
138
+
139
+ self.ax_ = ax
140
+ self.figure_ = ax.figure
141
+ return self
142
+
143
+ @classmethod
144
+ def from_estimator(
145
+ cls,
146
+ estimator,
147
+ X,
148
+ y,
149
+ *,
150
+ sample_weight=None,
151
+ drop_intermediate=True,
152
+ response_method="auto",
153
+ pos_label=None,
154
+ name=None,
155
+ ax=None,
156
+ **kwargs,
157
+ ):
158
+ """Create a ROC Curve display from an estimator.
159
+
160
+ Parameters
161
+ ----------
162
+ estimator : estimator instance
163
+ Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline`
164
+ in which the last estimator is a classifier.
165
+
166
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
167
+ Input values.
168
+
169
+ y : array-like of shape (n_samples,)
170
+ Target values.
171
+
172
+ sample_weight : array-like of shape (n_samples,), default=None
173
+ Sample weights.
174
+
175
+ drop_intermediate : bool, default=True
176
+ Whether to drop some suboptimal thresholds which would not appear
177
+ on a plotted ROC curve. This is useful in order to create lighter
178
+ ROC curves.
179
+
180
+ response_method : {'predict_proba', 'decision_function', 'auto'} \
181
+ default='auto'
182
+ Specifies whether to use :term:`predict_proba` or
183
+ :term:`decision_function` as the target response. If set to 'auto',
184
+ :term:`predict_proba` is tried first and if it does not exist
185
+ :term:`decision_function` is tried next.
186
+
187
+ pos_label : str or int, default=None
188
+ The class considered as the positive class when computing the roc auc
189
+ metrics. By default, `estimators.classes_[1]` is considered
190
+ as the positive class.
191
+
192
+ name : str, default=None
193
+ Name of ROC Curve for labeling. If `None`, use the name of the
194
+ estimator.
195
+
196
+ ax : matplotlib axes, default=None
197
+ Axes object to plot on. If `None`, a new figure and axes is created.
198
+
199
+ **kwargs : dict
200
+ Keyword arguments to be passed to matplotlib's `plot`.
201
+
202
+ Returns
203
+ -------
204
+ display : :class:`~sklearn.metrics.plot.RocCurveDisplay`
205
+ The ROC Curve display.
206
+
207
+ See Also
208
+ --------
209
+ roc_curve : Compute Receiver operating characteristic (ROC) curve.
210
+ RocCurveDisplay.from_predictions : ROC Curve visualization given the
211
+ probabilities of scores of a classifier.
212
+ roc_auc_score : Compute the area under the ROC curve.
213
+
214
+ Examples
215
+ --------
216
+ >>> import matplotlib.pyplot as plt
217
+ >>> from sklearn.datasets import make_classification
218
+ >>> from sklearn.metrics import RocCurveDisplay
219
+ >>> from sklearn.model_selection import train_test_split
220
+ >>> from sklearn.svm import SVC
221
+ >>> X, y = make_classification(random_state=0)
222
+ >>> X_train, X_test, y_train, y_test = train_test_split(
223
+ ... X, y, random_state=0)
224
+ >>> clf = SVC(random_state=0).fit(X_train, y_train)
225
+ >>> RocCurveDisplay.from_estimator(
226
+ ... clf, X_test, y_test)
227
+ <...>
228
+ >>> plt.show()
229
+ """
230
+ check_matplotlib_support(f"{cls.__name__}.from_estimator")
231
+
232
+ name = estimator.__class__.__name__ if name is None else name
233
+
234
+ y_pred, pos_label = _get_response(
235
+ X,
236
+ estimator,
237
+ response_method=response_method,
238
+ pos_label=pos_label,
239
+ )
240
+
241
+ return cls.from_predictions(
242
+ y_true=y,
243
+ y_pred=y_pred,
244
+ sample_weight=sample_weight,
245
+ drop_intermediate=drop_intermediate,
246
+ name=name,
247
+ ax=ax,
248
+ pos_label=pos_label,
249
+ **kwargs,
250
+ )
251
+
252
+ @classmethod
253
+ def from_predictions(
254
+ cls,
255
+ y_true,
256
+ y_pred,
257
+ *,
258
+ sample_weight=None,
259
+ drop_intermediate=True,
260
+ pos_label=None,
261
+ name=None,
262
+ ax=None,
263
+ **kwargs,
264
+ ):
265
+ """Plot ROC curve given the true and predicted values.
266
+
267
+ Read more in the :ref:`User Guide <visualizations>`.
268
+
269
+ .. versionadded:: 1.0
270
+
271
+ Parameters
272
+ ----------
273
+ y_true : array-like of shape (n_samples,)
274
+ True labels.
275
+
276
+ y_pred : array-like of shape (n_samples,)
277
+ Target scores, can either be probability estimates of the positive
278
+ class, confidence values, or non-thresholded measure of decisions
279
+ (as returned by “decision_function” on some classifiers).
280
+
281
+ sample_weight : array-like of shape (n_samples,), default=None
282
+ Sample weights.
283
+
284
+ drop_intermediate : bool, default=True
285
+ Whether to drop some suboptimal thresholds which would not appear
286
+ on a plotted ROC curve. This is useful in order to create lighter
287
+ ROC curves.
288
+
289
+ pos_label : str or int, default=None
290
+ The label of the positive class. When `pos_label=None`, if `y_true`
291
+ is in {-1, 1} or {0, 1}, `pos_label` is set to 1, otherwise an
292
+ error will be raised.
293
+
294
+ name : str, default=None
295
+ Name of ROC curve for labeling. If `None`, name will be set to
296
+ `"Classifier"`.
297
+
298
+ ax : matplotlib axes, default=None
299
+ Axes object to plot on. If `None`, a new figure and axes is
300
+ created.
301
+
302
+ **kwargs : dict
303
+ Additional keywords arguments passed to matplotlib `plot` function.
304
+
305
+ Returns
306
+ -------
307
+ display : :class:`~sklearn.metrics.RocCurveDisplay`
308
+ Object that stores computed values.
309
+
310
+ See Also
311
+ --------
312
+ roc_curve : Compute Receiver operating characteristic (ROC) curve.
313
+ RocCurveDisplay.from_estimator : ROC Curve visualization given an
314
+ estimator and some data.
315
+ roc_auc_score : Compute the area under the ROC curve.
316
+
317
+ Examples
318
+ --------
319
+ >>> import matplotlib.pyplot as plt
320
+ >>> from sklearn.datasets import make_classification
321
+ >>> from sklearn.metrics import RocCurveDisplay
322
+ >>> from sklearn.model_selection import train_test_split
323
+ >>> from sklearn.svm import SVC
324
+ >>> X, y = make_classification(random_state=0)
325
+ >>> X_train, X_test, y_train, y_test = train_test_split(
326
+ ... X, y, random_state=0)
327
+ >>> clf = SVC(random_state=0).fit(X_train, y_train)
328
+ >>> y_pred = clf.decision_function(X_test)
329
+ >>> RocCurveDisplay.from_predictions(
330
+ ... y_test, y_pred)
331
+ <...>
332
+ >>> plt.show()
333
+ """
334
+ check_matplotlib_support(f"{cls.__name__}.from_predictions")
335
+
336
+ fpr, tpr, _ = roc_curve(
337
+ y_true,
338
+ y_pred,
339
+ pos_label=pos_label,
340
+ sample_weight=sample_weight,
341
+ drop_intermediate=drop_intermediate,
342
+ )
343
+ roc_auc = auc(fpr, tpr)
344
+
345
+ name = "Classifier" if name is None else name
346
+ pos_label = _check_pos_label_consistency(pos_label, y_true)
347
+
348
+ viz = RocCurveDisplay(
349
+ fpr=fpr, tpr=tpr, roc_auc=roc_auc, estimator_name=name, pos_label=pos_label
350
+ )
351
+
352
+ return viz.plot(ax=ax, name=name, **kwargs)
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__init__.py ADDED
File without changes
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_common_curve_display.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from sklearn.base import ClassifierMixin, clone
4
+ from sklearn.compose import make_column_transformer
5
+ from sklearn.datasets import load_iris
6
+ from sklearn.exceptions import NotFittedError
7
+ from sklearn.linear_model import LogisticRegression
8
+ from sklearn.pipeline import make_pipeline
9
+ from sklearn.preprocessing import StandardScaler
10
+ from sklearn.tree import DecisionTreeClassifier
11
+
12
+ from sklearn.metrics import (
13
+ DetCurveDisplay,
14
+ PrecisionRecallDisplay,
15
+ RocCurveDisplay,
16
+ )
17
+
18
+
19
+ @pytest.fixture(scope="module")
20
+ def data():
21
+ return load_iris(return_X_y=True)
22
+
23
+
24
+ @pytest.fixture(scope="module")
25
+ def data_binary(data):
26
+ X, y = data
27
+ return X[y < 2], y[y < 2]
28
+
29
+
30
+ @pytest.mark.parametrize(
31
+ "Display", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay]
32
+ )
33
+ def test_display_curve_error_non_binary(pyplot, data, Display):
34
+ """Check that a proper error is raised when only binary classification is
35
+ supported."""
36
+ X, y = data
37
+ clf = DecisionTreeClassifier().fit(X, y)
38
+
39
+ msg = (
40
+ "Expected 'estimator' to be a binary classifier, but got DecisionTreeClassifier"
41
+ )
42
+ with pytest.raises(ValueError, match=msg):
43
+ Display.from_estimator(clf, X, y)
44
+
45
+
46
+ @pytest.mark.parametrize(
47
+ "response_method, msg",
48
+ [
49
+ (
50
+ "predict_proba",
51
+ "response method predict_proba is not defined in MyClassifier",
52
+ ),
53
+ (
54
+ "decision_function",
55
+ "response method decision_function is not defined in MyClassifier",
56
+ ),
57
+ (
58
+ "auto",
59
+ "response method decision_function or predict_proba is not "
60
+ "defined in MyClassifier",
61
+ ),
62
+ (
63
+ "bad_method",
64
+ "response_method must be 'predict_proba', 'decision_function' or 'auto'",
65
+ ),
66
+ ],
67
+ )
68
+ @pytest.mark.parametrize(
69
+ "Display", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay]
70
+ )
71
+ def test_display_curve_error_no_response(
72
+ pyplot,
73
+ data_binary,
74
+ response_method,
75
+ msg,
76
+ Display,
77
+ ):
78
+ """Check that a proper error is raised when the response method requested
79
+ is not defined for the given trained classifier."""
80
+ X, y = data_binary
81
+
82
+ class MyClassifier(ClassifierMixin):
83
+ def fit(self, X, y):
84
+ self.classes_ = [0, 1]
85
+ return self
86
+
87
+ clf = MyClassifier().fit(X, y)
88
+
89
+ with pytest.raises(ValueError, match=msg):
90
+ Display.from_estimator(clf, X, y, response_method=response_method)
91
+
92
+
93
+ @pytest.mark.parametrize(
94
+ "Display", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay]
95
+ )
96
+ @pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"])
97
+ def test_display_curve_estimator_name_multiple_calls(
98
+ pyplot,
99
+ data_binary,
100
+ Display,
101
+ constructor_name,
102
+ ):
103
+ """Check that passing `name` when calling `plot` will overwrite the original name
104
+ in the legend."""
105
+ X, y = data_binary
106
+ clf_name = "my hand-crafted name"
107
+ clf = LogisticRegression().fit(X, y)
108
+ y_pred = clf.predict_proba(X)[:, 1]
109
+
110
+ # safe guard for the binary if/else construction
111
+ assert constructor_name in ("from_estimator", "from_predictions")
112
+
113
+ if constructor_name == "from_estimator":
114
+ disp = Display.from_estimator(clf, X, y, name=clf_name)
115
+ else:
116
+ disp = Display.from_predictions(y, y_pred, name=clf_name)
117
+ assert disp.estimator_name == clf_name
118
+ pyplot.close("all")
119
+ disp.plot()
120
+ assert clf_name in disp.line_.get_label()
121
+ pyplot.close("all")
122
+ clf_name = "another_name"
123
+ disp.plot(name=clf_name)
124
+ assert clf_name in disp.line_.get_label()
125
+
126
+
127
+ @pytest.mark.parametrize(
128
+ "clf",
129
+ [
130
+ LogisticRegression(),
131
+ make_pipeline(StandardScaler(), LogisticRegression()),
132
+ make_pipeline(
133
+ make_column_transformer((StandardScaler(), [0, 1])), LogisticRegression()
134
+ ),
135
+ ],
136
+ )
137
+ @pytest.mark.parametrize(
138
+ "Display", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay]
139
+ )
140
+ def test_display_curve_not_fitted_errors(pyplot, data_binary, clf, Display):
141
+ """Check that a proper error is raised when the classifier is not
142
+ fitted."""
143
+ X, y = data_binary
144
+ # clone since we parametrize the test and the classifier will be fitted
145
+ # when testing the second and subsequent plotting function
146
+ model = clone(clf)
147
+ with pytest.raises(NotFittedError):
148
+ Display.from_estimator(model, X, y)
149
+ model.fit(X, y)
150
+ disp = Display.from_estimator(model, X, y)
151
+ assert model.__class__.__name__ in disp.line_.get_label()
152
+ assert disp.estimator_name == model.__class__.__name__
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy.testing import (
2
+ assert_allclose,
3
+ assert_array_equal,
4
+ )
5
+ import numpy as np
6
+ import pytest
7
+
8
+ from sklearn.datasets import make_classification
9
+ from sklearn.compose import make_column_transformer
10
+ from sklearn.exceptions import NotFittedError
11
+ from sklearn.linear_model import LogisticRegression
12
+ from sklearn.pipeline import make_pipeline
13
+ from sklearn.preprocessing import StandardScaler
14
+ from sklearn.svm import SVC, SVR
15
+
16
+ from sklearn.metrics import ConfusionMatrixDisplay
17
+ from sklearn.metrics import confusion_matrix
18
+
19
+
20
+ # TODO: Remove when https://github.com/numpy/numpy/issues/14397 is resolved
21
+ pytestmark = pytest.mark.filterwarnings(
22
+ "ignore:In future, it will be an error for 'np.bool_':DeprecationWarning:"
23
+ "matplotlib.*"
24
+ )
25
+
26
+
27
+ def test_confusion_matrix_display_validation(pyplot):
28
+ """Check that we raise the proper error when validating parameters."""
29
+ X, y = make_classification(
30
+ n_samples=100, n_informative=5, n_classes=5, random_state=0
31
+ )
32
+
33
+ with pytest.raises(NotFittedError):
34
+ ConfusionMatrixDisplay.from_estimator(SVC(), X, y)
35
+
36
+ regressor = SVR().fit(X, y)
37
+ y_pred_regressor = regressor.predict(X)
38
+ y_pred_classifier = SVC().fit(X, y).predict(X)
39
+
40
+ err_msg = "ConfusionMatrixDisplay.from_estimator only supports classifiers"
41
+ with pytest.raises(ValueError, match=err_msg):
42
+ ConfusionMatrixDisplay.from_estimator(regressor, X, y)
43
+
44
+ err_msg = "Mix type of y not allowed, got types"
45
+ with pytest.raises(ValueError, match=err_msg):
46
+ # Force `y_true` to be seen as a regression problem
47
+ ConfusionMatrixDisplay.from_predictions(y + 0.5, y_pred_classifier)
48
+ with pytest.raises(ValueError, match=err_msg):
49
+ ConfusionMatrixDisplay.from_predictions(y, y_pred_regressor)
50
+
51
+ err_msg = "Found input variables with inconsistent numbers of samples"
52
+ with pytest.raises(ValueError, match=err_msg):
53
+ ConfusionMatrixDisplay.from_predictions(y, y_pred_classifier[::2])
54
+
55
+
56
+ @pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"])
57
+ def test_confusion_matrix_display_invalid_option(pyplot, constructor_name):
58
+ """Check the error raise if an invalid parameter value is passed."""
59
+ X, y = make_classification(
60
+ n_samples=100, n_informative=5, n_classes=5, random_state=0
61
+ )
62
+ classifier = SVC().fit(X, y)
63
+ y_pred = classifier.predict(X)
64
+
65
+ # safe guard for the binary if/else construction
66
+ assert constructor_name in ("from_estimator", "from_predictions")
67
+ extra_params = {"normalize": "invalid"}
68
+
69
+ err_msg = r"normalize must be one of \{'true', 'pred', 'all', None\}"
70
+ with pytest.raises(ValueError, match=err_msg):
71
+ if constructor_name == "from_estimator":
72
+ ConfusionMatrixDisplay.from_estimator(classifier, X, y, **extra_params)
73
+ else:
74
+ ConfusionMatrixDisplay.from_predictions(y, y_pred, **extra_params)
75
+
76
+
77
+ @pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"])
78
+ @pytest.mark.parametrize("with_labels", [True, False])
79
+ @pytest.mark.parametrize("with_display_labels", [True, False])
80
+ def test_confusion_matrix_display_custom_labels(
81
+ pyplot, constructor_name, with_labels, with_display_labels
82
+ ):
83
+ """Check the resulting plot when labels are given."""
84
+ n_classes = 5
85
+ X, y = make_classification(
86
+ n_samples=100, n_informative=5, n_classes=n_classes, random_state=0
87
+ )
88
+ classifier = SVC().fit(X, y)
89
+ y_pred = classifier.predict(X)
90
+
91
+ # safe guard for the binary if/else construction
92
+ assert constructor_name in ("from_estimator", "from_predictions")
93
+
94
+ ax = pyplot.gca()
95
+ labels = [2, 1, 0, 3, 4] if with_labels else None
96
+ display_labels = ["b", "d", "a", "e", "f"] if with_display_labels else None
97
+
98
+ cm = confusion_matrix(y, y_pred, labels=labels)
99
+ common_kwargs = {
100
+ "ax": ax,
101
+ "display_labels": display_labels,
102
+ "labels": labels,
103
+ }
104
+ if constructor_name == "from_estimator":
105
+ disp = ConfusionMatrixDisplay.from_estimator(classifier, X, y, **common_kwargs)
106
+ else:
107
+ disp = ConfusionMatrixDisplay.from_predictions(y, y_pred, **common_kwargs)
108
+ assert_allclose(disp.confusion_matrix, cm)
109
+
110
+ if with_display_labels:
111
+ expected_display_labels = display_labels
112
+ elif with_labels:
113
+ expected_display_labels = labels
114
+ else:
115
+ expected_display_labels = list(range(n_classes))
116
+
117
+ expected_display_labels_str = [str(name) for name in expected_display_labels]
118
+
119
+ x_ticks = [tick.get_text() for tick in disp.ax_.get_xticklabels()]
120
+ y_ticks = [tick.get_text() for tick in disp.ax_.get_yticklabels()]
121
+
122
+ assert_array_equal(disp.display_labels, expected_display_labels)
123
+ assert_array_equal(x_ticks, expected_display_labels_str)
124
+ assert_array_equal(y_ticks, expected_display_labels_str)
125
+
126
+
127
+ @pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"])
128
+ @pytest.mark.parametrize("normalize", ["true", "pred", "all", None])
129
+ @pytest.mark.parametrize("include_values", [True, False])
130
+ def test_confusion_matrix_display_plotting(
131
+ pyplot,
132
+ constructor_name,
133
+ normalize,
134
+ include_values,
135
+ ):
136
+ """Check the overall plotting rendering."""
137
+ n_classes = 5
138
+ X, y = make_classification(
139
+ n_samples=100, n_informative=5, n_classes=n_classes, random_state=0
140
+ )
141
+ classifier = SVC().fit(X, y)
142
+ y_pred = classifier.predict(X)
143
+
144
+ # safe guard for the binary if/else construction
145
+ assert constructor_name in ("from_estimator", "from_predictions")
146
+
147
+ ax = pyplot.gca()
148
+ cmap = "plasma"
149
+
150
+ cm = confusion_matrix(y, y_pred)
151
+ common_kwargs = {
152
+ "normalize": normalize,
153
+ "cmap": cmap,
154
+ "ax": ax,
155
+ "include_values": include_values,
156
+ }
157
+ if constructor_name == "from_estimator":
158
+ disp = ConfusionMatrixDisplay.from_estimator(classifier, X, y, **common_kwargs)
159
+ else:
160
+ disp = ConfusionMatrixDisplay.from_predictions(y, y_pred, **common_kwargs)
161
+
162
+ assert disp.ax_ == ax
163
+
164
+ if normalize == "true":
165
+ cm = cm / cm.sum(axis=1, keepdims=True)
166
+ elif normalize == "pred":
167
+ cm = cm / cm.sum(axis=0, keepdims=True)
168
+ elif normalize == "all":
169
+ cm = cm / cm.sum()
170
+
171
+ assert_allclose(disp.confusion_matrix, cm)
172
+ import matplotlib as mpl
173
+
174
+ assert isinstance(disp.im_, mpl.image.AxesImage)
175
+ assert disp.im_.get_cmap().name == cmap
176
+ assert isinstance(disp.ax_, pyplot.Axes)
177
+ assert isinstance(disp.figure_, pyplot.Figure)
178
+
179
+ assert disp.ax_.get_ylabel() == "True label"
180
+ assert disp.ax_.get_xlabel() == "Predicted label"
181
+
182
+ x_ticks = [tick.get_text() for tick in disp.ax_.get_xticklabels()]
183
+ y_ticks = [tick.get_text() for tick in disp.ax_.get_yticklabels()]
184
+
185
+ expected_display_labels = list(range(n_classes))
186
+
187
+ expected_display_labels_str = [str(name) for name in expected_display_labels]
188
+
189
+ assert_array_equal(disp.display_labels, expected_display_labels)
190
+ assert_array_equal(x_ticks, expected_display_labels_str)
191
+ assert_array_equal(y_ticks, expected_display_labels_str)
192
+
193
+ image_data = disp.im_.get_array().data
194
+ assert_allclose(image_data, cm)
195
+
196
+ if include_values:
197
+ assert disp.text_.shape == (n_classes, n_classes)
198
+ fmt = ".2g"
199
+ expected_text = np.array([format(v, fmt) for v in cm.ravel(order="C")])
200
+ text_text = np.array([t.get_text() for t in disp.text_.ravel(order="C")])
201
+ assert_array_equal(expected_text, text_text)
202
+ else:
203
+ assert disp.text_ is None
204
+
205
+
206
+ @pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"])
207
+ def test_confusion_matrix_display(pyplot, constructor_name):
208
+ """Check the behaviour of the default constructor without using the class
209
+ methods."""
210
+ n_classes = 5
211
+ X, y = make_classification(
212
+ n_samples=100, n_informative=5, n_classes=n_classes, random_state=0
213
+ )
214
+ classifier = SVC().fit(X, y)
215
+ y_pred = classifier.predict(X)
216
+
217
+ # safe guard for the binary if/else construction
218
+ assert constructor_name in ("from_estimator", "from_predictions")
219
+
220
+ cm = confusion_matrix(y, y_pred)
221
+ common_kwargs = {
222
+ "normalize": None,
223
+ "include_values": True,
224
+ "cmap": "viridis",
225
+ "xticks_rotation": 45.0,
226
+ }
227
+ if constructor_name == "from_estimator":
228
+ disp = ConfusionMatrixDisplay.from_estimator(classifier, X, y, **common_kwargs)
229
+ else:
230
+ disp = ConfusionMatrixDisplay.from_predictions(y, y_pred, **common_kwargs)
231
+
232
+ assert_allclose(disp.confusion_matrix, cm)
233
+ assert disp.text_.shape == (n_classes, n_classes)
234
+
235
+ rotations = [tick.get_rotation() for tick in disp.ax_.get_xticklabels()]
236
+ assert_allclose(rotations, 45.0)
237
+
238
+ image_data = disp.im_.get_array().data
239
+ assert_allclose(image_data, cm)
240
+
241
+ disp.plot(cmap="plasma")
242
+ assert disp.im_.get_cmap().name == "plasma"
243
+
244
+ disp.plot(include_values=False)
245
+ assert disp.text_ is None
246
+
247
+ disp.plot(xticks_rotation=90.0)
248
+ rotations = [tick.get_rotation() for tick in disp.ax_.get_xticklabels()]
249
+ assert_allclose(rotations, 90.0)
250
+
251
+ disp.plot(values_format="e")
252
+ expected_text = np.array([format(v, "e") for v in cm.ravel(order="C")])
253
+ text_text = np.array([t.get_text() for t in disp.text_.ravel(order="C")])
254
+ assert_array_equal(expected_text, text_text)
255
+
256
+
257
+ def test_confusion_matrix_contrast(pyplot):
258
+ """Check that the text color is appropriate depending on background."""
259
+
260
+ cm = np.eye(2) / 2
261
+ disp = ConfusionMatrixDisplay(cm, display_labels=[0, 1])
262
+
263
+ disp.plot(cmap=pyplot.cm.gray)
264
+ # diagonal text is black
265
+ assert_allclose(disp.text_[0, 0].get_color(), [0.0, 0.0, 0.0, 1.0])
266
+ assert_allclose(disp.text_[1, 1].get_color(), [0.0, 0.0, 0.0, 1.0])
267
+
268
+ # off-diagonal text is white
269
+ assert_allclose(disp.text_[0, 1].get_color(), [1.0, 1.0, 1.0, 1.0])
270
+ assert_allclose(disp.text_[1, 0].get_color(), [1.0, 1.0, 1.0, 1.0])
271
+
272
+ disp.plot(cmap=pyplot.cm.gray_r)
273
+ # diagonal text is white
274
+ assert_allclose(disp.text_[0, 1].get_color(), [0.0, 0.0, 0.0, 1.0])
275
+ assert_allclose(disp.text_[1, 0].get_color(), [0.0, 0.0, 0.0, 1.0])
276
+
277
+ # off-diagonal text is black
278
+ assert_allclose(disp.text_[0, 0].get_color(), [1.0, 1.0, 1.0, 1.0])
279
+ assert_allclose(disp.text_[1, 1].get_color(), [1.0, 1.0, 1.0, 1.0])
280
+
281
+ # Regression test for #15920
282
+ cm = np.array([[19, 34], [32, 58]])
283
+ disp = ConfusionMatrixDisplay(cm, display_labels=[0, 1])
284
+
285
+ disp.plot(cmap=pyplot.cm.Blues)
286
+ min_color = pyplot.cm.Blues(0)
287
+ max_color = pyplot.cm.Blues(255)
288
+ assert_allclose(disp.text_[0, 0].get_color(), max_color)
289
+ assert_allclose(disp.text_[0, 1].get_color(), max_color)
290
+ assert_allclose(disp.text_[1, 0].get_color(), max_color)
291
+ assert_allclose(disp.text_[1, 1].get_color(), min_color)
292
+
293
+
294
+ @pytest.mark.parametrize(
295
+ "clf",
296
+ [
297
+ LogisticRegression(),
298
+ make_pipeline(StandardScaler(), LogisticRegression()),
299
+ make_pipeline(
300
+ make_column_transformer((StandardScaler(), [0, 1])),
301
+ LogisticRegression(),
302
+ ),
303
+ ],
304
+ ids=["clf", "pipeline-clf", "pipeline-column_transformer-clf"],
305
+ )
306
+ def test_confusion_matrix_pipeline(pyplot, clf):
307
+ """Check the behaviour of the plotting with more complex pipeline."""
308
+ n_classes = 5
309
+ X, y = make_classification(
310
+ n_samples=100, n_informative=5, n_classes=n_classes, random_state=0
311
+ )
312
+ with pytest.raises(NotFittedError):
313
+ ConfusionMatrixDisplay.from_estimator(clf, X, y)
314
+ clf.fit(X, y)
315
+ y_pred = clf.predict(X)
316
+
317
+ disp = ConfusionMatrixDisplay.from_estimator(clf, X, y)
318
+ cm = confusion_matrix(y, y_pred)
319
+
320
+ assert_allclose(disp.confusion_matrix, cm)
321
+ assert disp.text_.shape == (n_classes, n_classes)
322
+
323
+
324
+ @pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"])
325
+ def test_confusion_matrix_with_unknown_labels(pyplot, constructor_name):
326
+ """Check that when labels=None, the unique values in `y_pred` and `y_true`
327
+ will be used.
328
+ Non-regression test for:
329
+ https://github.com/scikit-learn/scikit-learn/pull/18405
330
+ """
331
+ n_classes = 5
332
+ X, y = make_classification(
333
+ n_samples=100, n_informative=5, n_classes=n_classes, random_state=0
334
+ )
335
+ classifier = SVC().fit(X, y)
336
+ y_pred = classifier.predict(X)
337
+ # create unseen labels in `y_true` not seen during fitting and not present
338
+ # in 'classifier.classes_'
339
+ y = y + 1
340
+
341
+ # safe guard for the binary if/else construction
342
+ assert constructor_name in ("from_estimator", "from_predictions")
343
+
344
+ common_kwargs = {"labels": None}
345
+ if constructor_name == "from_estimator":
346
+ disp = ConfusionMatrixDisplay.from_estimator(classifier, X, y, **common_kwargs)
347
+ else:
348
+ disp = ConfusionMatrixDisplay.from_predictions(y, y_pred, **common_kwargs)
349
+
350
+ display_labels = [tick.get_text() for tick in disp.ax_.get_xticklabels()]
351
+ expected_labels = [str(i) for i in range(n_classes + 1)]
352
+ assert_array_equal(expected_labels, display_labels)
353
+
354
+
355
+ def test_colormap_max(pyplot):
356
+ """Check that the max color is used for the color of the text."""
357
+
358
+ from matplotlib import cm
359
+
360
+ gray = cm.get_cmap("gray", 1024)
361
+ confusion_matrix = np.array([[1.0, 0.0], [0.0, 1.0]])
362
+
363
+ disp = ConfusionMatrixDisplay(confusion_matrix)
364
+ disp.plot(cmap=gray)
365
+
366
+ color = disp.text_[1, 0].get_color()
367
+ assert_allclose(color, [1.0, 1.0, 1.0, 1.0])
368
+
369
+
370
+ def test_im_kw_adjust_vmin_vmax(pyplot):
371
+ """Check that im_kw passes kwargs to imshow"""
372
+
373
+ confusion_matrix = np.array([[0.48, 0.04], [0.08, 0.4]])
374
+ disp = ConfusionMatrixDisplay(confusion_matrix)
375
+ disp.plot(im_kw=dict(vmin=0.0, vmax=0.8))
376
+
377
+ clim = disp.im_.get_clim()
378
+ assert clim[0] == pytest.approx(0.0)
379
+ assert clim[1] == pytest.approx(0.8)
380
+
381
+
382
+ def test_confusion_matrix_text_kw(pyplot):
383
+ """Check that text_kw is passed to the text call."""
384
+ font_size = 15.0
385
+ X, y = make_classification(random_state=0)
386
+ classifier = SVC().fit(X, y)
387
+
388
+ # from_estimator passes the font size
389
+ disp = ConfusionMatrixDisplay.from_estimator(
390
+ classifier, X, y, text_kw={"fontsize": font_size}
391
+ )
392
+ for text in disp.text_.reshape(-1):
393
+ assert text.get_fontsize() == font_size
394
+
395
+ # plot adjusts plot to new font size
396
+ new_font_size = 20.0
397
+ disp.plot(text_kw={"fontsize": new_font_size})
398
+ for text in disp.text_.reshape(-1):
399
+ assert text.get_fontsize() == new_font_size
400
+
401
+ # from_predictions passes the font size
402
+ y_pred = classifier.predict(X)
403
+ disp = ConfusionMatrixDisplay.from_predictions(
404
+ y, y_pred, text_kw={"fontsize": font_size}
405
+ )
406
+ for text in disp.text_.reshape(-1):
407
+ assert text.get_fontsize() == font_size
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_precision_recall_display.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from sklearn.compose import make_column_transformer
5
+ from sklearn.datasets import load_breast_cancer, make_classification
6
+ from sklearn.exceptions import NotFittedError
7
+ from sklearn.linear_model import LogisticRegression
8
+ from sklearn.metrics import average_precision_score, precision_recall_curve
9
+ from sklearn.model_selection import train_test_split
10
+ from sklearn.pipeline import make_pipeline
11
+ from sklearn.preprocessing import StandardScaler
12
+ from sklearn.svm import SVC, SVR
13
+ from sklearn.utils import shuffle
14
+
15
+ from sklearn.metrics import PrecisionRecallDisplay
16
+
17
+ # TODO: Remove when https://github.com/numpy/numpy/issues/14397 is resolved
18
+ pytestmark = pytest.mark.filterwarnings(
19
+ "ignore:In future, it will be an error for 'np.bool_':DeprecationWarning:"
20
+ "matplotlib.*"
21
+ )
22
+
23
+
24
+ def test_precision_recall_display_validation(pyplot):
25
+ """Check that we raise the proper error when validating parameters."""
26
+ X, y = make_classification(
27
+ n_samples=100, n_informative=5, n_classes=5, random_state=0
28
+ )
29
+
30
+ with pytest.raises(NotFittedError):
31
+ PrecisionRecallDisplay.from_estimator(SVC(), X, y)
32
+
33
+ regressor = SVR().fit(X, y)
34
+ y_pred_regressor = regressor.predict(X)
35
+ classifier = SVC(probability=True).fit(X, y)
36
+ y_pred_classifier = classifier.predict_proba(X)[:, -1]
37
+
38
+ err_msg = "PrecisionRecallDisplay.from_estimator only supports classifiers"
39
+ with pytest.raises(ValueError, match=err_msg):
40
+ PrecisionRecallDisplay.from_estimator(regressor, X, y)
41
+
42
+ err_msg = "Expected 'estimator' to be a binary classifier, but got SVC"
43
+ with pytest.raises(ValueError, match=err_msg):
44
+ PrecisionRecallDisplay.from_estimator(classifier, X, y)
45
+
46
+ err_msg = "{} format is not supported"
47
+ with pytest.raises(ValueError, match=err_msg.format("continuous")):
48
+ # Force `y_true` to be seen as a regression problem
49
+ PrecisionRecallDisplay.from_predictions(y + 0.5, y_pred_classifier, pos_label=1)
50
+ with pytest.raises(ValueError, match=err_msg.format("multiclass")):
51
+ PrecisionRecallDisplay.from_predictions(y, y_pred_regressor, pos_label=1)
52
+
53
+ err_msg = "Found input variables with inconsistent numbers of samples"
54
+ with pytest.raises(ValueError, match=err_msg):
55
+ PrecisionRecallDisplay.from_predictions(y, y_pred_classifier[::2])
56
+
57
+ X, y = make_classification(n_classes=2, n_samples=50, random_state=0)
58
+ y += 10
59
+ classifier.fit(X, y)
60
+ y_pred_classifier = classifier.predict_proba(X)[:, -1]
61
+ err_msg = r"y_true takes value in {10, 11} and pos_label is not specified"
62
+ with pytest.raises(ValueError, match=err_msg):
63
+ PrecisionRecallDisplay.from_predictions(y, y_pred_classifier)
64
+
65
+
66
+ @pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"])
67
+ @pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"])
68
+ def test_precision_recall_display_plotting(pyplot, constructor_name, response_method):
69
+ """Check the overall plotting rendering."""
70
+ X, y = make_classification(n_classes=2, n_samples=50, random_state=0)
71
+ pos_label = 1
72
+
73
+ classifier = LogisticRegression().fit(X, y)
74
+ classifier.fit(X, y)
75
+
76
+ y_pred = getattr(classifier, response_method)(X)
77
+ y_pred = y_pred if y_pred.ndim == 1 else y_pred[:, pos_label]
78
+
79
+ # safe guard for the binary if/else construction
80
+ assert constructor_name in ("from_estimator", "from_predictions")
81
+
82
+ if constructor_name == "from_estimator":
83
+ display = PrecisionRecallDisplay.from_estimator(
84
+ classifier, X, y, response_method=response_method
85
+ )
86
+ else:
87
+ display = PrecisionRecallDisplay.from_predictions(
88
+ y, y_pred, pos_label=pos_label
89
+ )
90
+
91
+ precision, recall, _ = precision_recall_curve(y, y_pred, pos_label=pos_label)
92
+ average_precision = average_precision_score(y, y_pred, pos_label=pos_label)
93
+
94
+ np.testing.assert_allclose(display.precision, precision)
95
+ np.testing.assert_allclose(display.recall, recall)
96
+ assert display.average_precision == pytest.approx(average_precision)
97
+
98
+ import matplotlib as mpl
99
+
100
+ assert isinstance(display.line_, mpl.lines.Line2D)
101
+ assert isinstance(display.ax_, mpl.axes.Axes)
102
+ assert isinstance(display.figure_, mpl.figure.Figure)
103
+
104
+ assert display.ax_.get_xlabel() == "Recall (Positive label: 1)"
105
+ assert display.ax_.get_ylabel() == "Precision (Positive label: 1)"
106
+
107
+ # plotting passing some new parameters
108
+ display.plot(alpha=0.8, name="MySpecialEstimator")
109
+ expected_label = f"MySpecialEstimator (AP = {average_precision:0.2f})"
110
+ assert display.line_.get_label() == expected_label
111
+ assert display.line_.get_alpha() == pytest.approx(0.8)
112
+
113
+
114
+ @pytest.mark.parametrize(
115
+ "constructor_name, default_label",
116
+ [
117
+ ("from_estimator", "LogisticRegression (AP = {:.2f})"),
118
+ ("from_predictions", "Classifier (AP = {:.2f})"),
119
+ ],
120
+ )
121
+ def test_precision_recall_display_name(pyplot, constructor_name, default_label):
122
+ """Check the behaviour of the name parameters"""
123
+ X, y = make_classification(n_classes=2, n_samples=100, random_state=0)
124
+ pos_label = 1
125
+
126
+ classifier = LogisticRegression().fit(X, y)
127
+ classifier.fit(X, y)
128
+
129
+ y_pred = classifier.predict_proba(X)[:, pos_label]
130
+
131
+ # safe guard for the binary if/else construction
132
+ assert constructor_name in ("from_estimator", "from_predictions")
133
+
134
+ if constructor_name == "from_estimator":
135
+ display = PrecisionRecallDisplay.from_estimator(classifier, X, y)
136
+ else:
137
+ display = PrecisionRecallDisplay.from_predictions(
138
+ y, y_pred, pos_label=pos_label
139
+ )
140
+
141
+ average_precision = average_precision_score(y, y_pred, pos_label=pos_label)
142
+
143
+ # check that the default name is used
144
+ assert display.line_.get_label() == default_label.format(average_precision)
145
+
146
+ # check that the name can be set
147
+ display.plot(name="MySpecialEstimator")
148
+ assert (
149
+ display.line_.get_label()
150
+ == f"MySpecialEstimator (AP = {average_precision:.2f})"
151
+ )
152
+
153
+
154
+ @pytest.mark.parametrize(
155
+ "clf",
156
+ [
157
+ make_pipeline(StandardScaler(), LogisticRegression()),
158
+ make_pipeline(
159
+ make_column_transformer((StandardScaler(), [0, 1])), LogisticRegression()
160
+ ),
161
+ ],
162
+ )
163
+ def test_precision_recall_display_pipeline(pyplot, clf):
164
+ X, y = make_classification(n_classes=2, n_samples=50, random_state=0)
165
+ with pytest.raises(NotFittedError):
166
+ PrecisionRecallDisplay.from_estimator(clf, X, y)
167
+ clf.fit(X, y)
168
+ display = PrecisionRecallDisplay.from_estimator(clf, X, y)
169
+ assert display.estimator_name == clf.__class__.__name__
170
+
171
+
172
+ def test_precision_recall_display_string_labels(pyplot):
173
+ # regression test #15738
174
+ cancer = load_breast_cancer()
175
+ X, y = cancer.data, cancer.target_names[cancer.target]
176
+
177
+ lr = make_pipeline(StandardScaler(), LogisticRegression())
178
+ lr.fit(X, y)
179
+ for klass in cancer.target_names:
180
+ assert klass in lr.classes_
181
+ display = PrecisionRecallDisplay.from_estimator(lr, X, y)
182
+
183
+ y_pred = lr.predict_proba(X)[:, 1]
184
+ avg_prec = average_precision_score(y, y_pred, pos_label=lr.classes_[1])
185
+
186
+ assert display.average_precision == pytest.approx(avg_prec)
187
+ assert display.estimator_name == lr.__class__.__name__
188
+
189
+ err_msg = r"y_true takes value in {'benign', 'malignant'}"
190
+ with pytest.raises(ValueError, match=err_msg):
191
+ PrecisionRecallDisplay.from_predictions(y, y_pred)
192
+
193
+ display = PrecisionRecallDisplay.from_predictions(
194
+ y, y_pred, pos_label=lr.classes_[1]
195
+ )
196
+ assert display.average_precision == pytest.approx(avg_prec)
197
+
198
+
199
+ @pytest.mark.parametrize(
200
+ "average_precision, estimator_name, expected_label",
201
+ [
202
+ (0.9, None, "AP = 0.90"),
203
+ (None, "my_est", "my_est"),
204
+ (0.8, "my_est2", "my_est2 (AP = 0.80)"),
205
+ ],
206
+ )
207
+ def test_default_labels(pyplot, average_precision, estimator_name, expected_label):
208
+ """Check the default labels used in the display."""
209
+ precision = np.array([1, 0.5, 0])
210
+ recall = np.array([0, 0.5, 1])
211
+ display = PrecisionRecallDisplay(
212
+ precision,
213
+ recall,
214
+ average_precision=average_precision,
215
+ estimator_name=estimator_name,
216
+ )
217
+ display.plot()
218
+ assert display.line_.get_label() == expected_label
219
+
220
+
221
+ @pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"])
222
+ @pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"])
223
+ def test_plot_precision_recall_pos_label(pyplot, constructor_name, response_method):
224
+ # check that we can provide the positive label and display the proper
225
+ # statistics
226
+ X, y = load_breast_cancer(return_X_y=True)
227
+ # create an highly imbalanced version of the breast cancer dataset
228
+ idx_positive = np.flatnonzero(y == 1)
229
+ idx_negative = np.flatnonzero(y == 0)
230
+ idx_selected = np.hstack([idx_negative, idx_positive[:25]])
231
+ X, y = X[idx_selected], y[idx_selected]
232
+ X, y = shuffle(X, y, random_state=42)
233
+ # only use 2 features to make the problem even harder
234
+ X = X[:, :2]
235
+ y = np.array(["cancer" if c == 1 else "not cancer" for c in y], dtype=object)
236
+ X_train, X_test, y_train, y_test = train_test_split(
237
+ X,
238
+ y,
239
+ stratify=y,
240
+ random_state=0,
241
+ )
242
+
243
+ classifier = LogisticRegression()
244
+ classifier.fit(X_train, y_train)
245
+
246
+ # sanity check to be sure the positive class is classes_[0] and that we
247
+ # are betrayed by the class imbalance
248
+ assert classifier.classes_.tolist() == ["cancer", "not cancer"]
249
+
250
+ y_pred = getattr(classifier, response_method)(X_test)
251
+ # we select the corresponding probability columns or reverse the decision
252
+ # function otherwise
253
+ y_pred_cancer = -1 * y_pred if y_pred.ndim == 1 else y_pred[:, 0]
254
+ y_pred_not_cancer = y_pred if y_pred.ndim == 1 else y_pred[:, 1]
255
+
256
+ if constructor_name == "from_estimator":
257
+ display = PrecisionRecallDisplay.from_estimator(
258
+ classifier,
259
+ X_test,
260
+ y_test,
261
+ pos_label="cancer",
262
+ response_method=response_method,
263
+ )
264
+ else:
265
+ display = PrecisionRecallDisplay.from_predictions(
266
+ y_test,
267
+ y_pred_cancer,
268
+ pos_label="cancer",
269
+ )
270
+ # we should obtain the statistics of the "cancer" class
271
+ avg_prec_limit = 0.65
272
+ assert display.average_precision < avg_prec_limit
273
+ assert -np.trapz(display.precision, display.recall) < avg_prec_limit
274
+
275
+ # otherwise we should obtain the statistics of the "not cancer" class
276
+ if constructor_name == "from_estimator":
277
+ display = PrecisionRecallDisplay.from_estimator(
278
+ classifier,
279
+ X_test,
280
+ y_test,
281
+ response_method=response_method,
282
+ pos_label="not cancer",
283
+ )
284
+ else:
285
+ display = PrecisionRecallDisplay.from_predictions(
286
+ y_test,
287
+ y_pred_not_cancer,
288
+ pos_label="not cancer",
289
+ )
290
+ avg_prec_limit = 0.95
291
+ assert display.average_precision > avg_prec_limit
292
+ assert -np.trapz(display.precision, display.recall) > avg_prec_limit
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_predict_error_display.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ from numpy.testing import assert_allclose
4
+
5
+ from sklearn.datasets import load_diabetes
6
+ from sklearn.exceptions import NotFittedError
7
+ from sklearn.linear_model import Ridge
8
+
9
+ from sklearn.metrics import PredictionErrorDisplay
10
+
11
+ X, y = load_diabetes(return_X_y=True)
12
+
13
+
14
+ @pytest.fixture
15
+ def regressor_fitted():
16
+ return Ridge().fit(X, y)
17
+
18
+
19
+ @pytest.mark.parametrize(
20
+ "regressor, params, err_type, err_msg",
21
+ [
22
+ (
23
+ Ridge().fit(X, y),
24
+ {"subsample": -1},
25
+ ValueError,
26
+ "When an integer, subsample=-1 should be",
27
+ ),
28
+ (
29
+ Ridge().fit(X, y),
30
+ {"subsample": 20.0},
31
+ ValueError,
32
+ "When a floating-point, subsample=20.0 should be",
33
+ ),
34
+ (
35
+ Ridge().fit(X, y),
36
+ {"subsample": -20.0},
37
+ ValueError,
38
+ "When a floating-point, subsample=-20.0 should be",
39
+ ),
40
+ (
41
+ Ridge().fit(X, y),
42
+ {"kind": "xxx"},
43
+ ValueError,
44
+ "`kind` must be one of",
45
+ ),
46
+ ],
47
+ )
48
+ @pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"])
49
+ def test_prediction_error_display_raise_error(
50
+ pyplot, class_method, regressor, params, err_type, err_msg
51
+ ):
52
+ """Check that we raise the proper error when making the parameters
53
+ # validation."""
54
+ with pytest.raises(err_type, match=err_msg):
55
+ if class_method == "from_estimator":
56
+ PredictionErrorDisplay.from_estimator(regressor, X, y, **params)
57
+ else:
58
+ y_pred = regressor.predict(X)
59
+ PredictionErrorDisplay.from_predictions(y_true=y, y_pred=y_pred, **params)
60
+
61
+
62
+ def test_from_estimator_not_fitted(pyplot):
63
+ """Check that we raise a `NotFittedError` when the passed regressor is not
64
+ fit."""
65
+ regressor = Ridge()
66
+ with pytest.raises(NotFittedError, match="is not fitted yet."):
67
+ PredictionErrorDisplay.from_estimator(regressor, X, y)
68
+
69
+
70
+ @pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"])
71
+ @pytest.mark.parametrize("kind", ["actual_vs_predicted", "residual_vs_predicted"])
72
+ def test_prediction_error_display(pyplot, regressor_fitted, class_method, kind):
73
+ """Check the default behaviour of the display."""
74
+ if class_method == "from_estimator":
75
+ display = PredictionErrorDisplay.from_estimator(
76
+ regressor_fitted, X, y, kind=kind
77
+ )
78
+ else:
79
+ y_pred = regressor_fitted.predict(X)
80
+ display = PredictionErrorDisplay.from_predictions(
81
+ y_true=y, y_pred=y_pred, kind=kind
82
+ )
83
+
84
+ if kind == "actual_vs_predicted":
85
+ assert_allclose(display.line_.get_xdata(), display.line_.get_ydata())
86
+ assert display.ax_.get_xlabel() == "Predicted values"
87
+ assert display.ax_.get_ylabel() == "Actual values"
88
+ assert display.line_ is not None
89
+ else:
90
+ assert display.ax_.get_xlabel() == "Predicted values"
91
+ assert display.ax_.get_ylabel() == "Residuals (actual - predicted)"
92
+ assert display.line_ is not None
93
+
94
+ assert display.ax_.get_legend() is None
95
+
96
+
97
+ @pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"])
98
+ @pytest.mark.parametrize(
99
+ "subsample, expected_size",
100
+ [(5, 5), (0.1, int(X.shape[0] * 0.1)), (None, X.shape[0])],
101
+ )
102
+ def test_plot_prediction_error_subsample(
103
+ pyplot, regressor_fitted, class_method, subsample, expected_size
104
+ ):
105
+ """Check the behaviour of `subsample`."""
106
+ if class_method == "from_estimator":
107
+ display = PredictionErrorDisplay.from_estimator(
108
+ regressor_fitted, X, y, subsample=subsample
109
+ )
110
+ else:
111
+ y_pred = regressor_fitted.predict(X)
112
+ display = PredictionErrorDisplay.from_predictions(
113
+ y_true=y, y_pred=y_pred, subsample=subsample
114
+ )
115
+ assert len(display.scatter_.get_offsets()) == expected_size
116
+
117
+
118
+ @pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"])
119
+ def test_plot_prediction_error_ax(pyplot, regressor_fitted, class_method):
120
+ """Check that we can pass an axis to the display."""
121
+ _, ax = pyplot.subplots()
122
+ if class_method == "from_estimator":
123
+ display = PredictionErrorDisplay.from_estimator(regressor_fitted, X, y, ax=ax)
124
+ else:
125
+ y_pred = regressor_fitted.predict(X)
126
+ display = PredictionErrorDisplay.from_predictions(
127
+ y_true=y, y_pred=y_pred, ax=ax
128
+ )
129
+ assert display.ax_ is ax
130
+
131
+
132
+ @pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"])
133
+ def test_prediction_error_custom_artist(pyplot, regressor_fitted, class_method):
134
+ """Check that we can tune the style of the lines."""
135
+ extra_params = {
136
+ "kind": "actual_vs_predicted",
137
+ "scatter_kwargs": {"color": "red"},
138
+ "line_kwargs": {"color": "black"},
139
+ }
140
+ if class_method == "from_estimator":
141
+ display = PredictionErrorDisplay.from_estimator(
142
+ regressor_fitted, X, y, **extra_params
143
+ )
144
+ else:
145
+ y_pred = regressor_fitted.predict(X)
146
+ display = PredictionErrorDisplay.from_predictions(
147
+ y_true=y, y_pred=y_pred, **extra_params
148
+ )
149
+
150
+ assert display.line_.get_color() == "black"
151
+ assert_allclose(display.scatter_.get_edgecolor(), [[1.0, 0.0, 0.0, 0.8]])
152
+
153
+ # create a display with the default values
154
+ if class_method == "from_estimator":
155
+ display = PredictionErrorDisplay.from_estimator(regressor_fitted, X, y)
156
+ else:
157
+ y_pred = regressor_fitted.predict(X)
158
+ display = PredictionErrorDisplay.from_predictions(y_true=y, y_pred=y_pred)
159
+ pyplot.close("all")
160
+
161
+ display.plot(**extra_params)
162
+ assert display.line_.get_color() == "black"
163
+ assert_allclose(display.scatter_.get_edgecolor(), [[1.0, 0.0, 0.0, 0.8]])
videollama2/lib/python3.10/site-packages/sklearn/metrics/_regression.py ADDED
@@ -0,0 +1,1497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Metrics to assess performance on regression task.
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
+ # Karan Desai <karandesai281196@gmail.com>
18
+ # Noel Dawe <noel@dawe.me>
19
+ # Manoj Kumar <manojkumarsivaraj334@gmail.com>
20
+ # Michael Eickenberg <michael.eickenberg@gmail.com>
21
+ # Konstantin Shmelkov <konstantin.shmelkov@polytechnique.edu>
22
+ # Christian Lorentzen <lorentzen.ch@gmail.com>
23
+ # Ashutosh Hathidara <ashutoshhathidara98@gmail.com>
24
+ # Uttam kumar <bajiraouttamsinha@gmail.com>
25
+ # Sylvain Marie <sylvain.marie@se.com>
26
+ # Ohad Michel <ohadmich@gmail.com>
27
+ # License: BSD 3 clause
28
+
29
+ import numbers
30
+ import warnings
31
+
32
+ import numpy as np
33
+ from scipy.special import xlogy
34
+
35
+ from ..exceptions import UndefinedMetricWarning
36
+ from ..utils.validation import (
37
+ check_array,
38
+ check_consistent_length,
39
+ check_scalar,
40
+ _num_samples,
41
+ column_or_1d,
42
+ _check_sample_weight,
43
+ )
44
+ from ..utils.stats import _weighted_percentile
45
+
46
+
47
+ __ALL__ = [
48
+ "max_error",
49
+ "mean_absolute_error",
50
+ "mean_squared_error",
51
+ "mean_squared_log_error",
52
+ "median_absolute_error",
53
+ "mean_absolute_percentage_error",
54
+ "mean_pinball_loss",
55
+ "r2_score",
56
+ "explained_variance_score",
57
+ "mean_tweedie_deviance",
58
+ "mean_poisson_deviance",
59
+ "mean_gamma_deviance",
60
+ "d2_tweedie_score",
61
+ "d2_pinball_score",
62
+ "d2_absolute_error_score",
63
+ ]
64
+
65
+
66
+ def _check_reg_targets(y_true, y_pred, multioutput, dtype="numeric"):
67
+ """Check that y_true and y_pred belong to the same regression task.
68
+
69
+ Parameters
70
+ ----------
71
+ y_true : array-like
72
+
73
+ y_pred : array-like
74
+
75
+ multioutput : array-like or string in ['raw_values', uniform_average',
76
+ 'variance_weighted'] or None
77
+ None is accepted due to backward compatibility of r2_score().
78
+
79
+ dtype : str or list, default="numeric"
80
+ the dtype argument passed to check_array.
81
+
82
+ Returns
83
+ -------
84
+ type_true : one of {'continuous', continuous-multioutput'}
85
+ The type of the true target data, as output by
86
+ 'utils.multiclass.type_of_target'.
87
+
88
+ y_true : array-like of shape (n_samples, n_outputs)
89
+ Ground truth (correct) target values.
90
+
91
+ y_pred : array-like of shape (n_samples, n_outputs)
92
+ Estimated target values.
93
+
94
+ multioutput : array-like of shape (n_outputs) or string in ['raw_values',
95
+ uniform_average', 'variance_weighted'] or None
96
+ Custom output weights if ``multioutput`` is array-like or
97
+ just the corresponding argument if ``multioutput`` is a
98
+ correct keyword.
99
+ """
100
+ check_consistent_length(y_true, y_pred)
101
+ y_true = check_array(y_true, ensure_2d=False, dtype=dtype)
102
+ y_pred = check_array(y_pred, ensure_2d=False, dtype=dtype)
103
+
104
+ if y_true.ndim == 1:
105
+ y_true = y_true.reshape((-1, 1))
106
+
107
+ if y_pred.ndim == 1:
108
+ y_pred = y_pred.reshape((-1, 1))
109
+
110
+ if y_true.shape[1] != y_pred.shape[1]:
111
+ raise ValueError(
112
+ "y_true and y_pred have different number of output ({0}!={1})".format(
113
+ y_true.shape[1], y_pred.shape[1]
114
+ )
115
+ )
116
+
117
+ n_outputs = y_true.shape[1]
118
+ allowed_multioutput_str = ("raw_values", "uniform_average", "variance_weighted")
119
+ if isinstance(multioutput, str):
120
+ if multioutput not in allowed_multioutput_str:
121
+ raise ValueError(
122
+ "Allowed 'multioutput' string values are {}. "
123
+ "You provided multioutput={!r}".format(
124
+ allowed_multioutput_str, multioutput
125
+ )
126
+ )
127
+ elif multioutput is not None:
128
+ multioutput = check_array(multioutput, ensure_2d=False)
129
+ if n_outputs == 1:
130
+ raise ValueError("Custom weights are useful only in multi-output cases.")
131
+ elif n_outputs != len(multioutput):
132
+ raise ValueError(
133
+ "There must be equally many custom weights (%d) as outputs (%d)."
134
+ % (len(multioutput), n_outputs)
135
+ )
136
+ y_type = "continuous" if n_outputs == 1 else "continuous-multioutput"
137
+
138
+ return y_type, y_true, y_pred, multioutput
139
+
140
+
141
+ def mean_absolute_error(
142
+ y_true, y_pred, *, sample_weight=None, multioutput="uniform_average"
143
+ ):
144
+ """Mean absolute error regression loss.
145
+
146
+ Read more in the :ref:`User Guide <mean_absolute_error>`.
147
+
148
+ Parameters
149
+ ----------
150
+ y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)
151
+ Ground truth (correct) target values.
152
+
153
+ y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)
154
+ Estimated target values.
155
+
156
+ sample_weight : array-like of shape (n_samples,), default=None
157
+ Sample weights.
158
+
159
+ multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
160
+ (n_outputs,), default='uniform_average'
161
+ Defines aggregating of multiple output values.
162
+ Array-like value defines weights used to average errors.
163
+
164
+ 'raw_values' :
165
+ Returns a full set of errors in case of multioutput input.
166
+
167
+ 'uniform_average' :
168
+ Errors of all outputs are averaged with uniform weight.
169
+
170
+ Returns
171
+ -------
172
+ loss : float or ndarray of floats
173
+ If multioutput is 'raw_values', then mean absolute error is returned
174
+ for each output separately.
175
+ If multioutput is 'uniform_average' or an ndarray of weights, then the
176
+ weighted average of all output errors is returned.
177
+
178
+ MAE output is non-negative floating point. The best value is 0.0.
179
+
180
+ Examples
181
+ --------
182
+ >>> from sklearn.metrics import mean_absolute_error
183
+ >>> y_true = [3, -0.5, 2, 7]
184
+ >>> y_pred = [2.5, 0.0, 2, 8]
185
+ >>> mean_absolute_error(y_true, y_pred)
186
+ 0.5
187
+ >>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
188
+ >>> y_pred = [[0, 2], [-1, 2], [8, -5]]
189
+ >>> mean_absolute_error(y_true, y_pred)
190
+ 0.75
191
+ >>> mean_absolute_error(y_true, y_pred, multioutput='raw_values')
192
+ array([0.5, 1. ])
193
+ >>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7])
194
+ 0.85...
195
+ """
196
+ y_type, y_true, y_pred, multioutput = _check_reg_targets(
197
+ y_true, y_pred, multioutput
198
+ )
199
+ check_consistent_length(y_true, y_pred, sample_weight)
200
+ output_errors = np.average(np.abs(y_pred - y_true), weights=sample_weight, axis=0)
201
+ if isinstance(multioutput, str):
202
+ if multioutput == "raw_values":
203
+ return output_errors
204
+ elif multioutput == "uniform_average":
205
+ # pass None as weights to np.average: uniform mean
206
+ multioutput = None
207
+
208
+ return np.average(output_errors, weights=multioutput)
209
+
210
+
211
+ def mean_pinball_loss(
212
+ y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput="uniform_average"
213
+ ):
214
+ """Pinball loss for quantile regression.
215
+
216
+ Read more in the :ref:`User Guide <pinball_loss>`.
217
+
218
+ Parameters
219
+ ----------
220
+ y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)
221
+ Ground truth (correct) target values.
222
+
223
+ y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)
224
+ Estimated target values.
225
+
226
+ sample_weight : array-like of shape (n_samples,), default=None
227
+ Sample weights.
228
+
229
+ alpha : float, slope of the pinball loss, default=0.5,
230
+ This loss is equivalent to :ref:`mean_absolute_error` when `alpha=0.5`,
231
+ `alpha=0.95` is minimized by estimators of the 95th percentile.
232
+
233
+ multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
234
+ (n_outputs,), default='uniform_average'
235
+ Defines aggregating of multiple output values.
236
+ Array-like value defines weights used to average errors.
237
+
238
+ 'raw_values' :
239
+ Returns a full set of errors in case of multioutput input.
240
+
241
+ 'uniform_average' :
242
+ Errors of all outputs are averaged with uniform weight.
243
+
244
+ Returns
245
+ -------
246
+ loss : float or ndarray of floats
247
+ If multioutput is 'raw_values', then mean absolute error is returned
248
+ for each output separately.
249
+ If multioutput is 'uniform_average' or an ndarray of weights, then the
250
+ weighted average of all output errors is returned.
251
+
252
+ The pinball loss output is a non-negative floating point. The best
253
+ value is 0.0.
254
+
255
+ Examples
256
+ --------
257
+ >>> from sklearn.metrics import mean_pinball_loss
258
+ >>> y_true = [1, 2, 3]
259
+ >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1)
260
+ 0.03...
261
+ >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1)
262
+ 0.3...
263
+ >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9)
264
+ 0.3...
265
+ >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9)
266
+ 0.03...
267
+ >>> mean_pinball_loss(y_true, y_true, alpha=0.1)
268
+ 0.0
269
+ >>> mean_pinball_loss(y_true, y_true, alpha=0.9)
270
+ 0.0
271
+ """
272
+ y_type, y_true, y_pred, multioutput = _check_reg_targets(
273
+ y_true, y_pred, multioutput
274
+ )
275
+ check_consistent_length(y_true, y_pred, sample_weight)
276
+ diff = y_true - y_pred
277
+ sign = (diff >= 0).astype(diff.dtype)
278
+ loss = alpha * sign * diff - (1 - alpha) * (1 - sign) * diff
279
+ output_errors = np.average(loss, weights=sample_weight, axis=0)
280
+ if isinstance(multioutput, str):
281
+ if multioutput == "raw_values":
282
+ return output_errors
283
+ elif multioutput == "uniform_average":
284
+ # pass None as weights to np.average: uniform mean
285
+ multioutput = None
286
+ else:
287
+ raise ValueError(
288
+ "multioutput is expected to be 'raw_values' "
289
+ "or 'uniform_average' but we got %r"
290
+ " instead." % multioutput
291
+ )
292
+
293
+ return np.average(output_errors, weights=multioutput)
294
+
295
+
296
+ def mean_absolute_percentage_error(
297
+ y_true, y_pred, *, sample_weight=None, multioutput="uniform_average"
298
+ ):
299
+ """Mean absolute percentage error (MAPE) regression loss.
300
+
301
+ Note here that the output is not a percentage in the range [0, 100]
302
+ and a value of 100 does not mean 100% but 1e2. Furthermore, the output
303
+ can be arbitrarily high when `y_true` is small (which is specific to the
304
+ metric) or when `abs(y_true - y_pred)` is large (which is common for most
305
+ regression metrics). Read more in the
306
+ :ref:`User Guide <mean_absolute_percentage_error>`.
307
+
308
+ .. versionadded:: 0.24
309
+
310
+ Parameters
311
+ ----------
312
+ y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)
313
+ Ground truth (correct) target values.
314
+
315
+ y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)
316
+ Estimated target values.
317
+
318
+ sample_weight : array-like of shape (n_samples,), default=None
319
+ Sample weights.
320
+
321
+ multioutput : {'raw_values', 'uniform_average'} or array-like
322
+ Defines aggregating of multiple output values.
323
+ Array-like value defines weights used to average errors.
324
+ If input is list then the shape must be (n_outputs,).
325
+
326
+ 'raw_values' :
327
+ Returns a full set of errors in case of multioutput input.
328
+
329
+ 'uniform_average' :
330
+ Errors of all outputs are averaged with uniform weight.
331
+
332
+ Returns
333
+ -------
334
+ loss : float or ndarray of floats
335
+ If multioutput is 'raw_values', then mean absolute percentage error
336
+ is returned for each output separately.
337
+ If multioutput is 'uniform_average' or an ndarray of weights, then the
338
+ weighted average of all output errors is returned.
339
+
340
+ MAPE output is non-negative floating point. The best value is 0.0.
341
+ But note that bad predictions can lead to arbitrarily large
342
+ MAPE values, especially if some `y_true` values are very close to zero.
343
+ Note that we return a large value instead of `inf` when `y_true` is zero.
344
+
345
+ Examples
346
+ --------
347
+ >>> from sklearn.metrics import mean_absolute_percentage_error
348
+ >>> y_true = [3, -0.5, 2, 7]
349
+ >>> y_pred = [2.5, 0.0, 2, 8]
350
+ >>> mean_absolute_percentage_error(y_true, y_pred)
351
+ 0.3273...
352
+ >>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
353
+ >>> y_pred = [[0, 2], [-1, 2], [8, -5]]
354
+ >>> mean_absolute_percentage_error(y_true, y_pred)
355
+ 0.5515...
356
+ >>> mean_absolute_percentage_error(y_true, y_pred, multioutput=[0.3, 0.7])
357
+ 0.6198...
358
+ >>> # the value when some element of the y_true is zero is arbitrarily high because
359
+ >>> # of the division by epsilon
360
+ >>> y_true = [1., 0., 2.4, 7.]
361
+ >>> y_pred = [1.2, 0.1, 2.4, 8.]
362
+ >>> mean_absolute_percentage_error(y_true, y_pred)
363
+ 112589990684262.48
364
+ """
365
+ y_type, y_true, y_pred, multioutput = _check_reg_targets(
366
+ y_true, y_pred, multioutput
367
+ )
368
+ check_consistent_length(y_true, y_pred, sample_weight)
369
+ epsilon = np.finfo(np.float64).eps
370
+ mape = np.abs(y_pred - y_true) / np.maximum(np.abs(y_true), epsilon)
371
+ output_errors = np.average(mape, weights=sample_weight, axis=0)
372
+ if isinstance(multioutput, str):
373
+ if multioutput == "raw_values":
374
+ return output_errors
375
+ elif multioutput == "uniform_average":
376
+ # pass None as weights to np.average: uniform mean
377
+ multioutput = None
378
+
379
+ return np.average(output_errors, weights=multioutput)
380
+
381
+
382
+ def mean_squared_error(
383
+ y_true, y_pred, *, sample_weight=None, multioutput="uniform_average", squared=True
384
+ ):
385
+ """Mean squared error regression loss.
386
+
387
+ Read more in the :ref:`User Guide <mean_squared_error>`.
388
+
389
+ Parameters
390
+ ----------
391
+ y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)
392
+ Ground truth (correct) target values.
393
+
394
+ y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)
395
+ Estimated target values.
396
+
397
+ sample_weight : array-like of shape (n_samples,), default=None
398
+ Sample weights.
399
+
400
+ multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
401
+ (n_outputs,), default='uniform_average'
402
+ Defines aggregating of multiple output values.
403
+ Array-like value defines weights used to average errors.
404
+
405
+ 'raw_values' :
406
+ Returns a full set of errors in case of multioutput input.
407
+
408
+ 'uniform_average' :
409
+ Errors of all outputs are averaged with uniform weight.
410
+
411
+ squared : bool, default=True
412
+ If True returns MSE value, if False returns RMSE value.
413
+
414
+ Returns
415
+ -------
416
+ loss : float or ndarray of floats
417
+ A non-negative floating point value (the best value is 0.0), or an
418
+ array of floating point values, one for each individual target.
419
+
420
+ Examples
421
+ --------
422
+ >>> from sklearn.metrics import mean_squared_error
423
+ >>> y_true = [3, -0.5, 2, 7]
424
+ >>> y_pred = [2.5, 0.0, 2, 8]
425
+ >>> mean_squared_error(y_true, y_pred)
426
+ 0.375
427
+ >>> y_true = [3, -0.5, 2, 7]
428
+ >>> y_pred = [2.5, 0.0, 2, 8]
429
+ >>> mean_squared_error(y_true, y_pred, squared=False)
430
+ 0.612...
431
+ >>> y_true = [[0.5, 1],[-1, 1],[7, -6]]
432
+ >>> y_pred = [[0, 2],[-1, 2],[8, -5]]
433
+ >>> mean_squared_error(y_true, y_pred)
434
+ 0.708...
435
+ >>> mean_squared_error(y_true, y_pred, squared=False)
436
+ 0.822...
437
+ >>> mean_squared_error(y_true, y_pred, multioutput='raw_values')
438
+ array([0.41666667, 1. ])
439
+ >>> mean_squared_error(y_true, y_pred, multioutput=[0.3, 0.7])
440
+ 0.825...
441
+ """
442
+ y_type, y_true, y_pred, multioutput = _check_reg_targets(
443
+ y_true, y_pred, multioutput
444
+ )
445
+ check_consistent_length(y_true, y_pred, sample_weight)
446
+ output_errors = np.average((y_true - y_pred) ** 2, axis=0, weights=sample_weight)
447
+
448
+ if not squared:
449
+ output_errors = np.sqrt(output_errors)
450
+
451
+ if isinstance(multioutput, str):
452
+ if multioutput == "raw_values":
453
+ return output_errors
454
+ elif multioutput == "uniform_average":
455
+ # pass None as weights to np.average: uniform mean
456
+ multioutput = None
457
+
458
+ return np.average(output_errors, weights=multioutput)
459
+
460
+
461
+ def mean_squared_log_error(
462
+ y_true, y_pred, *, sample_weight=None, multioutput="uniform_average", squared=True
463
+ ):
464
+ """Mean squared logarithmic error regression loss.
465
+
466
+ Read more in the :ref:`User Guide <mean_squared_log_error>`.
467
+
468
+ Parameters
469
+ ----------
470
+ y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)
471
+ Ground truth (correct) target values.
472
+
473
+ y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)
474
+ Estimated target values.
475
+
476
+ sample_weight : array-like of shape (n_samples,), default=None
477
+ Sample weights.
478
+
479
+ multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
480
+ (n_outputs,), default='uniform_average'
481
+
482
+ Defines aggregating of multiple output values.
483
+ Array-like value defines weights used to average errors.
484
+
485
+ 'raw_values' :
486
+ Returns a full set of errors when the input is of multioutput
487
+ format.
488
+
489
+ 'uniform_average' :
490
+ Errors of all outputs are averaged with uniform weight.
491
+ squared : bool, default=True
492
+ If True returns MSLE (mean squared log error) value.
493
+ If False returns RMSLE (root mean squared log error) value.
494
+
495
+ Returns
496
+ -------
497
+ loss : float or ndarray of floats
498
+ A non-negative floating point value (the best value is 0.0), or an
499
+ array of floating point values, one for each individual target.
500
+
501
+ Examples
502
+ --------
503
+ >>> from sklearn.metrics import mean_squared_log_error
504
+ >>> y_true = [3, 5, 2.5, 7]
505
+ >>> y_pred = [2.5, 5, 4, 8]
506
+ >>> mean_squared_log_error(y_true, y_pred)
507
+ 0.039...
508
+ >>> mean_squared_log_error(y_true, y_pred, squared=False)
509
+ 0.199...
510
+ >>> y_true = [[0.5, 1], [1, 2], [7, 6]]
511
+ >>> y_pred = [[0.5, 2], [1, 2.5], [8, 8]]
512
+ >>> mean_squared_log_error(y_true, y_pred)
513
+ 0.044...
514
+ >>> mean_squared_log_error(y_true, y_pred, multioutput='raw_values')
515
+ array([0.00462428, 0.08377444])
516
+ >>> mean_squared_log_error(y_true, y_pred, multioutput=[0.3, 0.7])
517
+ 0.060...
518
+ """
519
+ y_type, y_true, y_pred, multioutput = _check_reg_targets(
520
+ y_true, y_pred, multioutput
521
+ )
522
+ check_consistent_length(y_true, y_pred, sample_weight)
523
+
524
+ if (y_true < 0).any() or (y_pred < 0).any():
525
+ raise ValueError(
526
+ "Mean Squared Logarithmic Error cannot be used when "
527
+ "targets contain negative values."
528
+ )
529
+
530
+ return mean_squared_error(
531
+ np.log1p(y_true),
532
+ np.log1p(y_pred),
533
+ sample_weight=sample_weight,
534
+ multioutput=multioutput,
535
+ squared=squared,
536
+ )
537
+
538
+
539
+ def median_absolute_error(
540
+ y_true, y_pred, *, multioutput="uniform_average", sample_weight=None
541
+ ):
542
+ """Median absolute error regression loss.
543
+
544
+ Median absolute error output is non-negative floating point. The best value
545
+ is 0.0. Read more in the :ref:`User Guide <median_absolute_error>`.
546
+
547
+ Parameters
548
+ ----------
549
+ y_true : array-like of shape = (n_samples) or (n_samples, n_outputs)
550
+ Ground truth (correct) target values.
551
+
552
+ y_pred : array-like of shape = (n_samples) or (n_samples, n_outputs)
553
+ Estimated target values.
554
+
555
+ multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
556
+ (n_outputs,), default='uniform_average'
557
+ Defines aggregating of multiple output values. Array-like value defines
558
+ weights used to average errors.
559
+
560
+ 'raw_values' :
561
+ Returns a full set of errors in case of multioutput input.
562
+
563
+ 'uniform_average' :
564
+ Errors of all outputs are averaged with uniform weight.
565
+
566
+ sample_weight : array-like of shape (n_samples,), default=None
567
+ Sample weights.
568
+
569
+ .. versionadded:: 0.24
570
+
571
+ Returns
572
+ -------
573
+ loss : float or ndarray of floats
574
+ If multioutput is 'raw_values', then mean absolute error is returned
575
+ for each output separately.
576
+ If multioutput is 'uniform_average' or an ndarray of weights, then the
577
+ weighted average of all output errors is returned.
578
+
579
+ Examples
580
+ --------
581
+ >>> from sklearn.metrics import median_absolute_error
582
+ >>> y_true = [3, -0.5, 2, 7]
583
+ >>> y_pred = [2.5, 0.0, 2, 8]
584
+ >>> median_absolute_error(y_true, y_pred)
585
+ 0.5
586
+ >>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
587
+ >>> y_pred = [[0, 2], [-1, 2], [8, -5]]
588
+ >>> median_absolute_error(y_true, y_pred)
589
+ 0.75
590
+ >>> median_absolute_error(y_true, y_pred, multioutput='raw_values')
591
+ array([0.5, 1. ])
592
+ >>> median_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7])
593
+ 0.85
594
+ """
595
+ y_type, y_true, y_pred, multioutput = _check_reg_targets(
596
+ y_true, y_pred, multioutput
597
+ )
598
+ if sample_weight is None:
599
+ output_errors = np.median(np.abs(y_pred - y_true), axis=0)
600
+ else:
601
+ sample_weight = _check_sample_weight(sample_weight, y_pred)
602
+ output_errors = _weighted_percentile(
603
+ np.abs(y_pred - y_true), sample_weight=sample_weight
604
+ )
605
+ if isinstance(multioutput, str):
606
+ if multioutput == "raw_values":
607
+ return output_errors
608
+ elif multioutput == "uniform_average":
609
+ # pass None as weights to np.average: uniform mean
610
+ multioutput = None
611
+
612
+ return np.average(output_errors, weights=multioutput)
613
+
614
+
615
+ def _assemble_r2_explained_variance(
616
+ numerator, denominator, n_outputs, multioutput, force_finite
617
+ ):
618
+ """Common part used by explained variance score and :math:`R^2` score."""
619
+
620
+ nonzero_denominator = denominator != 0
621
+
622
+ if not force_finite:
623
+ # Standard formula, that may lead to NaN or -Inf
624
+ output_scores = 1 - (numerator / denominator)
625
+ else:
626
+ nonzero_numerator = numerator != 0
627
+ # Default = Zero Numerator = perfect predictions. Set to 1.0
628
+ # (note: even if denominator is zero, thus avoiding NaN scores)
629
+ output_scores = np.ones([n_outputs])
630
+ # Non-zero Numerator and Non-zero Denominator: use the formula
631
+ valid_score = nonzero_denominator & nonzero_numerator
632
+ output_scores[valid_score] = 1 - (
633
+ numerator[valid_score] / denominator[valid_score]
634
+ )
635
+ # Non-zero Numerator and Zero Denominator:
636
+ # arbitrary set to 0.0 to avoid -inf scores
637
+ output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0
638
+
639
+ if isinstance(multioutput, str):
640
+ if multioutput == "raw_values":
641
+ # return scores individually
642
+ return output_scores
643
+ elif multioutput == "uniform_average":
644
+ # Passing None as weights to np.average results is uniform mean
645
+ avg_weights = None
646
+ elif multioutput == "variance_weighted":
647
+ avg_weights = denominator
648
+ if not np.any(nonzero_denominator):
649
+ # All weights are zero, np.average would raise a ZeroDiv error.
650
+ # This only happens when all y are constant (or 1-element long)
651
+ # Since weights are all equal, fall back to uniform weights.
652
+ avg_weights = None
653
+ else:
654
+ avg_weights = multioutput
655
+
656
+ return np.average(output_scores, weights=avg_weights)
657
+
658
+
659
+ def explained_variance_score(
660
+ y_true,
661
+ y_pred,
662
+ *,
663
+ sample_weight=None,
664
+ multioutput="uniform_average",
665
+ force_finite=True,
666
+ ):
667
+ """Explained variance regression score function.
668
+
669
+ Best possible score is 1.0, lower values are worse.
670
+
671
+ In the particular case when ``y_true`` is constant, the explained variance
672
+ score is not finite: it is either ``NaN`` (perfect predictions) or
673
+ ``-Inf`` (imperfect predictions). To prevent such non-finite numbers to
674
+ pollute higher-level experiments such as a grid search cross-validation,
675
+ by default these cases are replaced with 1.0 (perfect predictions) or 0.0
676
+ (imperfect predictions) respectively. If ``force_finite``
677
+ is set to ``False``, this score falls back on the original :math:`R^2`
678
+ definition.
679
+
680
+ .. note::
681
+ The Explained Variance score is similar to the
682
+ :func:`R^2 score <r2_score>`, with the notable difference that it
683
+ does not account for systematic offsets in the prediction. Most often
684
+ the :func:`R^2 score <r2_score>` should be preferred.
685
+
686
+ Read more in the :ref:`User Guide <explained_variance_score>`.
687
+
688
+ Parameters
689
+ ----------
690
+ y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)
691
+ Ground truth (correct) target values.
692
+
693
+ y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)
694
+ Estimated target values.
695
+
696
+ sample_weight : array-like of shape (n_samples,), default=None
697
+ Sample weights.
698
+
699
+ multioutput : {'raw_values', 'uniform_average', 'variance_weighted'} or \
700
+ array-like of shape (n_outputs,), default='uniform_average'
701
+ Defines aggregating of multiple output scores.
702
+ Array-like value defines weights used to average scores.
703
+
704
+ 'raw_values' :
705
+ Returns a full set of scores in case of multioutput input.
706
+
707
+ 'uniform_average' :
708
+ Scores of all outputs are averaged with uniform weight.
709
+
710
+ 'variance_weighted' :
711
+ Scores of all outputs are averaged, weighted by the variances
712
+ of each individual output.
713
+
714
+ force_finite : bool, default=True
715
+ Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant
716
+ data should be replaced with real numbers (``1.0`` if prediction is
717
+ perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting
718
+ for hyperparameters' search procedures (e.g. grid search
719
+ cross-validation).
720
+
721
+ .. versionadded:: 1.1
722
+
723
+ Returns
724
+ -------
725
+ score : float or ndarray of floats
726
+ The explained variance or ndarray if 'multioutput' is 'raw_values'.
727
+
728
+ See Also
729
+ --------
730
+ r2_score :
731
+ Similar metric, but accounting for systematic offsets in
732
+ prediction.
733
+
734
+ Notes
735
+ -----
736
+ This is not a symmetric function.
737
+
738
+ Examples
739
+ --------
740
+ >>> from sklearn.metrics import explained_variance_score
741
+ >>> y_true = [3, -0.5, 2, 7]
742
+ >>> y_pred = [2.5, 0.0, 2, 8]
743
+ >>> explained_variance_score(y_true, y_pred)
744
+ 0.957...
745
+ >>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
746
+ >>> y_pred = [[0, 2], [-1, 2], [8, -5]]
747
+ >>> explained_variance_score(y_true, y_pred, multioutput='uniform_average')
748
+ 0.983...
749
+ >>> y_true = [-2, -2, -2]
750
+ >>> y_pred = [-2, -2, -2]
751
+ >>> explained_variance_score(y_true, y_pred)
752
+ 1.0
753
+ >>> explained_variance_score(y_true, y_pred, force_finite=False)
754
+ nan
755
+ >>> y_true = [-2, -2, -2]
756
+ >>> y_pred = [-2, -2, -2 + 1e-8]
757
+ >>> explained_variance_score(y_true, y_pred)
758
+ 0.0
759
+ >>> explained_variance_score(y_true, y_pred, force_finite=False)
760
+ -inf
761
+ """
762
+ y_type, y_true, y_pred, multioutput = _check_reg_targets(
763
+ y_true, y_pred, multioutput
764
+ )
765
+ check_consistent_length(y_true, y_pred, sample_weight)
766
+
767
+ y_diff_avg = np.average(y_true - y_pred, weights=sample_weight, axis=0)
768
+ numerator = np.average(
769
+ (y_true - y_pred - y_diff_avg) ** 2, weights=sample_weight, axis=0
770
+ )
771
+
772
+ y_true_avg = np.average(y_true, weights=sample_weight, axis=0)
773
+ denominator = np.average((y_true - y_true_avg) ** 2, weights=sample_weight, axis=0)
774
+
775
+ return _assemble_r2_explained_variance(
776
+ numerator=numerator,
777
+ denominator=denominator,
778
+ n_outputs=y_true.shape[1],
779
+ multioutput=multioutput,
780
+ force_finite=force_finite,
781
+ )
782
+
783
+
784
+ def r2_score(
785
+ y_true,
786
+ y_pred,
787
+ *,
788
+ sample_weight=None,
789
+ multioutput="uniform_average",
790
+ force_finite=True,
791
+ ):
792
+ """:math:`R^2` (coefficient of determination) regression score function.
793
+
794
+ Best possible score is 1.0 and it can be negative (because the
795
+ model can be arbitrarily worse). In the general case when the true y is
796
+ non-constant, a constant model that always predicts the average y
797
+ disregarding the input features would get a :math:`R^2` score of 0.0.
798
+
799
+ In the particular case when ``y_true`` is constant, the :math:`R^2` score
800
+ is not finite: it is either ``NaN`` (perfect predictions) or ``-Inf``
801
+ (imperfect predictions). To prevent such non-finite numbers to pollute
802
+ higher-level experiments such as a grid search cross-validation, by default
803
+ these cases are replaced with 1.0 (perfect predictions) or 0.0 (imperfect
804
+ predictions) respectively. You can set ``force_finite`` to ``False`` to
805
+ prevent this fix from happening.
806
+
807
+ Note: when the prediction residuals have zero mean, the :math:`R^2` score
808
+ is identical to the
809
+ :func:`Explained Variance score <explained_variance_score>`.
810
+
811
+ Read more in the :ref:`User Guide <r2_score>`.
812
+
813
+ Parameters
814
+ ----------
815
+ y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)
816
+ Ground truth (correct) target values.
817
+
818
+ y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)
819
+ Estimated target values.
820
+
821
+ sample_weight : array-like of shape (n_samples,), default=None
822
+ Sample weights.
823
+
824
+ multioutput : {'raw_values', 'uniform_average', 'variance_weighted'}, \
825
+ array-like of shape (n_outputs,) or None, default='uniform_average'
826
+
827
+ Defines aggregating of multiple output scores.
828
+ Array-like value defines weights used to average scores.
829
+ Default is "uniform_average".
830
+
831
+ 'raw_values' :
832
+ Returns a full set of scores in case of multioutput input.
833
+
834
+ 'uniform_average' :
835
+ Scores of all outputs are averaged with uniform weight.
836
+
837
+ 'variance_weighted' :
838
+ Scores of all outputs are averaged, weighted by the variances
839
+ of each individual output.
840
+
841
+ .. versionchanged:: 0.19
842
+ Default value of multioutput is 'uniform_average'.
843
+
844
+ force_finite : bool, default=True
845
+ Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant
846
+ data should be replaced with real numbers (``1.0`` if prediction is
847
+ perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting
848
+ for hyperparameters' search procedures (e.g. grid search
849
+ cross-validation).
850
+
851
+ .. versionadded:: 1.1
852
+
853
+ Returns
854
+ -------
855
+ z : float or ndarray of floats
856
+ The :math:`R^2` score or ndarray of scores if 'multioutput' is
857
+ 'raw_values'.
858
+
859
+ Notes
860
+ -----
861
+ This is not a symmetric function.
862
+
863
+ Unlike most other scores, :math:`R^2` score may be negative (it need not
864
+ actually be the square of a quantity R).
865
+
866
+ This metric is not well-defined for single samples and will return a NaN
867
+ value if n_samples is less than two.
868
+
869
+ References
870
+ ----------
871
+ .. [1] `Wikipedia entry on the Coefficient of determination
872
+ <https://en.wikipedia.org/wiki/Coefficient_of_determination>`_
873
+
874
+ Examples
875
+ --------
876
+ >>> from sklearn.metrics import r2_score
877
+ >>> y_true = [3, -0.5, 2, 7]
878
+ >>> y_pred = [2.5, 0.0, 2, 8]
879
+ >>> r2_score(y_true, y_pred)
880
+ 0.948...
881
+ >>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
882
+ >>> y_pred = [[0, 2], [-1, 2], [8, -5]]
883
+ >>> r2_score(y_true, y_pred,
884
+ ... multioutput='variance_weighted')
885
+ 0.938...
886
+ >>> y_true = [1, 2, 3]
887
+ >>> y_pred = [1, 2, 3]
888
+ >>> r2_score(y_true, y_pred)
889
+ 1.0
890
+ >>> y_true = [1, 2, 3]
891
+ >>> y_pred = [2, 2, 2]
892
+ >>> r2_score(y_true, y_pred)
893
+ 0.0
894
+ >>> y_true = [1, 2, 3]
895
+ >>> y_pred = [3, 2, 1]
896
+ >>> r2_score(y_true, y_pred)
897
+ -3.0
898
+ >>> y_true = [-2, -2, -2]
899
+ >>> y_pred = [-2, -2, -2]
900
+ >>> r2_score(y_true, y_pred)
901
+ 1.0
902
+ >>> r2_score(y_true, y_pred, force_finite=False)
903
+ nan
904
+ >>> y_true = [-2, -2, -2]
905
+ >>> y_pred = [-2, -2, -2 + 1e-8]
906
+ >>> r2_score(y_true, y_pred)
907
+ 0.0
908
+ >>> r2_score(y_true, y_pred, force_finite=False)
909
+ -inf
910
+ """
911
+ y_type, y_true, y_pred, multioutput = _check_reg_targets(
912
+ y_true, y_pred, multioutput
913
+ )
914
+ check_consistent_length(y_true, y_pred, sample_weight)
915
+
916
+ if _num_samples(y_pred) < 2:
917
+ msg = "R^2 score is not well-defined with less than two samples."
918
+ warnings.warn(msg, UndefinedMetricWarning)
919
+ return float("nan")
920
+
921
+ if sample_weight is not None:
922
+ sample_weight = column_or_1d(sample_weight)
923
+ weight = sample_weight[:, np.newaxis]
924
+ else:
925
+ weight = 1.0
926
+
927
+ numerator = (weight * (y_true - y_pred) ** 2).sum(axis=0, dtype=np.float64)
928
+ denominator = (
929
+ weight * (y_true - np.average(y_true, axis=0, weights=sample_weight)) ** 2
930
+ ).sum(axis=0, dtype=np.float64)
931
+
932
+ return _assemble_r2_explained_variance(
933
+ numerator=numerator,
934
+ denominator=denominator,
935
+ n_outputs=y_true.shape[1],
936
+ multioutput=multioutput,
937
+ force_finite=force_finite,
938
+ )
939
+
940
+
941
+ def max_error(y_true, y_pred):
942
+ """
943
+ The max_error metric calculates the maximum residual error.
944
+
945
+ Read more in the :ref:`User Guide <max_error>`.
946
+
947
+ Parameters
948
+ ----------
949
+ y_true : array-like of shape (n_samples,)
950
+ Ground truth (correct) target values.
951
+
952
+ y_pred : array-like of shape (n_samples,)
953
+ Estimated target values.
954
+
955
+ Returns
956
+ -------
957
+ max_error : float
958
+ A positive floating point value (the best value is 0.0).
959
+
960
+ Examples
961
+ --------
962
+ >>> from sklearn.metrics import max_error
963
+ >>> y_true = [3, 2, 7, 1]
964
+ >>> y_pred = [4, 2, 7, 1]
965
+ >>> max_error(y_true, y_pred)
966
+ 1
967
+ """
968
+ y_type, y_true, y_pred, _ = _check_reg_targets(y_true, y_pred, None)
969
+ if y_type == "continuous-multioutput":
970
+ raise ValueError("Multioutput not supported in max_error")
971
+ return np.max(np.abs(y_true - y_pred))
972
+
973
+
974
+ def _mean_tweedie_deviance(y_true, y_pred, sample_weight, power):
975
+ """Mean Tweedie deviance regression loss."""
976
+ p = power
977
+ if p < 0:
978
+ # 'Extreme stable', y any real number, y_pred > 0
979
+ dev = 2 * (
980
+ np.power(np.maximum(y_true, 0), 2 - p) / ((1 - p) * (2 - p))
981
+ - y_true * np.power(y_pred, 1 - p) / (1 - p)
982
+ + np.power(y_pred, 2 - p) / (2 - p)
983
+ )
984
+ elif p == 0:
985
+ # Normal distribution, y and y_pred any real number
986
+ dev = (y_true - y_pred) ** 2
987
+ elif p == 1:
988
+ # Poisson distribution
989
+ dev = 2 * (xlogy(y_true, y_true / y_pred) - y_true + y_pred)
990
+ elif p == 2:
991
+ # Gamma distribution
992
+ dev = 2 * (np.log(y_pred / y_true) + y_true / y_pred - 1)
993
+ else:
994
+ dev = 2 * (
995
+ np.power(y_true, 2 - p) / ((1 - p) * (2 - p))
996
+ - y_true * np.power(y_pred, 1 - p) / (1 - p)
997
+ + np.power(y_pred, 2 - p) / (2 - p)
998
+ )
999
+
1000
+ return np.average(dev, weights=sample_weight)
1001
+
1002
+
1003
+ def mean_tweedie_deviance(y_true, y_pred, *, sample_weight=None, power=0):
1004
+ """Mean Tweedie deviance regression loss.
1005
+
1006
+ Read more in the :ref:`User Guide <mean_tweedie_deviance>`.
1007
+
1008
+ Parameters
1009
+ ----------
1010
+ y_true : array-like of shape (n_samples,)
1011
+ Ground truth (correct) target values.
1012
+
1013
+ y_pred : array-like of shape (n_samples,)
1014
+ Estimated target values.
1015
+
1016
+ sample_weight : array-like of shape (n_samples,), default=None
1017
+ Sample weights.
1018
+
1019
+ power : float, default=0
1020
+ Tweedie power parameter. Either power <= 0 or power >= 1.
1021
+
1022
+ The higher `p` the less weight is given to extreme
1023
+ deviations between true and predicted targets.
1024
+
1025
+ - power < 0: Extreme stable distribution. Requires: y_pred > 0.
1026
+ - power = 0 : Normal distribution, output corresponds to
1027
+ mean_squared_error. y_true and y_pred can be any real numbers.
1028
+ - power = 1 : Poisson distribution. Requires: y_true >= 0 and
1029
+ y_pred > 0.
1030
+ - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0
1031
+ and y_pred > 0.
1032
+ - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0.
1033
+ - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0
1034
+ and y_pred > 0.
1035
+ - otherwise : Positive stable distribution. Requires: y_true > 0
1036
+ and y_pred > 0.
1037
+
1038
+ Returns
1039
+ -------
1040
+ loss : float
1041
+ A non-negative floating point value (the best value is 0.0).
1042
+
1043
+ Examples
1044
+ --------
1045
+ >>> from sklearn.metrics import mean_tweedie_deviance
1046
+ >>> y_true = [2, 0, 1, 4]
1047
+ >>> y_pred = [0.5, 0.5, 2., 2.]
1048
+ >>> mean_tweedie_deviance(y_true, y_pred, power=1)
1049
+ 1.4260...
1050
+ """
1051
+ y_type, y_true, y_pred, _ = _check_reg_targets(
1052
+ y_true, y_pred, None, dtype=[np.float64, np.float32]
1053
+ )
1054
+ if y_type == "continuous-multioutput":
1055
+ raise ValueError("Multioutput not supported in mean_tweedie_deviance")
1056
+ check_consistent_length(y_true, y_pred, sample_weight)
1057
+
1058
+ if sample_weight is not None:
1059
+ sample_weight = column_or_1d(sample_weight)
1060
+ sample_weight = sample_weight[:, np.newaxis]
1061
+
1062
+ p = check_scalar(
1063
+ power,
1064
+ name="power",
1065
+ target_type=numbers.Real,
1066
+ )
1067
+
1068
+ message = f"Mean Tweedie deviance error with power={p} can only be used on "
1069
+ if p < 0:
1070
+ # 'Extreme stable', y any real number, y_pred > 0
1071
+ if (y_pred <= 0).any():
1072
+ raise ValueError(message + "strictly positive y_pred.")
1073
+ elif p == 0:
1074
+ # Normal, y and y_pred can be any real number
1075
+ pass
1076
+ elif 0 < p < 1:
1077
+ raise ValueError("Tweedie deviance is only defined for power<=0 and power>=1.")
1078
+ elif 1 <= p < 2:
1079
+ # Poisson and compound Poisson distribution, y >= 0, y_pred > 0
1080
+ if (y_true < 0).any() or (y_pred <= 0).any():
1081
+ raise ValueError(message + "non-negative y and strictly positive y_pred.")
1082
+ elif p >= 2:
1083
+ # Gamma and Extreme stable distribution, y and y_pred > 0
1084
+ if (y_true <= 0).any() or (y_pred <= 0).any():
1085
+ raise ValueError(message + "strictly positive y and y_pred.")
1086
+ else: # pragma: nocover
1087
+ # Unreachable statement
1088
+ raise ValueError
1089
+
1090
+ return _mean_tweedie_deviance(
1091
+ y_true, y_pred, sample_weight=sample_weight, power=power
1092
+ )
1093
+
1094
+
1095
+ def mean_poisson_deviance(y_true, y_pred, *, sample_weight=None):
1096
+ """Mean Poisson deviance regression loss.
1097
+
1098
+ Poisson deviance is equivalent to the Tweedie deviance with
1099
+ the power parameter `power=1`.
1100
+
1101
+ Read more in the :ref:`User Guide <mean_tweedie_deviance>`.
1102
+
1103
+ Parameters
1104
+ ----------
1105
+ y_true : array-like of shape (n_samples,)
1106
+ Ground truth (correct) target values. Requires y_true >= 0.
1107
+
1108
+ y_pred : array-like of shape (n_samples,)
1109
+ Estimated target values. Requires y_pred > 0.
1110
+
1111
+ sample_weight : array-like of shape (n_samples,), default=None
1112
+ Sample weights.
1113
+
1114
+ Returns
1115
+ -------
1116
+ loss : float
1117
+ A non-negative floating point value (the best value is 0.0).
1118
+
1119
+ Examples
1120
+ --------
1121
+ >>> from sklearn.metrics import mean_poisson_deviance
1122
+ >>> y_true = [2, 0, 1, 4]
1123
+ >>> y_pred = [0.5, 0.5, 2., 2.]
1124
+ >>> mean_poisson_deviance(y_true, y_pred)
1125
+ 1.4260...
1126
+ """
1127
+ return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=1)
1128
+
1129
+
1130
+ def mean_gamma_deviance(y_true, y_pred, *, sample_weight=None):
1131
+ """Mean Gamma deviance regression loss.
1132
+
1133
+ Gamma deviance is equivalent to the Tweedie deviance with
1134
+ the power parameter `power=2`. It is invariant to scaling of
1135
+ the target variable, and measures relative errors.
1136
+
1137
+ Read more in the :ref:`User Guide <mean_tweedie_deviance>`.
1138
+
1139
+ Parameters
1140
+ ----------
1141
+ y_true : array-like of shape (n_samples,)
1142
+ Ground truth (correct) target values. Requires y_true > 0.
1143
+
1144
+ y_pred : array-like of shape (n_samples,)
1145
+ Estimated target values. Requires y_pred > 0.
1146
+
1147
+ sample_weight : array-like of shape (n_samples,), default=None
1148
+ Sample weights.
1149
+
1150
+ Returns
1151
+ -------
1152
+ loss : float
1153
+ A non-negative floating point value (the best value is 0.0).
1154
+
1155
+ Examples
1156
+ --------
1157
+ >>> from sklearn.metrics import mean_gamma_deviance
1158
+ >>> y_true = [2, 0.5, 1, 4]
1159
+ >>> y_pred = [0.5, 0.5, 2., 2.]
1160
+ >>> mean_gamma_deviance(y_true, y_pred)
1161
+ 1.0568...
1162
+ """
1163
+ return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=2)
1164
+
1165
+
1166
+ def d2_tweedie_score(y_true, y_pred, *, sample_weight=None, power=0):
1167
+ """D^2 regression score function, fraction of Tweedie deviance explained.
1168
+
1169
+ Best possible score is 1.0 and it can be negative (because the model can be
1170
+ arbitrarily worse). A model that always uses the empirical mean of `y_true` as
1171
+ constant prediction, disregarding the input features, gets a D^2 score of 0.0.
1172
+
1173
+ Read more in the :ref:`User Guide <d2_score>`.
1174
+
1175
+ .. versionadded:: 1.0
1176
+
1177
+ Parameters
1178
+ ----------
1179
+ y_true : array-like of shape (n_samples,)
1180
+ Ground truth (correct) target values.
1181
+
1182
+ y_pred : array-like of shape (n_samples,)
1183
+ Estimated target values.
1184
+
1185
+ sample_weight : array-like of shape (n_samples,), optional
1186
+ Sample weights.
1187
+
1188
+ power : float, default=0
1189
+ Tweedie power parameter. Either power <= 0 or power >= 1.
1190
+
1191
+ The higher `p` the less weight is given to extreme
1192
+ deviations between true and predicted targets.
1193
+
1194
+ - power < 0: Extreme stable distribution. Requires: y_pred > 0.
1195
+ - power = 0 : Normal distribution, output corresponds to r2_score.
1196
+ y_true and y_pred can be any real numbers.
1197
+ - power = 1 : Poisson distribution. Requires: y_true >= 0 and
1198
+ y_pred > 0.
1199
+ - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0
1200
+ and y_pred > 0.
1201
+ - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0.
1202
+ - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0
1203
+ and y_pred > 0.
1204
+ - otherwise : Positive stable distribution. Requires: y_true > 0
1205
+ and y_pred > 0.
1206
+
1207
+ Returns
1208
+ -------
1209
+ z : float or ndarray of floats
1210
+ The D^2 score.
1211
+
1212
+ Notes
1213
+ -----
1214
+ This is not a symmetric function.
1215
+
1216
+ Like R^2, D^2 score may be negative (it need not actually be the square of
1217
+ a quantity D).
1218
+
1219
+ This metric is not well-defined for single samples and will return a NaN
1220
+ value if n_samples is less than two.
1221
+
1222
+ References
1223
+ ----------
1224
+ .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J.
1225
+ Wainwright. "Statistical Learning with Sparsity: The Lasso and
1226
+ Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/
1227
+
1228
+ Examples
1229
+ --------
1230
+ >>> from sklearn.metrics import d2_tweedie_score
1231
+ >>> y_true = [0.5, 1, 2.5, 7]
1232
+ >>> y_pred = [1, 1, 5, 3.5]
1233
+ >>> d2_tweedie_score(y_true, y_pred)
1234
+ 0.285...
1235
+ >>> d2_tweedie_score(y_true, y_pred, power=1)
1236
+ 0.487...
1237
+ >>> d2_tweedie_score(y_true, y_pred, power=2)
1238
+ 0.630...
1239
+ >>> d2_tweedie_score(y_true, y_true, power=2)
1240
+ 1.0
1241
+ """
1242
+ y_type, y_true, y_pred, _ = _check_reg_targets(
1243
+ y_true, y_pred, None, dtype=[np.float64, np.float32]
1244
+ )
1245
+ if y_type == "continuous-multioutput":
1246
+ raise ValueError("Multioutput not supported in d2_tweedie_score")
1247
+
1248
+ if _num_samples(y_pred) < 2:
1249
+ msg = "D^2 score is not well-defined with less than two samples."
1250
+ warnings.warn(msg, UndefinedMetricWarning)
1251
+ return float("nan")
1252
+
1253
+ y_true, y_pred = np.squeeze(y_true), np.squeeze(y_pred)
1254
+ numerator = mean_tweedie_deviance(
1255
+ y_true, y_pred, sample_weight=sample_weight, power=power
1256
+ )
1257
+
1258
+ y_avg = np.average(y_true, weights=sample_weight)
1259
+ denominator = _mean_tweedie_deviance(
1260
+ y_true, y_avg, sample_weight=sample_weight, power=power
1261
+ )
1262
+
1263
+ return 1 - numerator / denominator
1264
+
1265
+
1266
+ def d2_pinball_score(
1267
+ y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput="uniform_average"
1268
+ ):
1269
+ """
1270
+ :math:`D^2` regression score function, fraction of pinball loss explained.
1271
+
1272
+ Best possible score is 1.0 and it can be negative (because the model can be
1273
+ arbitrarily worse). A model that always uses the empirical alpha-quantile of
1274
+ `y_true` as constant prediction, disregarding the input features,
1275
+ gets a :math:`D^2` score of 0.0.
1276
+
1277
+ Read more in the :ref:`User Guide <d2_score>`.
1278
+
1279
+ .. versionadded:: 1.1
1280
+
1281
+ Parameters
1282
+ ----------
1283
+ y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)
1284
+ Ground truth (correct) target values.
1285
+
1286
+ y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)
1287
+ Estimated target values.
1288
+
1289
+ sample_weight : array-like of shape (n_samples,), optional
1290
+ Sample weights.
1291
+
1292
+ alpha : float, default=0.5
1293
+ Slope of the pinball deviance. It determines the quantile level alpha
1294
+ for which the pinball deviance and also D2 are optimal.
1295
+ The default `alpha=0.5` is equivalent to `d2_absolute_error_score`.
1296
+
1297
+ multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
1298
+ (n_outputs,), default='uniform_average'
1299
+ Defines aggregating of multiple output values.
1300
+ Array-like value defines weights used to average scores.
1301
+
1302
+ 'raw_values' :
1303
+ Returns a full set of errors in case of multioutput input.
1304
+
1305
+ 'uniform_average' :
1306
+ Scores of all outputs are averaged with uniform weight.
1307
+
1308
+ Returns
1309
+ -------
1310
+ score : float or ndarray of floats
1311
+ The :math:`D^2` score with a pinball deviance
1312
+ or ndarray of scores if `multioutput='raw_values'`.
1313
+
1314
+ Notes
1315
+ -----
1316
+ Like :math:`R^2`, :math:`D^2` score may be negative
1317
+ (it need not actually be the square of a quantity D).
1318
+
1319
+ This metric is not well-defined for a single point and will return a NaN
1320
+ value if n_samples is less than two.
1321
+
1322
+ References
1323
+ ----------
1324
+ .. [1] Eq. (7) of `Koenker, Roger; Machado, José A. F. (1999).
1325
+ "Goodness of Fit and Related Inference Processes for Quantile Regression"
1326
+ <http://dx.doi.org/10.1080/01621459.1999.10473882>`_
1327
+ .. [2] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J.
1328
+ Wainwright. "Statistical Learning with Sparsity: The Lasso and
1329
+ Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/
1330
+
1331
+ Examples
1332
+ --------
1333
+ >>> from sklearn.metrics import d2_pinball_score
1334
+ >>> y_true = [1, 2, 3]
1335
+ >>> y_pred = [1, 3, 3]
1336
+ >>> d2_pinball_score(y_true, y_pred)
1337
+ 0.5
1338
+ >>> d2_pinball_score(y_true, y_pred, alpha=0.9)
1339
+ 0.772...
1340
+ >>> d2_pinball_score(y_true, y_pred, alpha=0.1)
1341
+ -1.045...
1342
+ >>> d2_pinball_score(y_true, y_true, alpha=0.1)
1343
+ 1.0
1344
+ """
1345
+ y_type, y_true, y_pred, multioutput = _check_reg_targets(
1346
+ y_true, y_pred, multioutput
1347
+ )
1348
+ check_consistent_length(y_true, y_pred, sample_weight)
1349
+
1350
+ if _num_samples(y_pred) < 2:
1351
+ msg = "D^2 score is not well-defined with less than two samples."
1352
+ warnings.warn(msg, UndefinedMetricWarning)
1353
+ return float("nan")
1354
+
1355
+ numerator = mean_pinball_loss(
1356
+ y_true,
1357
+ y_pred,
1358
+ sample_weight=sample_weight,
1359
+ alpha=alpha,
1360
+ multioutput="raw_values",
1361
+ )
1362
+
1363
+ if sample_weight is None:
1364
+ y_quantile = np.tile(
1365
+ np.percentile(y_true, q=alpha * 100, axis=0), (len(y_true), 1)
1366
+ )
1367
+ else:
1368
+ sample_weight = _check_sample_weight(sample_weight, y_true)
1369
+ y_quantile = np.tile(
1370
+ _weighted_percentile(
1371
+ y_true, sample_weight=sample_weight, percentile=alpha * 100
1372
+ ),
1373
+ (len(y_true), 1),
1374
+ )
1375
+
1376
+ denominator = mean_pinball_loss(
1377
+ y_true,
1378
+ y_quantile,
1379
+ sample_weight=sample_weight,
1380
+ alpha=alpha,
1381
+ multioutput="raw_values",
1382
+ )
1383
+
1384
+ nonzero_numerator = numerator != 0
1385
+ nonzero_denominator = denominator != 0
1386
+ valid_score = nonzero_numerator & nonzero_denominator
1387
+ output_scores = np.ones(y_true.shape[1])
1388
+
1389
+ output_scores[valid_score] = 1 - (numerator[valid_score] / denominator[valid_score])
1390
+ output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0
1391
+
1392
+ if isinstance(multioutput, str):
1393
+ if multioutput == "raw_values":
1394
+ # return scores individually
1395
+ return output_scores
1396
+ elif multioutput == "uniform_average":
1397
+ # passing None as weights to np.average results in uniform mean
1398
+ avg_weights = None
1399
+ else:
1400
+ raise ValueError(
1401
+ "multioutput is expected to be 'raw_values' "
1402
+ "or 'uniform_average' but we got %r"
1403
+ " instead." % multioutput
1404
+ )
1405
+ else:
1406
+ avg_weights = multioutput
1407
+
1408
+ return np.average(output_scores, weights=avg_weights)
1409
+
1410
+
1411
+ def d2_absolute_error_score(
1412
+ y_true, y_pred, *, sample_weight=None, multioutput="uniform_average"
1413
+ ):
1414
+ """
1415
+ :math:`D^2` regression score function, \
1416
+ fraction of absolute error explained.
1417
+
1418
+ Best possible score is 1.0 and it can be negative (because the model can be
1419
+ arbitrarily worse). A model that always uses the empirical median of `y_true`
1420
+ as constant prediction, disregarding the input features,
1421
+ gets a :math:`D^2` score of 0.0.
1422
+
1423
+ Read more in the :ref:`User Guide <d2_score>`.
1424
+
1425
+ .. versionadded:: 1.1
1426
+
1427
+ Parameters
1428
+ ----------
1429
+ y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)
1430
+ Ground truth (correct) target values.
1431
+
1432
+ y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)
1433
+ Estimated target values.
1434
+
1435
+ sample_weight : array-like of shape (n_samples,), optional
1436
+ Sample weights.
1437
+
1438
+ multioutput : {'raw_values', 'uniform_average'} or array-like of shape \
1439
+ (n_outputs,), default='uniform_average'
1440
+ Defines aggregating of multiple output values.
1441
+ Array-like value defines weights used to average scores.
1442
+
1443
+ 'raw_values' :
1444
+ Returns a full set of errors in case of multioutput input.
1445
+
1446
+ 'uniform_average' :
1447
+ Scores of all outputs are averaged with uniform weight.
1448
+
1449
+ Returns
1450
+ -------
1451
+ score : float or ndarray of floats
1452
+ The :math:`D^2` score with an absolute error deviance
1453
+ or ndarray of scores if 'multioutput' is 'raw_values'.
1454
+
1455
+ Notes
1456
+ -----
1457
+ Like :math:`R^2`, :math:`D^2` score may be negative
1458
+ (it need not actually be the square of a quantity D).
1459
+
1460
+ This metric is not well-defined for single samples and will return a NaN
1461
+ value if n_samples is less than two.
1462
+
1463
+ References
1464
+ ----------
1465
+ .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J.
1466
+ Wainwright. "Statistical Learning with Sparsity: The Lasso and
1467
+ Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/
1468
+
1469
+ Examples
1470
+ --------
1471
+ >>> from sklearn.metrics import d2_absolute_error_score
1472
+ >>> y_true = [3, -0.5, 2, 7]
1473
+ >>> y_pred = [2.5, 0.0, 2, 8]
1474
+ >>> d2_absolute_error_score(y_true, y_pred)
1475
+ 0.764...
1476
+ >>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
1477
+ >>> y_pred = [[0, 2], [-1, 2], [8, -5]]
1478
+ >>> d2_absolute_error_score(y_true, y_pred, multioutput='uniform_average')
1479
+ 0.691...
1480
+ >>> d2_absolute_error_score(y_true, y_pred, multioutput='raw_values')
1481
+ array([0.8125 , 0.57142857])
1482
+ >>> y_true = [1, 2, 3]
1483
+ >>> y_pred = [1, 2, 3]
1484
+ >>> d2_absolute_error_score(y_true, y_pred)
1485
+ 1.0
1486
+ >>> y_true = [1, 2, 3]
1487
+ >>> y_pred = [2, 2, 2]
1488
+ >>> d2_absolute_error_score(y_true, y_pred)
1489
+ 0.0
1490
+ >>> y_true = [1, 2, 3]
1491
+ >>> y_pred = [3, 2, 1]
1492
+ >>> d2_absolute_error_score(y_true, y_pred)
1493
+ -1.0
1494
+ """
1495
+ return d2_pinball_score(
1496
+ y_true, y_pred, sample_weight=sample_weight, alpha=0.5, multioutput=multioutput
1497
+ )
videollama2/lib/python3.10/site-packages/sklearn/metrics/_scorer.py ADDED
@@ -0,0 +1,867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The :mod:`sklearn.metrics.scorer` submodule implements a flexible
3
+ interface for model selection and evaluation using
4
+ arbitrary score functions.
5
+
6
+ A scorer object is a callable that can be passed to
7
+ :class:`~sklearn.model_selection.GridSearchCV` or
8
+ :func:`sklearn.model_selection.cross_val_score` as the ``scoring``
9
+ parameter, to specify how a model should be evaluated.
10
+
11
+ The signature of the call is ``(estimator, X, y)`` where ``estimator``
12
+ is the model to be evaluated, ``X`` is the test data and ``y`` is the
13
+ ground truth labeling (or ``None`` in the case of unsupervised models).
14
+ """
15
+
16
+ # Authors: Andreas Mueller <amueller@ais.uni-bonn.de>
17
+ # Lars Buitinck
18
+ # Arnaud Joly <arnaud.v.joly@gmail.com>
19
+ # License: Simplified BSD
20
+
21
+ from collections.abc import Iterable
22
+ from functools import partial
23
+ from collections import Counter
24
+ from traceback import format_exc
25
+
26
+ import numpy as np
27
+ import copy
28
+ import warnings
29
+
30
+ from . import (
31
+ r2_score,
32
+ median_absolute_error,
33
+ max_error,
34
+ mean_absolute_error,
35
+ mean_squared_error,
36
+ mean_squared_log_error,
37
+ mean_poisson_deviance,
38
+ mean_gamma_deviance,
39
+ accuracy_score,
40
+ top_k_accuracy_score,
41
+ f1_score,
42
+ roc_auc_score,
43
+ average_precision_score,
44
+ precision_score,
45
+ recall_score,
46
+ log_loss,
47
+ balanced_accuracy_score,
48
+ explained_variance_score,
49
+ brier_score_loss,
50
+ jaccard_score,
51
+ mean_absolute_percentage_error,
52
+ matthews_corrcoef,
53
+ class_likelihood_ratios,
54
+ )
55
+
56
+ from .cluster import adjusted_rand_score
57
+ from .cluster import rand_score
58
+ from .cluster import homogeneity_score
59
+ from .cluster import completeness_score
60
+ from .cluster import v_measure_score
61
+ from .cluster import mutual_info_score
62
+ from .cluster import adjusted_mutual_info_score
63
+ from .cluster import normalized_mutual_info_score
64
+ from .cluster import fowlkes_mallows_score
65
+
66
+ from ..utils.multiclass import type_of_target
67
+ from ..base import is_regressor
68
+
69
+
70
+ def _cached_call(cache, estimator, method, *args, **kwargs):
71
+ """Call estimator with method and args and kwargs."""
72
+ if cache is None:
73
+ return getattr(estimator, method)(*args, **kwargs)
74
+
75
+ try:
76
+ return cache[method]
77
+ except KeyError:
78
+ result = getattr(estimator, method)(*args, **kwargs)
79
+ cache[method] = result
80
+ return result
81
+
82
+
83
+ class _MultimetricScorer:
84
+ """Callable for multimetric scoring used to avoid repeated calls
85
+ to `predict_proba`, `predict`, and `decision_function`.
86
+
87
+ `_MultimetricScorer` will return a dictionary of scores corresponding to
88
+ the scorers in the dictionary. Note that `_MultimetricScorer` can be
89
+ created with a dictionary with one key (i.e. only one actual scorer).
90
+
91
+ Parameters
92
+ ----------
93
+ scorers : dict
94
+ Dictionary mapping names to callable scorers.
95
+
96
+ raise_exc : bool, default=True
97
+ Whether to raise the exception in `__call__` or not. If set to `False`
98
+ a formatted string of the exception details is passed as result of
99
+ the failing scorer.
100
+ """
101
+
102
+ def __init__(self, *, scorers, raise_exc=True):
103
+ self._scorers = scorers
104
+ self._raise_exc = raise_exc
105
+
106
+ def __call__(self, estimator, *args, **kwargs):
107
+ """Evaluate predicted target values."""
108
+ scores = {}
109
+ cache = {} if self._use_cache(estimator) else None
110
+ cached_call = partial(_cached_call, cache)
111
+
112
+ for name, scorer in self._scorers.items():
113
+ try:
114
+ if isinstance(scorer, _BaseScorer):
115
+ score = scorer._score(cached_call, estimator, *args, **kwargs)
116
+ else:
117
+ score = scorer(estimator, *args, **kwargs)
118
+ scores[name] = score
119
+ except Exception as e:
120
+ if self._raise_exc:
121
+ raise e
122
+ else:
123
+ scores[name] = format_exc()
124
+
125
+ return scores
126
+
127
+ def _use_cache(self, estimator):
128
+ """Return True if using a cache is beneficial.
129
+
130
+ Caching may be beneficial when one of these conditions holds:
131
+ - `_ProbaScorer` will be called twice.
132
+ - `_PredictScorer` will be called twice.
133
+ - `_ThresholdScorer` will be called twice.
134
+ - `_ThresholdScorer` and `_PredictScorer` are called and
135
+ estimator is a regressor.
136
+ - `_ThresholdScorer` and `_ProbaScorer` are called and
137
+ estimator does not have a `decision_function` attribute.
138
+
139
+ """
140
+ if len(self._scorers) == 1: # Only one scorer
141
+ return False
142
+
143
+ counter = Counter([type(v) for v in self._scorers.values()])
144
+
145
+ if any(
146
+ counter[known_type] > 1
147
+ for known_type in [_PredictScorer, _ProbaScorer, _ThresholdScorer]
148
+ ):
149
+ return True
150
+
151
+ if counter[_ThresholdScorer]:
152
+ if is_regressor(estimator) and counter[_PredictScorer]:
153
+ return True
154
+ elif counter[_ProbaScorer] and not hasattr(estimator, "decision_function"):
155
+ return True
156
+ return False
157
+
158
+
159
+ class _BaseScorer:
160
+ def __init__(self, score_func, sign, kwargs):
161
+ self._kwargs = kwargs
162
+ self._score_func = score_func
163
+ self._sign = sign
164
+
165
+ @staticmethod
166
+ def _check_pos_label(pos_label, classes):
167
+ if pos_label not in list(classes):
168
+ raise ValueError(f"pos_label={pos_label} is not a valid label: {classes}")
169
+
170
+ def _select_proba_binary(self, y_pred, classes):
171
+ """Select the column of the positive label in `y_pred` when
172
+ probabilities are provided.
173
+
174
+ Parameters
175
+ ----------
176
+ y_pred : ndarray of shape (n_samples, n_classes)
177
+ The prediction given by `predict_proba`.
178
+
179
+ classes : ndarray of shape (n_classes,)
180
+ The class labels for the estimator.
181
+
182
+ Returns
183
+ -------
184
+ y_pred : ndarray of shape (n_samples,)
185
+ Probability predictions of the positive class.
186
+ """
187
+ if y_pred.shape[1] == 2:
188
+ pos_label = self._kwargs.get("pos_label", classes[1])
189
+ self._check_pos_label(pos_label, classes)
190
+ col_idx = np.flatnonzero(classes == pos_label)[0]
191
+ return y_pred[:, col_idx]
192
+
193
+ err_msg = (
194
+ f"Got predict_proba of shape {y_pred.shape}, but need "
195
+ f"classifier with two classes for {self._score_func.__name__} "
196
+ "scoring"
197
+ )
198
+ raise ValueError(err_msg)
199
+
200
+ def __repr__(self):
201
+ kwargs_string = "".join(
202
+ [", %s=%s" % (str(k), str(v)) for k, v in self._kwargs.items()]
203
+ )
204
+ return "make_scorer(%s%s%s%s)" % (
205
+ self._score_func.__name__,
206
+ "" if self._sign > 0 else ", greater_is_better=False",
207
+ self._factory_args(),
208
+ kwargs_string,
209
+ )
210
+
211
+ def __call__(self, estimator, X, y_true, sample_weight=None):
212
+ """Evaluate predicted target values for X relative to y_true.
213
+
214
+ Parameters
215
+ ----------
216
+ estimator : object
217
+ Trained estimator to use for scoring. Must have a predict_proba
218
+ method; the output of that is used to compute the score.
219
+
220
+ X : {array-like, sparse matrix}
221
+ Test data that will be fed to estimator.predict.
222
+
223
+ y_true : array-like
224
+ Gold standard target values for X.
225
+
226
+ sample_weight : array-like of shape (n_samples,), default=None
227
+ Sample weights.
228
+
229
+ Returns
230
+ -------
231
+ score : float
232
+ Score function applied to prediction of estimator on X.
233
+ """
234
+ return self._score(
235
+ partial(_cached_call, None),
236
+ estimator,
237
+ X,
238
+ y_true,
239
+ sample_weight=sample_weight,
240
+ )
241
+
242
+ def _factory_args(self):
243
+ """Return non-default make_scorer arguments for repr."""
244
+ return ""
245
+
246
+
247
+ class _PredictScorer(_BaseScorer):
248
+ def _score(self, method_caller, estimator, X, y_true, sample_weight=None):
249
+ """Evaluate predicted target values for X relative to y_true.
250
+
251
+ Parameters
252
+ ----------
253
+ method_caller : callable
254
+ Returns predictions given an estimator, method name, and other
255
+ arguments, potentially caching results.
256
+
257
+ estimator : object
258
+ Trained estimator to use for scoring. Must have a `predict`
259
+ method; the output of that is used to compute the score.
260
+
261
+ X : {array-like, sparse matrix}
262
+ Test data that will be fed to estimator.predict.
263
+
264
+ y_true : array-like
265
+ Gold standard target values for X.
266
+
267
+ sample_weight : array-like of shape (n_samples,), default=None
268
+ Sample weights.
269
+
270
+ Returns
271
+ -------
272
+ score : float
273
+ Score function applied to prediction of estimator on X.
274
+ """
275
+
276
+ y_pred = method_caller(estimator, "predict", X)
277
+ if sample_weight is not None:
278
+ return self._sign * self._score_func(
279
+ y_true, y_pred, sample_weight=sample_weight, **self._kwargs
280
+ )
281
+ else:
282
+ return self._sign * self._score_func(y_true, y_pred, **self._kwargs)
283
+
284
+
285
+ class _ProbaScorer(_BaseScorer):
286
+ def _score(self, method_caller, clf, X, y, sample_weight=None):
287
+ """Evaluate predicted probabilities for X relative to y_true.
288
+
289
+ Parameters
290
+ ----------
291
+ method_caller : callable
292
+ Returns predictions given an estimator, method name, and other
293
+ arguments, potentially caching results.
294
+
295
+ clf : object
296
+ Trained classifier to use for scoring. Must have a `predict_proba`
297
+ method; the output of that is used to compute the score.
298
+
299
+ X : {array-like, sparse matrix}
300
+ Test data that will be fed to clf.predict_proba.
301
+
302
+ y : array-like
303
+ Gold standard target values for X. These must be class labels,
304
+ not probabilities.
305
+
306
+ sample_weight : array-like, default=None
307
+ Sample weights.
308
+
309
+ Returns
310
+ -------
311
+ score : float
312
+ Score function applied to prediction of estimator on X.
313
+ """
314
+
315
+ y_type = type_of_target(y)
316
+ y_pred = method_caller(clf, "predict_proba", X)
317
+ if y_type == "binary" and y_pred.shape[1] <= 2:
318
+ # `y_type` could be equal to "binary" even in a multi-class
319
+ # problem: (when only 2 class are given to `y_true` during scoring)
320
+ # Thus, we need to check for the shape of `y_pred`.
321
+ y_pred = self._select_proba_binary(y_pred, clf.classes_)
322
+ if sample_weight is not None:
323
+ return self._sign * self._score_func(
324
+ y, y_pred, sample_weight=sample_weight, **self._kwargs
325
+ )
326
+ else:
327
+ return self._sign * self._score_func(y, y_pred, **self._kwargs)
328
+
329
+ def _factory_args(self):
330
+ return ", needs_proba=True"
331
+
332
+
333
+ class _ThresholdScorer(_BaseScorer):
334
+ def _score(self, method_caller, clf, X, y, sample_weight=None):
335
+ """Evaluate decision function output for X relative to y_true.
336
+
337
+ Parameters
338
+ ----------
339
+ method_caller : callable
340
+ Returns predictions given an estimator, method name, and other
341
+ arguments, potentially caching results.
342
+
343
+ clf : object
344
+ Trained classifier to use for scoring. Must have either a
345
+ decision_function method or a predict_proba method; the output of
346
+ that is used to compute the score.
347
+
348
+ X : {array-like, sparse matrix}
349
+ Test data that will be fed to clf.decision_function or
350
+ clf.predict_proba.
351
+
352
+ y : array-like
353
+ Gold standard target values for X. These must be class labels,
354
+ not decision function values.
355
+
356
+ sample_weight : array-like, default=None
357
+ Sample weights.
358
+
359
+ Returns
360
+ -------
361
+ score : float
362
+ Score function applied to prediction of estimator on X.
363
+ """
364
+
365
+ y_type = type_of_target(y)
366
+ if y_type not in ("binary", "multilabel-indicator"):
367
+ raise ValueError("{0} format is not supported".format(y_type))
368
+
369
+ if is_regressor(clf):
370
+ y_pred = method_caller(clf, "predict", X)
371
+ else:
372
+ try:
373
+ y_pred = method_caller(clf, "decision_function", X)
374
+
375
+ if isinstance(y_pred, list):
376
+ # For multi-output multi-class estimator
377
+ y_pred = np.vstack([p for p in y_pred]).T
378
+ elif y_type == "binary" and "pos_label" in self._kwargs:
379
+ self._check_pos_label(self._kwargs["pos_label"], clf.classes_)
380
+ if self._kwargs["pos_label"] == clf.classes_[0]:
381
+ # The implicit positive class of the binary classifier
382
+ # does not match `pos_label`: we need to invert the
383
+ # predictions
384
+ y_pred *= -1
385
+
386
+ except (NotImplementedError, AttributeError):
387
+ y_pred = method_caller(clf, "predict_proba", X)
388
+
389
+ if y_type == "binary":
390
+ y_pred = self._select_proba_binary(y_pred, clf.classes_)
391
+ elif isinstance(y_pred, list):
392
+ y_pred = np.vstack([p[:, -1] for p in y_pred]).T
393
+
394
+ if sample_weight is not None:
395
+ return self._sign * self._score_func(
396
+ y, y_pred, sample_weight=sample_weight, **self._kwargs
397
+ )
398
+ else:
399
+ return self._sign * self._score_func(y, y_pred, **self._kwargs)
400
+
401
+ def _factory_args(self):
402
+ return ", needs_threshold=True"
403
+
404
+
405
+ def get_scorer(scoring):
406
+ """Get a scorer from string.
407
+
408
+ Read more in the :ref:`User Guide <scoring_parameter>`.
409
+ :func:`~sklearn.metrics.get_scorer_names` can be used to retrieve the names
410
+ of all available scorers.
411
+
412
+ Parameters
413
+ ----------
414
+ scoring : str or callable
415
+ Scoring method as string. If callable it is returned as is.
416
+
417
+ Returns
418
+ -------
419
+ scorer : callable
420
+ The scorer.
421
+
422
+ Notes
423
+ -----
424
+ When passed a string, this function always returns a copy of the scorer
425
+ object. Calling `get_scorer` twice for the same scorer results in two
426
+ separate scorer objects.
427
+ """
428
+ if isinstance(scoring, str):
429
+ try:
430
+ scorer = copy.deepcopy(_SCORERS[scoring])
431
+ except KeyError:
432
+ raise ValueError(
433
+ "%r is not a valid scoring value. "
434
+ "Use sklearn.metrics.get_scorer_names() "
435
+ "to get valid options." % scoring
436
+ )
437
+ else:
438
+ scorer = scoring
439
+ return scorer
440
+
441
+
442
+ def _passthrough_scorer(estimator, *args, **kwargs):
443
+ """Function that wraps estimator.score"""
444
+ return estimator.score(*args, **kwargs)
445
+
446
+
447
+ def check_scoring(estimator, scoring=None, *, allow_none=False):
448
+ """Determine scorer from user options.
449
+
450
+ A TypeError will be thrown if the estimator cannot be scored.
451
+
452
+ Parameters
453
+ ----------
454
+ estimator : estimator object implementing 'fit'
455
+ The object to use to fit the data.
456
+
457
+ scoring : str or callable, default=None
458
+ A string (see model evaluation documentation) or
459
+ a scorer callable object / function with signature
460
+ ``scorer(estimator, X, y)``.
461
+ If None, the provided estimator object's `score` method is used.
462
+
463
+ allow_none : bool, default=False
464
+ If no scoring is specified and the estimator has no score function, we
465
+ can either return None or raise an exception.
466
+
467
+ Returns
468
+ -------
469
+ scoring : callable
470
+ A scorer callable object / function with signature
471
+ ``scorer(estimator, X, y)``.
472
+ """
473
+ if not hasattr(estimator, "fit"):
474
+ raise TypeError(
475
+ "estimator should be an estimator implementing 'fit' method, %r was passed"
476
+ % estimator
477
+ )
478
+ if isinstance(scoring, str):
479
+ return get_scorer(scoring)
480
+ elif callable(scoring):
481
+ # Heuristic to ensure user has not passed a metric
482
+ module = getattr(scoring, "__module__", None)
483
+ if (
484
+ hasattr(module, "startswith")
485
+ and module.startswith("sklearn.metrics.")
486
+ and not module.startswith("sklearn.metrics._scorer")
487
+ and not module.startswith("sklearn.metrics.tests.")
488
+ ):
489
+ raise ValueError(
490
+ "scoring value %r looks like it is a metric "
491
+ "function rather than a scorer. A scorer should "
492
+ "require an estimator as its first parameter. "
493
+ "Please use `make_scorer` to convert a metric "
494
+ "to a scorer." % scoring
495
+ )
496
+ return get_scorer(scoring)
497
+ elif scoring is None:
498
+ if hasattr(estimator, "score"):
499
+ return _passthrough_scorer
500
+ elif allow_none:
501
+ return None
502
+ else:
503
+ raise TypeError(
504
+ "If no scoring is specified, the estimator passed should "
505
+ "have a 'score' method. The estimator %r does not." % estimator
506
+ )
507
+ elif isinstance(scoring, Iterable):
508
+ raise ValueError(
509
+ "For evaluating multiple scores, use "
510
+ "sklearn.model_selection.cross_validate instead. "
511
+ "{0} was passed.".format(scoring)
512
+ )
513
+ else:
514
+ raise ValueError(
515
+ "scoring value should either be a callable, string or None. %r was passed"
516
+ % scoring
517
+ )
518
+
519
+
520
+ def _check_multimetric_scoring(estimator, scoring):
521
+ """Check the scoring parameter in cases when multiple metrics are allowed.
522
+
523
+ Parameters
524
+ ----------
525
+ estimator : sklearn estimator instance
526
+ The estimator for which the scoring will be applied.
527
+
528
+ scoring : list, tuple or dict
529
+ Strategy to evaluate the performance of the cross-validated model on
530
+ the test set.
531
+
532
+ The possibilities are:
533
+
534
+ - a list or tuple of unique strings;
535
+ - a callable returning a dictionary where they keys are the metric
536
+ names and the values are the metric scores;
537
+ - a dictionary with metric names as keys and callables a values.
538
+
539
+ See :ref:`multimetric_grid_search` for an example.
540
+
541
+ Returns
542
+ -------
543
+ scorers_dict : dict
544
+ A dict mapping each scorer name to its validated scorer.
545
+ """
546
+ err_msg_generic = (
547
+ f"scoring is invalid (got {scoring!r}). Refer to the "
548
+ "scoring glossary for details: "
549
+ "https://scikit-learn.org/stable/glossary.html#term-scoring"
550
+ )
551
+
552
+ if isinstance(scoring, (list, tuple, set)):
553
+ err_msg = (
554
+ "The list/tuple elements must be unique strings of predefined scorers. "
555
+ )
556
+ try:
557
+ keys = set(scoring)
558
+ except TypeError as e:
559
+ raise ValueError(err_msg) from e
560
+
561
+ if len(keys) != len(scoring):
562
+ raise ValueError(
563
+ f"{err_msg} Duplicate elements were found in"
564
+ f" the given list. {scoring!r}"
565
+ )
566
+ elif len(keys) > 0:
567
+ if not all(isinstance(k, str) for k in keys):
568
+ if any(callable(k) for k in keys):
569
+ raise ValueError(
570
+ f"{err_msg} One or more of the elements "
571
+ "were callables. Use a dict of score "
572
+ "name mapped to the scorer callable. "
573
+ f"Got {scoring!r}"
574
+ )
575
+ else:
576
+ raise ValueError(
577
+ f"{err_msg} Non-string types were found "
578
+ f"in the given list. Got {scoring!r}"
579
+ )
580
+ scorers = {
581
+ scorer: check_scoring(estimator, scoring=scorer) for scorer in scoring
582
+ }
583
+ else:
584
+ raise ValueError(f"{err_msg} Empty list was given. {scoring!r}")
585
+
586
+ elif isinstance(scoring, dict):
587
+ keys = set(scoring)
588
+ if not all(isinstance(k, str) for k in keys):
589
+ raise ValueError(
590
+ "Non-string types were found in the keys of "
591
+ f"the given dict. scoring={scoring!r}"
592
+ )
593
+ if len(keys) == 0:
594
+ raise ValueError(f"An empty dict was passed. {scoring!r}")
595
+ scorers = {
596
+ key: check_scoring(estimator, scoring=scorer)
597
+ for key, scorer in scoring.items()
598
+ }
599
+ else:
600
+ raise ValueError(err_msg_generic)
601
+ return scorers
602
+
603
+
604
+ def make_scorer(
605
+ score_func,
606
+ *,
607
+ greater_is_better=True,
608
+ needs_proba=False,
609
+ needs_threshold=False,
610
+ **kwargs,
611
+ ):
612
+ """Make a scorer from a performance metric or loss function.
613
+
614
+ This factory function wraps scoring functions for use in
615
+ :class:`~sklearn.model_selection.GridSearchCV` and
616
+ :func:`~sklearn.model_selection.cross_val_score`.
617
+ It takes a score function, such as :func:`~sklearn.metrics.accuracy_score`,
618
+ :func:`~sklearn.metrics.mean_squared_error`,
619
+ :func:`~sklearn.metrics.adjusted_rand_score` or
620
+ :func:`~sklearn.metrics.average_precision_score`
621
+ and returns a callable that scores an estimator's output.
622
+ The signature of the call is `(estimator, X, y)` where `estimator`
623
+ is the model to be evaluated, `X` is the data and `y` is the
624
+ ground truth labeling (or `None` in the case of unsupervised models).
625
+
626
+ Read more in the :ref:`User Guide <scoring>`.
627
+
628
+ Parameters
629
+ ----------
630
+ score_func : callable
631
+ Score function (or loss function) with signature
632
+ `score_func(y, y_pred, **kwargs)`.
633
+
634
+ greater_is_better : bool, default=True
635
+ Whether `score_func` is a score function (default), meaning high is
636
+ good, or a loss function, meaning low is good. In the latter case, the
637
+ scorer object will sign-flip the outcome of the `score_func`.
638
+
639
+ needs_proba : bool, default=False
640
+ Whether `score_func` requires `predict_proba` to get probability
641
+ estimates out of a classifier.
642
+
643
+ If True, for binary `y_true`, the score function is supposed to accept
644
+ a 1D `y_pred` (i.e., probability of the positive class, shape
645
+ `(n_samples,)`).
646
+
647
+ needs_threshold : bool, default=False
648
+ Whether `score_func` takes a continuous decision certainty.
649
+ This only works for binary classification using estimators that
650
+ have either a `decision_function` or `predict_proba` method.
651
+
652
+ If True, for binary `y_true`, the score function is supposed to accept
653
+ a 1D `y_pred` (i.e., probability of the positive class or the decision
654
+ function, shape `(n_samples,)`).
655
+
656
+ For example `average_precision` or the area under the roc curve
657
+ can not be computed using discrete predictions alone.
658
+
659
+ **kwargs : additional arguments
660
+ Additional parameters to be passed to `score_func`.
661
+
662
+ Returns
663
+ -------
664
+ scorer : callable
665
+ Callable object that returns a scalar score; greater is better.
666
+
667
+ Notes
668
+ -----
669
+ If `needs_proba=False` and `needs_threshold=False`, the score
670
+ function is supposed to accept the output of :term:`predict`. If
671
+ `needs_proba=True`, the score function is supposed to accept the
672
+ output of :term:`predict_proba` (For binary `y_true`, the score function is
673
+ supposed to accept probability of the positive class). If
674
+ `needs_threshold=True`, the score function is supposed to accept the
675
+ output of :term:`decision_function` or :term:`predict_proba` when
676
+ :term:`decision_function` is not present.
677
+
678
+ Examples
679
+ --------
680
+ >>> from sklearn.metrics import fbeta_score, make_scorer
681
+ >>> ftwo_scorer = make_scorer(fbeta_score, beta=2)
682
+ >>> ftwo_scorer
683
+ make_scorer(fbeta_score, beta=2)
684
+ >>> from sklearn.model_selection import GridSearchCV
685
+ >>> from sklearn.svm import LinearSVC
686
+ >>> grid = GridSearchCV(LinearSVC(), param_grid={'C': [1, 10]},
687
+ ... scoring=ftwo_scorer)
688
+ """
689
+ sign = 1 if greater_is_better else -1
690
+ if needs_proba and needs_threshold:
691
+ raise ValueError(
692
+ "Set either needs_proba or needs_threshold to True, but not both."
693
+ )
694
+ if needs_proba:
695
+ cls = _ProbaScorer
696
+ elif needs_threshold:
697
+ cls = _ThresholdScorer
698
+ else:
699
+ cls = _PredictScorer
700
+ return cls(score_func, sign, kwargs)
701
+
702
+
703
+ # Standard regression scores
704
+ explained_variance_scorer = make_scorer(explained_variance_score)
705
+ r2_scorer = make_scorer(r2_score)
706
+ max_error_scorer = make_scorer(max_error, greater_is_better=False)
707
+ neg_mean_squared_error_scorer = make_scorer(mean_squared_error, greater_is_better=False)
708
+ neg_mean_squared_log_error_scorer = make_scorer(
709
+ mean_squared_log_error, greater_is_better=False
710
+ )
711
+ neg_mean_absolute_error_scorer = make_scorer(
712
+ mean_absolute_error, greater_is_better=False
713
+ )
714
+ neg_mean_absolute_percentage_error_scorer = make_scorer(
715
+ mean_absolute_percentage_error, greater_is_better=False
716
+ )
717
+ neg_median_absolute_error_scorer = make_scorer(
718
+ median_absolute_error, greater_is_better=False
719
+ )
720
+ neg_root_mean_squared_error_scorer = make_scorer(
721
+ mean_squared_error, greater_is_better=False, squared=False
722
+ )
723
+ neg_mean_poisson_deviance_scorer = make_scorer(
724
+ mean_poisson_deviance, greater_is_better=False
725
+ )
726
+
727
+ neg_mean_gamma_deviance_scorer = make_scorer(
728
+ mean_gamma_deviance, greater_is_better=False
729
+ )
730
+
731
+ # Standard Classification Scores
732
+ accuracy_scorer = make_scorer(accuracy_score)
733
+ balanced_accuracy_scorer = make_scorer(balanced_accuracy_score)
734
+ matthews_corrcoef_scorer = make_scorer(matthews_corrcoef)
735
+
736
+
737
+ def positive_likelihood_ratio(y_true, y_pred):
738
+ return class_likelihood_ratios(y_true, y_pred)[0]
739
+
740
+
741
+ def negative_likelihood_ratio(y_true, y_pred):
742
+ return class_likelihood_ratios(y_true, y_pred)[1]
743
+
744
+
745
+ positive_likelihood_ratio_scorer = make_scorer(positive_likelihood_ratio)
746
+ neg_negative_likelihood_ratio_scorer = make_scorer(
747
+ negative_likelihood_ratio, greater_is_better=False
748
+ )
749
+
750
+ # Score functions that need decision values
751
+ top_k_accuracy_scorer = make_scorer(
752
+ top_k_accuracy_score, greater_is_better=True, needs_threshold=True
753
+ )
754
+ roc_auc_scorer = make_scorer(
755
+ roc_auc_score, greater_is_better=True, needs_threshold=True
756
+ )
757
+ average_precision_scorer = make_scorer(average_precision_score, needs_threshold=True)
758
+ roc_auc_ovo_scorer = make_scorer(roc_auc_score, needs_proba=True, multi_class="ovo")
759
+ roc_auc_ovo_weighted_scorer = make_scorer(
760
+ roc_auc_score, needs_proba=True, multi_class="ovo", average="weighted"
761
+ )
762
+ roc_auc_ovr_scorer = make_scorer(roc_auc_score, needs_proba=True, multi_class="ovr")
763
+ roc_auc_ovr_weighted_scorer = make_scorer(
764
+ roc_auc_score, needs_proba=True, multi_class="ovr", average="weighted"
765
+ )
766
+
767
+ # Score function for probabilistic classification
768
+ neg_log_loss_scorer = make_scorer(log_loss, greater_is_better=False, needs_proba=True)
769
+ neg_brier_score_scorer = make_scorer(
770
+ brier_score_loss, greater_is_better=False, needs_proba=True
771
+ )
772
+ brier_score_loss_scorer = make_scorer(
773
+ brier_score_loss, greater_is_better=False, needs_proba=True
774
+ )
775
+
776
+
777
+ # Clustering scores
778
+ adjusted_rand_scorer = make_scorer(adjusted_rand_score)
779
+ rand_scorer = make_scorer(rand_score)
780
+ homogeneity_scorer = make_scorer(homogeneity_score)
781
+ completeness_scorer = make_scorer(completeness_score)
782
+ v_measure_scorer = make_scorer(v_measure_score)
783
+ mutual_info_scorer = make_scorer(mutual_info_score)
784
+ adjusted_mutual_info_scorer = make_scorer(adjusted_mutual_info_score)
785
+ normalized_mutual_info_scorer = make_scorer(normalized_mutual_info_score)
786
+ fowlkes_mallows_scorer = make_scorer(fowlkes_mallows_score)
787
+
788
+
789
+ # TODO(1.3) Remove
790
+ class _DeprecatedScorers(dict):
791
+ """A temporary class to deprecate SCORERS."""
792
+
793
+ def __getitem__(self, item):
794
+ warnings.warn(
795
+ "sklearn.metrics.SCORERS is deprecated and will be removed in v1.3. "
796
+ "Please use sklearn.metrics.get_scorer_names to get a list of available "
797
+ "scorers and sklearn.metrics.get_metric to get scorer.",
798
+ FutureWarning,
799
+ )
800
+ return super().__getitem__(item)
801
+
802
+
803
+ _SCORERS = dict(
804
+ explained_variance=explained_variance_scorer,
805
+ r2=r2_scorer,
806
+ max_error=max_error_scorer,
807
+ matthews_corrcoef=matthews_corrcoef_scorer,
808
+ neg_median_absolute_error=neg_median_absolute_error_scorer,
809
+ neg_mean_absolute_error=neg_mean_absolute_error_scorer,
810
+ neg_mean_absolute_percentage_error=neg_mean_absolute_percentage_error_scorer, # noqa
811
+ neg_mean_squared_error=neg_mean_squared_error_scorer,
812
+ neg_mean_squared_log_error=neg_mean_squared_log_error_scorer,
813
+ neg_root_mean_squared_error=neg_root_mean_squared_error_scorer,
814
+ neg_mean_poisson_deviance=neg_mean_poisson_deviance_scorer,
815
+ neg_mean_gamma_deviance=neg_mean_gamma_deviance_scorer,
816
+ accuracy=accuracy_scorer,
817
+ top_k_accuracy=top_k_accuracy_scorer,
818
+ roc_auc=roc_auc_scorer,
819
+ roc_auc_ovr=roc_auc_ovr_scorer,
820
+ roc_auc_ovo=roc_auc_ovo_scorer,
821
+ roc_auc_ovr_weighted=roc_auc_ovr_weighted_scorer,
822
+ roc_auc_ovo_weighted=roc_auc_ovo_weighted_scorer,
823
+ balanced_accuracy=balanced_accuracy_scorer,
824
+ average_precision=average_precision_scorer,
825
+ neg_log_loss=neg_log_loss_scorer,
826
+ neg_brier_score=neg_brier_score_scorer,
827
+ positive_likelihood_ratio=positive_likelihood_ratio_scorer,
828
+ neg_negative_likelihood_ratio=neg_negative_likelihood_ratio_scorer,
829
+ # Cluster metrics that use supervised evaluation
830
+ adjusted_rand_score=adjusted_rand_scorer,
831
+ rand_score=rand_scorer,
832
+ homogeneity_score=homogeneity_scorer,
833
+ completeness_score=completeness_scorer,
834
+ v_measure_score=v_measure_scorer,
835
+ mutual_info_score=mutual_info_scorer,
836
+ adjusted_mutual_info_score=adjusted_mutual_info_scorer,
837
+ normalized_mutual_info_score=normalized_mutual_info_scorer,
838
+ fowlkes_mallows_score=fowlkes_mallows_scorer,
839
+ )
840
+
841
+
842
+ def get_scorer_names():
843
+ """Get the names of all available scorers.
844
+
845
+ These names can be passed to :func:`~sklearn.metrics.get_scorer` to
846
+ retrieve the scorer object.
847
+
848
+ Returns
849
+ -------
850
+ list of str
851
+ Names of all available scorers.
852
+ """
853
+ return sorted(_SCORERS.keys())
854
+
855
+
856
+ for name, metric in [
857
+ ("precision", precision_score),
858
+ ("recall", recall_score),
859
+ ("f1", f1_score),
860
+ ("jaccard", jaccard_score),
861
+ ]:
862
+ _SCORERS[name] = make_scorer(metric, average="binary")
863
+ for average in ["macro", "micro", "samples", "weighted"]:
864
+ qualified_name = "{0}_{1}".format(name, average)
865
+ _SCORERS[qualified_name] = make_scorer(metric, pos_label=None, average=average)
866
+
867
+ SCORERS = _DeprecatedScorers(_SCORERS)
videollama2/lib/python3.10/site-packages/sklearn/metrics/pairwise.py ADDED
@@ -0,0 +1,2205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
2
+ # Mathieu Blondel <mathieu@mblondel.org>
3
+ # Robert Layton <robertlayton@gmail.com>
4
+ # Andreas Mueller <amueller@ais.uni-bonn.de>
5
+ # Philippe Gervais <philippe.gervais@inria.fr>
6
+ # Lars Buitinck
7
+ # Joel Nothman <joel.nothman@gmail.com>
8
+ # License: BSD 3 clause
9
+
10
+ import itertools
11
+ from functools import partial
12
+ import warnings
13
+
14
+ import numpy as np
15
+ from scipy.spatial import distance
16
+ from scipy.sparse import csr_matrix
17
+ from scipy.sparse import issparse
18
+ from joblib import effective_n_jobs
19
+
20
+ from .. import config_context
21
+ from ..utils.validation import _num_samples
22
+ from ..utils.validation import check_non_negative
23
+ from ..utils import check_array
24
+ from ..utils import gen_even_slices
25
+ from ..utils import gen_batches, get_chunk_n_rows
26
+ from ..utils import is_scalar_nan
27
+ from ..utils.extmath import row_norms, safe_sparse_dot
28
+ from ..preprocessing import normalize
29
+ from ..utils._mask import _get_mask
30
+ from ..utils.parallel import delayed, Parallel
31
+ from ..utils.fixes import sp_version, parse_version
32
+
33
+ from ._pairwise_distances_reduction import ArgKmin
34
+ from ._pairwise_fast import _chi2_kernel_fast, _sparse_manhattan
35
+ from ..exceptions import DataConversionWarning
36
+
37
+
38
+ # Utility Functions
39
+ def _return_float_dtype(X, Y):
40
+ """
41
+ 1. If dtype of X and Y is float32, then dtype float32 is returned.
42
+ 2. Else dtype float is returned.
43
+ """
44
+ if not issparse(X) and not isinstance(X, np.ndarray):
45
+ X = np.asarray(X)
46
+
47
+ if Y is None:
48
+ Y_dtype = X.dtype
49
+ elif not issparse(Y) and not isinstance(Y, np.ndarray):
50
+ Y = np.asarray(Y)
51
+ Y_dtype = Y.dtype
52
+ else:
53
+ Y_dtype = Y.dtype
54
+
55
+ if X.dtype == Y_dtype == np.float32:
56
+ dtype = np.float32
57
+ else:
58
+ dtype = float
59
+
60
+ return X, Y, dtype
61
+
62
+
63
+ def check_pairwise_arrays(
64
+ X,
65
+ Y,
66
+ *,
67
+ precomputed=False,
68
+ dtype=None,
69
+ accept_sparse="csr",
70
+ force_all_finite=True,
71
+ copy=False,
72
+ ):
73
+ """Set X and Y appropriately and checks inputs.
74
+
75
+ If Y is None, it is set as a pointer to X (i.e. not a copy).
76
+ If Y is given, this does not happen.
77
+ All distance metrics should use this function first to assert that the
78
+ given parameters are correct and safe to use.
79
+
80
+ Specifically, this function first ensures that both X and Y are arrays,
81
+ then checks that they are at least two dimensional while ensuring that
82
+ their elements are floats (or dtype if provided). Finally, the function
83
+ checks that the size of the second dimension of the two arrays is equal, or
84
+ the equivalent check for a precomputed distance matrix.
85
+
86
+ Parameters
87
+ ----------
88
+ X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
89
+
90
+ Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)
91
+
92
+ precomputed : bool, default=False
93
+ True if X is to be treated as precomputed distances to the samples in
94
+ Y.
95
+
96
+ dtype : str, type, list of type, default=None
97
+ Data type required for X and Y. If None, the dtype will be an
98
+ appropriate float type selected by _return_float_dtype.
99
+
100
+ .. versionadded:: 0.18
101
+
102
+ accept_sparse : str, bool or list/tuple of str, default='csr'
103
+ String[s] representing allowed sparse matrix formats, such as 'csc',
104
+ 'csr', etc. If the input is sparse but not in the allowed format,
105
+ it will be converted to the first listed format. True allows the input
106
+ to be any format. False means that a sparse matrix input will
107
+ raise an error.
108
+
109
+ force_all_finite : bool or 'allow-nan', default=True
110
+ Whether to raise an error on np.inf, np.nan, pd.NA in array. The
111
+ possibilities are:
112
+
113
+ - True: Force all values of array to be finite.
114
+ - False: accepts np.inf, np.nan, pd.NA in array.
115
+ - 'allow-nan': accepts only np.nan and pd.NA values in array. Values
116
+ cannot be infinite.
117
+
118
+ .. versionadded:: 0.22
119
+ ``force_all_finite`` accepts the string ``'allow-nan'``.
120
+
121
+ .. versionchanged:: 0.23
122
+ Accepts `pd.NA` and converts it into `np.nan`.
123
+
124
+ copy : bool, default=False
125
+ Whether a forced copy will be triggered. If copy=False, a copy might
126
+ be triggered by a conversion.
127
+
128
+ .. versionadded:: 0.22
129
+
130
+ Returns
131
+ -------
132
+ safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
133
+ An array equal to X, guaranteed to be a numpy array.
134
+
135
+ safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)
136
+ An array equal to Y if Y was not None, guaranteed to be a numpy array.
137
+ If Y was None, safe_Y will be a pointer to X.
138
+ """
139
+ X, Y, dtype_float = _return_float_dtype(X, Y)
140
+
141
+ estimator = "check_pairwise_arrays"
142
+ if dtype is None:
143
+ dtype = dtype_float
144
+
145
+ if Y is X or Y is None:
146
+ X = Y = check_array(
147
+ X,
148
+ accept_sparse=accept_sparse,
149
+ dtype=dtype,
150
+ copy=copy,
151
+ force_all_finite=force_all_finite,
152
+ estimator=estimator,
153
+ )
154
+ else:
155
+ X = check_array(
156
+ X,
157
+ accept_sparse=accept_sparse,
158
+ dtype=dtype,
159
+ copy=copy,
160
+ force_all_finite=force_all_finite,
161
+ estimator=estimator,
162
+ )
163
+ Y = check_array(
164
+ Y,
165
+ accept_sparse=accept_sparse,
166
+ dtype=dtype,
167
+ copy=copy,
168
+ force_all_finite=force_all_finite,
169
+ estimator=estimator,
170
+ )
171
+
172
+ if precomputed:
173
+ if X.shape[1] != Y.shape[0]:
174
+ raise ValueError(
175
+ "Precomputed metric requires shape "
176
+ "(n_queries, n_indexed). Got (%d, %d) "
177
+ "for %d indexed." % (X.shape[0], X.shape[1], Y.shape[0])
178
+ )
179
+ elif X.shape[1] != Y.shape[1]:
180
+ raise ValueError(
181
+ "Incompatible dimension for X and Y matrices: "
182
+ "X.shape[1] == %d while Y.shape[1] == %d" % (X.shape[1], Y.shape[1])
183
+ )
184
+
185
+ return X, Y
186
+
187
+
188
+ def check_paired_arrays(X, Y):
189
+ """Set X and Y appropriately and checks inputs for paired distances.
190
+
191
+ All paired distance metrics should use this function first to assert that
192
+ the given parameters are correct and safe to use.
193
+
194
+ Specifically, this function first ensures that both X and Y are arrays,
195
+ then checks that they are at least two dimensional while ensuring that
196
+ their elements are floats. Finally, the function checks that the size
197
+ of the dimensions of the two arrays are equal.
198
+
199
+ Parameters
200
+ ----------
201
+ X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
202
+
203
+ Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)
204
+
205
+ Returns
206
+ -------
207
+ safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
208
+ An array equal to X, guaranteed to be a numpy array.
209
+
210
+ safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)
211
+ An array equal to Y if Y was not None, guaranteed to be a numpy array.
212
+ If Y was None, safe_Y will be a pointer to X.
213
+ """
214
+ X, Y = check_pairwise_arrays(X, Y)
215
+ if X.shape != Y.shape:
216
+ raise ValueError(
217
+ "X and Y should be of same shape. They were respectively %r and %r long."
218
+ % (X.shape, Y.shape)
219
+ )
220
+ return X, Y
221
+
222
+
223
+ # Pairwise distances
224
+ def euclidean_distances(
225
+ X, Y=None, *, Y_norm_squared=None, squared=False, X_norm_squared=None
226
+ ):
227
+ """
228
+ Compute the distance matrix between each pair from a vector array X and Y.
229
+
230
+ For efficiency reasons, the euclidean distance between a pair of row
231
+ vector x and y is computed as::
232
+
233
+ dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y))
234
+
235
+ This formulation has two advantages over other ways of computing distances.
236
+ First, it is computationally efficient when dealing with sparse data.
237
+ Second, if one argument varies but the other remains unchanged, then
238
+ `dot(x, x)` and/or `dot(y, y)` can be pre-computed.
239
+
240
+ However, this is not the most precise way of doing this computation,
241
+ because this equation potentially suffers from "catastrophic cancellation".
242
+ Also, the distance matrix returned by this function may not be exactly
243
+ symmetric as required by, e.g., ``scipy.spatial.distance`` functions.
244
+
245
+ Read more in the :ref:`User Guide <metrics>`.
246
+
247
+ Parameters
248
+ ----------
249
+ X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
250
+ An array where each row is a sample and each column is a feature.
251
+
252
+ Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), \
253
+ default=None
254
+ An array where each row is a sample and each column is a feature.
255
+ If `None`, method uses `Y=X`.
256
+
257
+ Y_norm_squared : array-like of shape (n_samples_Y,) or (n_samples_Y, 1) \
258
+ or (1, n_samples_Y), default=None
259
+ Pre-computed dot-products of vectors in Y (e.g.,
260
+ ``(Y**2).sum(axis=1)``)
261
+ May be ignored in some cases, see the note below.
262
+
263
+ squared : bool, default=False
264
+ Return squared Euclidean distances.
265
+
266
+ X_norm_squared : array-like of shape (n_samples_X,) or (n_samples_X, 1) \
267
+ or (1, n_samples_X), default=None
268
+ Pre-computed dot-products of vectors in X (e.g.,
269
+ ``(X**2).sum(axis=1)``)
270
+ May be ignored in some cases, see the note below.
271
+
272
+ Returns
273
+ -------
274
+ distances : ndarray of shape (n_samples_X, n_samples_Y)
275
+ Returns the distances between the row vectors of `X`
276
+ and the row vectors of `Y`.
277
+
278
+ See Also
279
+ --------
280
+ paired_distances : Distances between pairs of elements of X and Y.
281
+
282
+ Notes
283
+ -----
284
+ To achieve a better accuracy, `X_norm_squared` and `Y_norm_squared` may be
285
+ unused if they are passed as `np.float32`.
286
+
287
+ Examples
288
+ --------
289
+ >>> from sklearn.metrics.pairwise import euclidean_distances
290
+ >>> X = [[0, 1], [1, 1]]
291
+ >>> # distance between rows of X
292
+ >>> euclidean_distances(X, X)
293
+ array([[0., 1.],
294
+ [1., 0.]])
295
+ >>> # get distance to origin
296
+ >>> euclidean_distances(X, [[0, 0]])
297
+ array([[1. ],
298
+ [1.41421356]])
299
+ """
300
+ X, Y = check_pairwise_arrays(X, Y)
301
+
302
+ if X_norm_squared is not None:
303
+ X_norm_squared = check_array(X_norm_squared, ensure_2d=False)
304
+ original_shape = X_norm_squared.shape
305
+ if X_norm_squared.shape == (X.shape[0],):
306
+ X_norm_squared = X_norm_squared.reshape(-1, 1)
307
+ if X_norm_squared.shape == (1, X.shape[0]):
308
+ X_norm_squared = X_norm_squared.T
309
+ if X_norm_squared.shape != (X.shape[0], 1):
310
+ raise ValueError(
311
+ f"Incompatible dimensions for X of shape {X.shape} and "
312
+ f"X_norm_squared of shape {original_shape}."
313
+ )
314
+
315
+ if Y_norm_squared is not None:
316
+ Y_norm_squared = check_array(Y_norm_squared, ensure_2d=False)
317
+ original_shape = Y_norm_squared.shape
318
+ if Y_norm_squared.shape == (Y.shape[0],):
319
+ Y_norm_squared = Y_norm_squared.reshape(1, -1)
320
+ if Y_norm_squared.shape == (Y.shape[0], 1):
321
+ Y_norm_squared = Y_norm_squared.T
322
+ if Y_norm_squared.shape != (1, Y.shape[0]):
323
+ raise ValueError(
324
+ f"Incompatible dimensions for Y of shape {Y.shape} and "
325
+ f"Y_norm_squared of shape {original_shape}."
326
+ )
327
+
328
+ return _euclidean_distances(X, Y, X_norm_squared, Y_norm_squared, squared)
329
+
330
+
331
+ def _euclidean_distances(X, Y, X_norm_squared=None, Y_norm_squared=None, squared=False):
332
+ """Computational part of euclidean_distances
333
+
334
+ Assumes inputs are already checked.
335
+
336
+ If norms are passed as float32, they are unused. If arrays are passed as
337
+ float32, norms needs to be recomputed on upcast chunks.
338
+ TODO: use a float64 accumulator in row_norms to avoid the latter.
339
+ """
340
+ if X_norm_squared is not None:
341
+ if X_norm_squared.dtype == np.float32:
342
+ XX = None
343
+ else:
344
+ XX = X_norm_squared.reshape(-1, 1)
345
+ elif X.dtype == np.float32:
346
+ XX = None
347
+ else:
348
+ XX = row_norms(X, squared=True)[:, np.newaxis]
349
+
350
+ if Y is X:
351
+ YY = None if XX is None else XX.T
352
+ else:
353
+ if Y_norm_squared is not None:
354
+ if Y_norm_squared.dtype == np.float32:
355
+ YY = None
356
+ else:
357
+ YY = Y_norm_squared.reshape(1, -1)
358
+ elif Y.dtype == np.float32:
359
+ YY = None
360
+ else:
361
+ YY = row_norms(Y, squared=True)[np.newaxis, :]
362
+
363
+ if X.dtype == np.float32:
364
+ # To minimize precision issues with float32, we compute the distance
365
+ # matrix on chunks of X and Y upcast to float64
366
+ distances = _euclidean_distances_upcast(X, XX, Y, YY)
367
+ else:
368
+ # if dtype is already float64, no need to chunk and upcast
369
+ distances = -2 * safe_sparse_dot(X, Y.T, dense_output=True)
370
+ distances += XX
371
+ distances += YY
372
+ np.maximum(distances, 0, out=distances)
373
+
374
+ # Ensure that distances between vectors and themselves are set to 0.0.
375
+ # This may not be the case due to floating point rounding errors.
376
+ if X is Y:
377
+ np.fill_diagonal(distances, 0)
378
+
379
+ return distances if squared else np.sqrt(distances, out=distances)
380
+
381
+
382
+ def nan_euclidean_distances(
383
+ X, Y=None, *, squared=False, missing_values=np.nan, copy=True
384
+ ):
385
+ """Calculate the euclidean distances in the presence of missing values.
386
+
387
+ Compute the euclidean distance between each pair of samples in X and Y,
388
+ where Y=X is assumed if Y=None. When calculating the distance between a
389
+ pair of samples, this formulation ignores feature coordinates with a
390
+ missing value in either sample and scales up the weight of the remaining
391
+ coordinates:
392
+
393
+ dist(x,y) = sqrt(weight * sq. distance from present coordinates)
394
+ where,
395
+ weight = Total # of coordinates / # of present coordinates
396
+
397
+ For example, the distance between ``[3, na, na, 6]`` and ``[1, na, 4, 5]``
398
+ is:
399
+
400
+ .. math::
401
+ \\sqrt{\\frac{4}{2}((3-1)^2 + (6-5)^2)}
402
+
403
+ If all the coordinates are missing or if there are no common present
404
+ coordinates then NaN is returned for that pair.
405
+
406
+ Read more in the :ref:`User Guide <metrics>`.
407
+
408
+ .. versionadded:: 0.22
409
+
410
+ Parameters
411
+ ----------
412
+ X : array-like of shape (n_samples_X, n_features)
413
+ An array where each row is a sample and each column is a feature.
414
+
415
+ Y : array-like of shape (n_samples_Y, n_features), default=None
416
+ An array where each row is a sample and each column is a feature.
417
+ If `None`, method uses `Y=X`.
418
+
419
+ squared : bool, default=False
420
+ Return squared Euclidean distances.
421
+
422
+ missing_values : np.nan or int, default=np.nan
423
+ Representation of missing value.
424
+
425
+ copy : bool, default=True
426
+ Make and use a deep copy of X and Y (if Y exists).
427
+
428
+ Returns
429
+ -------
430
+ distances : ndarray of shape (n_samples_X, n_samples_Y)
431
+ Returns the distances between the row vectors of `X`
432
+ and the row vectors of `Y`.
433
+
434
+ See Also
435
+ --------
436
+ paired_distances : Distances between pairs of elements of X and Y.
437
+
438
+ References
439
+ ----------
440
+ * John K. Dixon, "Pattern Recognition with Partly Missing Data",
441
+ IEEE Transactions on Systems, Man, and Cybernetics, Volume: 9, Issue:
442
+ 10, pp. 617 - 621, Oct. 1979.
443
+ http://ieeexplore.ieee.org/abstract/document/4310090/
444
+
445
+ Examples
446
+ --------
447
+ >>> from sklearn.metrics.pairwise import nan_euclidean_distances
448
+ >>> nan = float("NaN")
449
+ >>> X = [[0, 1], [1, nan]]
450
+ >>> nan_euclidean_distances(X, X) # distance between rows of X
451
+ array([[0. , 1.41421356],
452
+ [1.41421356, 0. ]])
453
+
454
+ >>> # get distance to origin
455
+ >>> nan_euclidean_distances(X, [[0, 0]])
456
+ array([[1. ],
457
+ [1.41421356]])
458
+ """
459
+
460
+ force_all_finite = "allow-nan" if is_scalar_nan(missing_values) else True
461
+ X, Y = check_pairwise_arrays(
462
+ X, Y, accept_sparse=False, force_all_finite=force_all_finite, copy=copy
463
+ )
464
+ # Get missing mask for X
465
+ missing_X = _get_mask(X, missing_values)
466
+
467
+ # Get missing mask for Y
468
+ missing_Y = missing_X if Y is X else _get_mask(Y, missing_values)
469
+
470
+ # set missing values to zero
471
+ X[missing_X] = 0
472
+ Y[missing_Y] = 0
473
+
474
+ distances = euclidean_distances(X, Y, squared=True)
475
+
476
+ # Adjust distances for missing values
477
+ XX = X * X
478
+ YY = Y * Y
479
+ distances -= np.dot(XX, missing_Y.T)
480
+ distances -= np.dot(missing_X, YY.T)
481
+
482
+ np.clip(distances, 0, None, out=distances)
483
+
484
+ if X is Y:
485
+ # Ensure that distances between vectors and themselves are set to 0.0.
486
+ # This may not be the case due to floating point rounding errors.
487
+ np.fill_diagonal(distances, 0.0)
488
+
489
+ present_X = 1 - missing_X
490
+ present_Y = present_X if Y is X else ~missing_Y
491
+ present_count = np.dot(present_X, present_Y.T)
492
+ distances[present_count == 0] = np.nan
493
+ # avoid divide by zero
494
+ np.maximum(1, present_count, out=present_count)
495
+ distances /= present_count
496
+ distances *= X.shape[1]
497
+
498
+ if not squared:
499
+ np.sqrt(distances, out=distances)
500
+
501
+ return distances
502
+
503
+
504
+ def _euclidean_distances_upcast(X, XX=None, Y=None, YY=None, batch_size=None):
505
+ """Euclidean distances between X and Y.
506
+
507
+ Assumes X and Y have float32 dtype.
508
+ Assumes XX and YY have float64 dtype or are None.
509
+
510
+ X and Y are upcast to float64 by chunks, which size is chosen to limit
511
+ memory increase by approximately 10% (at least 10MiB).
512
+ """
513
+ n_samples_X = X.shape[0]
514
+ n_samples_Y = Y.shape[0]
515
+ n_features = X.shape[1]
516
+
517
+ distances = np.empty((n_samples_X, n_samples_Y), dtype=np.float32)
518
+
519
+ if batch_size is None:
520
+ x_density = X.nnz / np.prod(X.shape) if issparse(X) else 1
521
+ y_density = Y.nnz / np.prod(Y.shape) if issparse(Y) else 1
522
+
523
+ # Allow 10% more memory than X, Y and the distance matrix take (at
524
+ # least 10MiB)
525
+ maxmem = max(
526
+ (
527
+ (x_density * n_samples_X + y_density * n_samples_Y) * n_features
528
+ + (x_density * n_samples_X * y_density * n_samples_Y)
529
+ )
530
+ / 10,
531
+ 10 * 2**17,
532
+ )
533
+
534
+ # The increase amount of memory in 8-byte blocks is:
535
+ # - x_density * batch_size * n_features (copy of chunk of X)
536
+ # - y_density * batch_size * n_features (copy of chunk of Y)
537
+ # - batch_size * batch_size (chunk of distance matrix)
538
+ # Hence x² + (xd+yd)kx = M, where x=batch_size, k=n_features, M=maxmem
539
+ # xd=x_density and yd=y_density
540
+ tmp = (x_density + y_density) * n_features
541
+ batch_size = (-tmp + np.sqrt(tmp**2 + 4 * maxmem)) / 2
542
+ batch_size = max(int(batch_size), 1)
543
+
544
+ x_batches = gen_batches(n_samples_X, batch_size)
545
+
546
+ for i, x_slice in enumerate(x_batches):
547
+ X_chunk = X[x_slice].astype(np.float64)
548
+ if XX is None:
549
+ XX_chunk = row_norms(X_chunk, squared=True)[:, np.newaxis]
550
+ else:
551
+ XX_chunk = XX[x_slice]
552
+
553
+ y_batches = gen_batches(n_samples_Y, batch_size)
554
+
555
+ for j, y_slice in enumerate(y_batches):
556
+ if X is Y and j < i:
557
+ # when X is Y the distance matrix is symmetric so we only need
558
+ # to compute half of it.
559
+ d = distances[y_slice, x_slice].T
560
+
561
+ else:
562
+ Y_chunk = Y[y_slice].astype(np.float64)
563
+ if YY is None:
564
+ YY_chunk = row_norms(Y_chunk, squared=True)[np.newaxis, :]
565
+ else:
566
+ YY_chunk = YY[:, y_slice]
567
+
568
+ d = -2 * safe_sparse_dot(X_chunk, Y_chunk.T, dense_output=True)
569
+ d += XX_chunk
570
+ d += YY_chunk
571
+
572
+ distances[x_slice, y_slice] = d.astype(np.float32, copy=False)
573
+
574
+ return distances
575
+
576
+
577
+ def _argmin_min_reduce(dist, start):
578
+ # `start` is specified in the signature but not used. This is because the higher
579
+ # order `pairwise_distances_chunked` function needs reduction functions that are
580
+ # passed as argument to have a two arguments signature.
581
+ indices = dist.argmin(axis=1)
582
+ values = dist[np.arange(dist.shape[0]), indices]
583
+ return indices, values
584
+
585
+
586
+ def _argmin_reduce(dist, start):
587
+ # `start` is specified in the signature but not used. This is because the higher
588
+ # order `pairwise_distances_chunked` function needs reduction functions that are
589
+ # passed as argument to have a two arguments signature.
590
+ return dist.argmin(axis=1)
591
+
592
+
593
+ def pairwise_distances_argmin_min(
594
+ X, Y, *, axis=1, metric="euclidean", metric_kwargs=None
595
+ ):
596
+ """Compute minimum distances between one point and a set of points.
597
+
598
+ This function computes for each row in X, the index of the row of Y which
599
+ is closest (according to the specified distance). The minimal distances are
600
+ also returned.
601
+
602
+ This is mostly equivalent to calling:
603
+
604
+ (pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis),
605
+ pairwise_distances(X, Y=Y, metric=metric).min(axis=axis))
606
+
607
+ but uses much less memory, and is faster for large arrays.
608
+
609
+ Parameters
610
+ ----------
611
+ X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
612
+ Array containing points.
613
+
614
+ Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)
615
+ Array containing points.
616
+
617
+ axis : int, default=1
618
+ Axis along which the argmin and distances are to be computed.
619
+
620
+ metric : str or callable, default='euclidean'
621
+ Metric to use for distance computation. Any metric from scikit-learn
622
+ or scipy.spatial.distance can be used.
623
+
624
+ If metric is a callable function, it is called on each
625
+ pair of instances (rows) and the resulting value recorded. The callable
626
+ should take two arrays as input and return one value indicating the
627
+ distance between them. This works for Scipy's metrics, but is less
628
+ efficient than passing the metric name as a string.
629
+
630
+ Distance matrices are not supported.
631
+
632
+ Valid values for metric are:
633
+
634
+ - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
635
+ 'manhattan']
636
+
637
+ - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
638
+ 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
639
+ 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao',
640
+ 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean',
641
+ 'yule']
642
+
643
+ See the documentation for scipy.spatial.distance for details on these
644
+ metrics.
645
+
646
+ metric_kwargs : dict, default=None
647
+ Keyword arguments to pass to specified metric function.
648
+
649
+ Returns
650
+ -------
651
+ argmin : ndarray
652
+ Y[argmin[i], :] is the row in Y that is closest to X[i, :].
653
+
654
+ distances : ndarray
655
+ The array of minimum distances. `distances[i]` is the distance between
656
+ the i-th row in X and the argmin[i]-th row in Y.
657
+
658
+ See Also
659
+ --------
660
+ pairwise_distances : Distances between every pair of samples of X and Y.
661
+ pairwise_distances_argmin : Same as `pairwise_distances_argmin_min` but only
662
+ returns the argmins.
663
+ """
664
+ X, Y = check_pairwise_arrays(X, Y)
665
+
666
+ if axis == 0:
667
+ X, Y = Y, X
668
+
669
+ if metric_kwargs is None:
670
+ metric_kwargs = {}
671
+
672
+ if ArgKmin.is_usable_for(X, Y, metric):
673
+ # This is an adaptor for one "sqeuclidean" specification.
674
+ # For this backend, we can directly use "sqeuclidean".
675
+ if metric_kwargs.get("squared", False) and metric == "euclidean":
676
+ metric = "sqeuclidean"
677
+ metric_kwargs = {}
678
+
679
+ values, indices = ArgKmin.compute(
680
+ X=X,
681
+ Y=Y,
682
+ k=1,
683
+ metric=metric,
684
+ metric_kwargs=metric_kwargs,
685
+ strategy="auto",
686
+ return_distance=True,
687
+ )
688
+ values = values.flatten()
689
+ indices = indices.flatten()
690
+ else:
691
+ # Joblib-based backend, which is used when user-defined callable
692
+ # are passed for metric.
693
+
694
+ # This won't be used in the future once PairwiseDistancesReductions support:
695
+ # - DistanceMetrics which work on supposedly binary data
696
+ # - CSR-dense and dense-CSR case if 'euclidean' in metric.
697
+
698
+ # Turn off check for finiteness because this is costly and because arrays
699
+ # have already been validated.
700
+ with config_context(assume_finite=True):
701
+ indices, values = zip(
702
+ *pairwise_distances_chunked(
703
+ X, Y, reduce_func=_argmin_min_reduce, metric=metric, **metric_kwargs
704
+ )
705
+ )
706
+ indices = np.concatenate(indices)
707
+ values = np.concatenate(values)
708
+
709
+ return indices, values
710
+
711
+
712
+ def pairwise_distances_argmin(X, Y, *, axis=1, metric="euclidean", metric_kwargs=None):
713
+ """Compute minimum distances between one point and a set of points.
714
+
715
+ This function computes for each row in X, the index of the row of Y which
716
+ is closest (according to the specified distance).
717
+
718
+ This is mostly equivalent to calling:
719
+
720
+ pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis)
721
+
722
+ but uses much less memory, and is faster for large arrays.
723
+
724
+ This function works with dense 2D arrays only.
725
+
726
+ Parameters
727
+ ----------
728
+ X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
729
+ Array containing points.
730
+
731
+ Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)
732
+ Arrays containing points.
733
+
734
+ axis : int, default=1
735
+ Axis along which the argmin and distances are to be computed.
736
+
737
+ metric : str or callable, default="euclidean"
738
+ Metric to use for distance computation. Any metric from scikit-learn
739
+ or scipy.spatial.distance can be used.
740
+
741
+ If metric is a callable function, it is called on each
742
+ pair of instances (rows) and the resulting value recorded. The callable
743
+ should take two arrays as input and return one value indicating the
744
+ distance between them. This works for Scipy's metrics, but is less
745
+ efficient than passing the metric name as a string.
746
+
747
+ Distance matrices are not supported.
748
+
749
+ Valid values for metric are:
750
+
751
+ - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
752
+ 'manhattan']
753
+
754
+ - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
755
+ 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
756
+ 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao',
757
+ 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean',
758
+ 'yule']
759
+
760
+ See the documentation for scipy.spatial.distance for details on these
761
+ metrics.
762
+
763
+ metric_kwargs : dict, default=None
764
+ Keyword arguments to pass to specified metric function.
765
+
766
+ Returns
767
+ -------
768
+ argmin : numpy.ndarray
769
+ Y[argmin[i], :] is the row in Y that is closest to X[i, :].
770
+
771
+ See Also
772
+ --------
773
+ pairwise_distances : Distances between every pair of samples of X and Y.
774
+ pairwise_distances_argmin_min : Same as `pairwise_distances_argmin` but also
775
+ returns the distances.
776
+ """
777
+ if metric_kwargs is None:
778
+ metric_kwargs = {}
779
+
780
+ X, Y = check_pairwise_arrays(X, Y)
781
+
782
+ if axis == 0:
783
+ X, Y = Y, X
784
+
785
+ if metric_kwargs is None:
786
+ metric_kwargs = {}
787
+
788
+ if ArgKmin.is_usable_for(X, Y, metric):
789
+ # This is an adaptor for one "sqeuclidean" specification.
790
+ # For this backend, we can directly use "sqeuclidean".
791
+ if metric_kwargs.get("squared", False) and metric == "euclidean":
792
+ metric = "sqeuclidean"
793
+ metric_kwargs = {}
794
+
795
+ indices = ArgKmin.compute(
796
+ X=X,
797
+ Y=Y,
798
+ k=1,
799
+ metric=metric,
800
+ metric_kwargs=metric_kwargs,
801
+ strategy="auto",
802
+ return_distance=False,
803
+ )
804
+ indices = indices.flatten()
805
+ else:
806
+ # Joblib-based backend, which is used when user-defined callable
807
+ # are passed for metric.
808
+
809
+ # This won't be used in the future once PairwiseDistancesReductions support:
810
+ # - DistanceMetrics which work on supposedly binary data
811
+ # - CSR-dense and dense-CSR case if 'euclidean' in metric.
812
+
813
+ # Turn off check for finiteness because this is costly and because arrays
814
+ # have already been validated.
815
+ with config_context(assume_finite=True):
816
+ indices = np.concatenate(
817
+ list(
818
+ # This returns a np.ndarray generator whose arrays we need
819
+ # to flatten into one.
820
+ pairwise_distances_chunked(
821
+ X, Y, reduce_func=_argmin_reduce, metric=metric, **metric_kwargs
822
+ )
823
+ )
824
+ )
825
+
826
+ return indices
827
+
828
+
829
+ def haversine_distances(X, Y=None):
830
+ """Compute the Haversine distance between samples in X and Y.
831
+
832
+ The Haversine (or great circle) distance is the angular distance between
833
+ two points on the surface of a sphere. The first coordinate of each point
834
+ is assumed to be the latitude, the second is the longitude, given
835
+ in radians. The dimension of the data must be 2.
836
+
837
+ .. math::
838
+ D(x, y) = 2\\arcsin[\\sqrt{\\sin^2((x1 - y1) / 2)
839
+ + \\cos(x1)\\cos(y1)\\sin^2((x2 - y2) / 2)}]
840
+
841
+ Parameters
842
+ ----------
843
+ X : array-like of shape (n_samples_X, 2)
844
+ A feature array.
845
+
846
+ Y : array-like of shape (n_samples_Y, 2), default=None
847
+ An optional second feature array. If `None`, uses `Y=X`.
848
+
849
+ Returns
850
+ -------
851
+ distance : ndarray of shape (n_samples_X, n_samples_Y)
852
+ The distance matrix.
853
+
854
+ Notes
855
+ -----
856
+ As the Earth is nearly spherical, the haversine formula provides a good
857
+ approximation of the distance between two points of the Earth surface, with
858
+ a less than 1% error on average.
859
+
860
+ Examples
861
+ --------
862
+ We want to calculate the distance between the Ezeiza Airport
863
+ (Buenos Aires, Argentina) and the Charles de Gaulle Airport (Paris,
864
+ France).
865
+
866
+ >>> from sklearn.metrics.pairwise import haversine_distances
867
+ >>> from math import radians
868
+ >>> bsas = [-34.83333, -58.5166646]
869
+ >>> paris = [49.0083899664, 2.53844117956]
870
+ >>> bsas_in_radians = [radians(_) for _ in bsas]
871
+ >>> paris_in_radians = [radians(_) for _ in paris]
872
+ >>> result = haversine_distances([bsas_in_radians, paris_in_radians])
873
+ >>> result * 6371000/1000 # multiply by Earth radius to get kilometers
874
+ array([[ 0. , 11099.54035582],
875
+ [11099.54035582, 0. ]])
876
+ """
877
+ from ..metrics import DistanceMetric
878
+
879
+ return DistanceMetric.get_metric("haversine").pairwise(X, Y)
880
+
881
+
882
+ def manhattan_distances(X, Y=None, *, sum_over_features="deprecated"):
883
+ """Compute the L1 distances between the vectors in X and Y.
884
+
885
+ With sum_over_features equal to False it returns the componentwise
886
+ distances.
887
+
888
+ Read more in the :ref:`User Guide <metrics>`.
889
+
890
+ Parameters
891
+ ----------
892
+ X : array-like of shape (n_samples_X, n_features)
893
+ An array where each row is a sample and each column is a feature.
894
+
895
+ Y : array-like of shape (n_samples_Y, n_features), default=None
896
+ An array where each row is a sample and each column is a feature.
897
+ If `None`, method uses `Y=X`.
898
+
899
+ sum_over_features : bool, default=True
900
+ If True the function returns the pairwise distance matrix
901
+ else it returns the componentwise L1 pairwise-distances.
902
+ Not supported for sparse matrix inputs.
903
+
904
+ .. deprecated:: 1.2
905
+ ``sum_over_features`` was deprecated in version 1.2 and will be removed in
906
+ 1.4.
907
+
908
+ Returns
909
+ -------
910
+ D : ndarray of shape (n_samples_X * n_samples_Y, n_features) or \
911
+ (n_samples_X, n_samples_Y)
912
+ If sum_over_features is False shape is
913
+ (n_samples_X * n_samples_Y, n_features) and D contains the
914
+ componentwise L1 pairwise-distances (ie. absolute difference),
915
+ else shape is (n_samples_X, n_samples_Y) and D contains
916
+ the pairwise L1 distances.
917
+
918
+ Notes
919
+ -----
920
+ When X and/or Y are CSR sparse matrices and they are not already
921
+ in canonical format, this function modifies them in-place to
922
+ make them canonical.
923
+
924
+ Examples
925
+ --------
926
+ >>> from sklearn.metrics.pairwise import manhattan_distances
927
+ >>> manhattan_distances([[3]], [[3]])
928
+ array([[0.]])
929
+ >>> manhattan_distances([[3]], [[2]])
930
+ array([[1.]])
931
+ >>> manhattan_distances([[2]], [[3]])
932
+ array([[1.]])
933
+ >>> manhattan_distances([[1, 2], [3, 4]],\
934
+ [[1, 2], [0, 3]])
935
+ array([[0., 2.],
936
+ [4., 4.]])
937
+ """
938
+ # TODO(1.4): remove sum_over_features
939
+ if sum_over_features != "deprecated":
940
+ warnings.warn(
941
+ "`sum_over_features` is deprecated in version 1.2 and will be"
942
+ " removed in version 1.4.",
943
+ FutureWarning,
944
+ )
945
+ else:
946
+ sum_over_features = True
947
+
948
+ X, Y = check_pairwise_arrays(X, Y)
949
+
950
+ if issparse(X) or issparse(Y):
951
+ if not sum_over_features:
952
+ raise TypeError(
953
+ "sum_over_features=%r not supported for sparse matrices"
954
+ % sum_over_features
955
+ )
956
+
957
+ X = csr_matrix(X, copy=False)
958
+ Y = csr_matrix(Y, copy=False)
959
+ X.sum_duplicates() # this also sorts indices in-place
960
+ Y.sum_duplicates()
961
+ D = np.zeros((X.shape[0], Y.shape[0]))
962
+ _sparse_manhattan(X.data, X.indices, X.indptr, Y.data, Y.indices, Y.indptr, D)
963
+ return D
964
+
965
+ if sum_over_features:
966
+ return distance.cdist(X, Y, "cityblock")
967
+
968
+ D = X[:, np.newaxis, :] - Y[np.newaxis, :, :]
969
+ D = np.abs(D, D)
970
+ return D.reshape((-1, X.shape[1]))
971
+
972
+
973
+ def cosine_distances(X, Y=None):
974
+ """Compute cosine distance between samples in X and Y.
975
+
976
+ Cosine distance is defined as 1.0 minus the cosine similarity.
977
+
978
+ Read more in the :ref:`User Guide <metrics>`.
979
+
980
+ Parameters
981
+ ----------
982
+ X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
983
+ Matrix `X`.
984
+
985
+ Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), \
986
+ default=None
987
+ Matrix `Y`.
988
+
989
+ Returns
990
+ -------
991
+ distance matrix : ndarray of shape (n_samples_X, n_samples_Y)
992
+ Returns the cosine distance between samples in X and Y.
993
+
994
+ See Also
995
+ --------
996
+ cosine_similarity : Compute cosine similarity between samples in X and Y.
997
+ scipy.spatial.distance.cosine : Dense matrices only.
998
+ """
999
+ # 1.0 - cosine_similarity(X, Y) without copy
1000
+ S = cosine_similarity(X, Y)
1001
+ S *= -1
1002
+ S += 1
1003
+ np.clip(S, 0, 2, out=S)
1004
+ if X is Y or Y is None:
1005
+ # Ensure that distances between vectors and themselves are set to 0.0.
1006
+ # This may not be the case due to floating point rounding errors.
1007
+ S[np.diag_indices_from(S)] = 0.0
1008
+ return S
1009
+
1010
+
1011
+ # Paired distances
1012
+ def paired_euclidean_distances(X, Y):
1013
+ """Compute the paired euclidean distances between X and Y.
1014
+
1015
+ Read more in the :ref:`User Guide <metrics>`.
1016
+
1017
+ Parameters
1018
+ ----------
1019
+ X : array-like of shape (n_samples, n_features)
1020
+ Input array/matrix X.
1021
+
1022
+ Y : array-like of shape (n_samples, n_features)
1023
+ Input array/matrix Y.
1024
+
1025
+ Returns
1026
+ -------
1027
+ distances : ndarray of shape (n_samples,)
1028
+ Output array/matrix containing the calculated paired euclidean
1029
+ distances.
1030
+ """
1031
+ X, Y = check_paired_arrays(X, Y)
1032
+ return row_norms(X - Y)
1033
+
1034
+
1035
+ def paired_manhattan_distances(X, Y):
1036
+ """Compute the paired L1 distances between X and Y.
1037
+
1038
+ Distances are calculated between (X[0], Y[0]), (X[1], Y[1]), ...,
1039
+ (X[n_samples], Y[n_samples]).
1040
+
1041
+ Read more in the :ref:`User Guide <metrics>`.
1042
+
1043
+ Parameters
1044
+ ----------
1045
+ X : array-like of shape (n_samples, n_features)
1046
+ An array-like where each row is a sample and each column is a feature.
1047
+
1048
+ Y : array-like of shape (n_samples, n_features)
1049
+ An array-like where each row is a sample and each column is a feature.
1050
+
1051
+ Returns
1052
+ -------
1053
+ distances : ndarray of shape (n_samples,)
1054
+ L1 paired distances between the row vectors of `X`
1055
+ and the row vectors of `Y`.
1056
+
1057
+ Examples
1058
+ --------
1059
+ >>> from sklearn.metrics.pairwise import paired_manhattan_distances
1060
+ >>> import numpy as np
1061
+ >>> X = np.array([[1, 1, 0], [0, 1, 0], [0, 0, 1]])
1062
+ >>> Y = np.array([[0, 1, 0], [0, 0, 1], [0, 0, 0]])
1063
+ >>> paired_manhattan_distances(X, Y)
1064
+ array([1., 2., 1.])
1065
+ """
1066
+ X, Y = check_paired_arrays(X, Y)
1067
+ diff = X - Y
1068
+ if issparse(diff):
1069
+ diff.data = np.abs(diff.data)
1070
+ return np.squeeze(np.array(diff.sum(axis=1)))
1071
+ else:
1072
+ return np.abs(diff).sum(axis=-1)
1073
+
1074
+
1075
+ def paired_cosine_distances(X, Y):
1076
+ """
1077
+ Compute the paired cosine distances between X and Y.
1078
+
1079
+ Read more in the :ref:`User Guide <metrics>`.
1080
+
1081
+ Parameters
1082
+ ----------
1083
+ X : array-like of shape (n_samples, n_features)
1084
+ An array where each row is a sample and each column is a feature.
1085
+
1086
+ Y : array-like of shape (n_samples, n_features)
1087
+ An array where each row is a sample and each column is a feature.
1088
+
1089
+ Returns
1090
+ -------
1091
+ distances : ndarray of shape (n_samples,)
1092
+ Returns the distances between the row vectors of `X`
1093
+ and the row vectors of `Y`, where `distances[i]` is the
1094
+ distance between `X[i]` and `Y[i]`.
1095
+
1096
+ Notes
1097
+ -----
1098
+ The cosine distance is equivalent to the half the squared
1099
+ euclidean distance if each sample is normalized to unit norm.
1100
+ """
1101
+ X, Y = check_paired_arrays(X, Y)
1102
+ return 0.5 * row_norms(normalize(X) - normalize(Y), squared=True)
1103
+
1104
+
1105
+ PAIRED_DISTANCES = {
1106
+ "cosine": paired_cosine_distances,
1107
+ "euclidean": paired_euclidean_distances,
1108
+ "l2": paired_euclidean_distances,
1109
+ "l1": paired_manhattan_distances,
1110
+ "manhattan": paired_manhattan_distances,
1111
+ "cityblock": paired_manhattan_distances,
1112
+ }
1113
+
1114
+
1115
+ def paired_distances(X, Y, *, metric="euclidean", **kwds):
1116
+ """
1117
+ Compute the paired distances between X and Y.
1118
+
1119
+ Compute the distances between (X[0], Y[0]), (X[1], Y[1]), etc...
1120
+
1121
+ Read more in the :ref:`User Guide <metrics>`.
1122
+
1123
+ Parameters
1124
+ ----------
1125
+ X : ndarray of shape (n_samples, n_features)
1126
+ Array 1 for distance computation.
1127
+
1128
+ Y : ndarray of shape (n_samples, n_features)
1129
+ Array 2 for distance computation.
1130
+
1131
+ metric : str or callable, default="euclidean"
1132
+ The metric to use when calculating distance between instances in a
1133
+ feature array. If metric is a string, it must be one of the options
1134
+ specified in PAIRED_DISTANCES, including "euclidean",
1135
+ "manhattan", or "cosine".
1136
+ Alternatively, if metric is a callable function, it is called on each
1137
+ pair of instances (rows) and the resulting value recorded. The callable
1138
+ should take two arrays from `X` as input and return a value indicating
1139
+ the distance between them.
1140
+
1141
+ **kwds : dict
1142
+ Unused parameters.
1143
+
1144
+ Returns
1145
+ -------
1146
+ distances : ndarray of shape (n_samples,)
1147
+ Returns the distances between the row vectors of `X`
1148
+ and the row vectors of `Y`.
1149
+
1150
+ See Also
1151
+ --------
1152
+ pairwise_distances : Computes the distance between every pair of samples.
1153
+
1154
+ Examples
1155
+ --------
1156
+ >>> from sklearn.metrics.pairwise import paired_distances
1157
+ >>> X = [[0, 1], [1, 1]]
1158
+ >>> Y = [[0, 1], [2, 1]]
1159
+ >>> paired_distances(X, Y)
1160
+ array([0., 1.])
1161
+ """
1162
+
1163
+ if metric in PAIRED_DISTANCES:
1164
+ func = PAIRED_DISTANCES[metric]
1165
+ return func(X, Y)
1166
+ elif callable(metric):
1167
+ # Check the matrix first (it is usually done by the metric)
1168
+ X, Y = check_paired_arrays(X, Y)
1169
+ distances = np.zeros(len(X))
1170
+ for i in range(len(X)):
1171
+ distances[i] = metric(X[i], Y[i])
1172
+ return distances
1173
+ else:
1174
+ raise ValueError("Unknown distance %s" % metric)
1175
+
1176
+
1177
+ # Kernels
1178
+ def linear_kernel(X, Y=None, dense_output=True):
1179
+ """
1180
+ Compute the linear kernel between X and Y.
1181
+
1182
+ Read more in the :ref:`User Guide <linear_kernel>`.
1183
+
1184
+ Parameters
1185
+ ----------
1186
+ X : ndarray of shape (n_samples_X, n_features)
1187
+ A feature array.
1188
+
1189
+ Y : ndarray of shape (n_samples_Y, n_features), default=None
1190
+ An optional second feature array. If `None`, uses `Y=X`.
1191
+
1192
+ dense_output : bool, default=True
1193
+ Whether to return dense output even when the input is sparse. If
1194
+ ``False``, the output is sparse if both input arrays are sparse.
1195
+
1196
+ .. versionadded:: 0.20
1197
+
1198
+ Returns
1199
+ -------
1200
+ Gram matrix : ndarray of shape (n_samples_X, n_samples_Y)
1201
+ The Gram matrix of the linear kernel, i.e. `X @ Y.T`.
1202
+ """
1203
+ X, Y = check_pairwise_arrays(X, Y)
1204
+ return safe_sparse_dot(X, Y.T, dense_output=dense_output)
1205
+
1206
+
1207
+ def polynomial_kernel(X, Y=None, degree=3, gamma=None, coef0=1):
1208
+ """
1209
+ Compute the polynomial kernel between X and Y.
1210
+
1211
+ :math:`K(X, Y) = (gamma <X, Y> + coef0)^{degree}`
1212
+
1213
+ Read more in the :ref:`User Guide <polynomial_kernel>`.
1214
+
1215
+ Parameters
1216
+ ----------
1217
+ X : ndarray of shape (n_samples_X, n_features)
1218
+ A feature array.
1219
+
1220
+ Y : ndarray of shape (n_samples_Y, n_features), default=None
1221
+ An optional second feature array. If `None`, uses `Y=X`.
1222
+
1223
+ degree : int, default=3
1224
+ Kernel degree.
1225
+
1226
+ gamma : float, default=None
1227
+ Coefficient of the vector inner product. If None, defaults to 1.0 / n_features.
1228
+
1229
+ coef0 : float, default=1
1230
+ Constant offset added to scaled inner product.
1231
+
1232
+ Returns
1233
+ -------
1234
+ Gram matrix : ndarray of shape (n_samples_X, n_samples_Y)
1235
+ The polynomial kernel.
1236
+ """
1237
+ X, Y = check_pairwise_arrays(X, Y)
1238
+ if gamma is None:
1239
+ gamma = 1.0 / X.shape[1]
1240
+
1241
+ K = safe_sparse_dot(X, Y.T, dense_output=True)
1242
+ K *= gamma
1243
+ K += coef0
1244
+ K **= degree
1245
+ return K
1246
+
1247
+
1248
+ def sigmoid_kernel(X, Y=None, gamma=None, coef0=1):
1249
+ """Compute the sigmoid kernel between X and Y.
1250
+
1251
+ K(X, Y) = tanh(gamma <X, Y> + coef0)
1252
+
1253
+ Read more in the :ref:`User Guide <sigmoid_kernel>`.
1254
+
1255
+ Parameters
1256
+ ----------
1257
+ X : ndarray of shape (n_samples_X, n_features)
1258
+ A feature array.
1259
+
1260
+ Y : ndarray of shape (n_samples_Y, n_features), default=None
1261
+ An optional second feature array. If `None`, uses `Y=X`.
1262
+
1263
+ gamma : float, default=None
1264
+ Coefficient of the vector inner product. If None, defaults to 1.0 / n_features.
1265
+
1266
+ coef0 : float, default=1
1267
+ Constant offset added to scaled inner product.
1268
+
1269
+ Returns
1270
+ -------
1271
+ Gram matrix : ndarray of shape (n_samples_X, n_samples_Y)
1272
+ Sigmoid kernel between two arrays.
1273
+ """
1274
+ X, Y = check_pairwise_arrays(X, Y)
1275
+ if gamma is None:
1276
+ gamma = 1.0 / X.shape[1]
1277
+
1278
+ K = safe_sparse_dot(X, Y.T, dense_output=True)
1279
+ K *= gamma
1280
+ K += coef0
1281
+ np.tanh(K, K) # compute tanh in-place
1282
+ return K
1283
+
1284
+
1285
+ def rbf_kernel(X, Y=None, gamma=None):
1286
+ """Compute the rbf (gaussian) kernel between X and Y.
1287
+
1288
+ K(x, y) = exp(-gamma ||x-y||^2)
1289
+
1290
+ for each pair of rows x in X and y in Y.
1291
+
1292
+ Read more in the :ref:`User Guide <rbf_kernel>`.
1293
+
1294
+ Parameters
1295
+ ----------
1296
+ X : ndarray of shape (n_samples_X, n_features)
1297
+ A feature array.
1298
+
1299
+ Y : ndarray of shape (n_samples_Y, n_features), default=None
1300
+ An optional second feature array. If `None`, uses `Y=X`.
1301
+
1302
+ gamma : float, default=None
1303
+ If None, defaults to 1.0 / n_features.
1304
+
1305
+ Returns
1306
+ -------
1307
+ kernel_matrix : ndarray of shape (n_samples_X, n_samples_Y)
1308
+ The RBF kernel.
1309
+ """
1310
+ X, Y = check_pairwise_arrays(X, Y)
1311
+ if gamma is None:
1312
+ gamma = 1.0 / X.shape[1]
1313
+
1314
+ K = euclidean_distances(X, Y, squared=True)
1315
+ K *= -gamma
1316
+ np.exp(K, K) # exponentiate K in-place
1317
+ return K
1318
+
1319
+
1320
+ def laplacian_kernel(X, Y=None, gamma=None):
1321
+ """Compute the laplacian kernel between X and Y.
1322
+
1323
+ The laplacian kernel is defined as::
1324
+
1325
+ K(x, y) = exp(-gamma ||x-y||_1)
1326
+
1327
+ for each pair of rows x in X and y in Y.
1328
+ Read more in the :ref:`User Guide <laplacian_kernel>`.
1329
+
1330
+ .. versionadded:: 0.17
1331
+
1332
+ Parameters
1333
+ ----------
1334
+ X : ndarray of shape (n_samples_X, n_features)
1335
+ A feature array.
1336
+
1337
+ Y : ndarray of shape (n_samples_Y, n_features), default=None
1338
+ An optional second feature array. If `None`, uses `Y=X`.
1339
+
1340
+ gamma : float, default=None
1341
+ If None, defaults to 1.0 / n_features.
1342
+
1343
+ Returns
1344
+ -------
1345
+ kernel_matrix : ndarray of shape (n_samples_X, n_samples_Y)
1346
+ The kernel matrix.
1347
+ """
1348
+ X, Y = check_pairwise_arrays(X, Y)
1349
+ if gamma is None:
1350
+ gamma = 1.0 / X.shape[1]
1351
+
1352
+ K = -gamma * manhattan_distances(X, Y)
1353
+ np.exp(K, K) # exponentiate K in-place
1354
+ return K
1355
+
1356
+
1357
+ def cosine_similarity(X, Y=None, dense_output=True):
1358
+ """Compute cosine similarity between samples in X and Y.
1359
+
1360
+ Cosine similarity, or the cosine kernel, computes similarity as the
1361
+ normalized dot product of X and Y:
1362
+
1363
+ K(X, Y) = <X, Y> / (||X||*||Y||)
1364
+
1365
+ On L2-normalized data, this function is equivalent to linear_kernel.
1366
+
1367
+ Read more in the :ref:`User Guide <cosine_similarity>`.
1368
+
1369
+ Parameters
1370
+ ----------
1371
+ X : {ndarray, sparse matrix} of shape (n_samples_X, n_features)
1372
+ Input data.
1373
+
1374
+ Y : {ndarray, sparse matrix} of shape (n_samples_Y, n_features), \
1375
+ default=None
1376
+ Input data. If ``None``, the output will be the pairwise
1377
+ similarities between all samples in ``X``.
1378
+
1379
+ dense_output : bool, default=True
1380
+ Whether to return dense output even when the input is sparse. If
1381
+ ``False``, the output is sparse if both input arrays are sparse.
1382
+
1383
+ .. versionadded:: 0.17
1384
+ parameter ``dense_output`` for dense output.
1385
+
1386
+ Returns
1387
+ -------
1388
+ kernel matrix : ndarray of shape (n_samples_X, n_samples_Y)
1389
+ Returns the cosine similarity between samples in X and Y.
1390
+ """
1391
+ # to avoid recursive import
1392
+
1393
+ X, Y = check_pairwise_arrays(X, Y)
1394
+
1395
+ X_normalized = normalize(X, copy=True)
1396
+ if X is Y:
1397
+ Y_normalized = X_normalized
1398
+ else:
1399
+ Y_normalized = normalize(Y, copy=True)
1400
+
1401
+ K = safe_sparse_dot(X_normalized, Y_normalized.T, dense_output=dense_output)
1402
+
1403
+ return K
1404
+
1405
+
1406
+ def additive_chi2_kernel(X, Y=None):
1407
+ """Compute the additive chi-squared kernel between observations in X and Y.
1408
+
1409
+ The chi-squared kernel is computed between each pair of rows in X and Y. X
1410
+ and Y have to be non-negative. This kernel is most commonly applied to
1411
+ histograms.
1412
+
1413
+ The chi-squared kernel is given by::
1414
+
1415
+ k(x, y) = -Sum [(x - y)^2 / (x + y)]
1416
+
1417
+ It can be interpreted as a weighted difference per entry.
1418
+
1419
+ Read more in the :ref:`User Guide <chi2_kernel>`.
1420
+
1421
+ Parameters
1422
+ ----------
1423
+ X : array-like of shape (n_samples_X, n_features)
1424
+ A feature array.
1425
+
1426
+ Y : ndarray of shape (n_samples_Y, n_features), default=None
1427
+ An optional second feature array. If `None`, uses `Y=X`.
1428
+
1429
+ Returns
1430
+ -------
1431
+ kernel_matrix : ndarray of shape (n_samples_X, n_samples_Y)
1432
+ The kernel matrix.
1433
+
1434
+ See Also
1435
+ --------
1436
+ chi2_kernel : The exponentiated version of the kernel, which is usually
1437
+ preferable.
1438
+ sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation
1439
+ to this kernel.
1440
+
1441
+ Notes
1442
+ -----
1443
+ As the negative of a distance, this kernel is only conditionally positive
1444
+ definite.
1445
+
1446
+ References
1447
+ ----------
1448
+ * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C.
1449
+ Local features and kernels for classification of texture and object
1450
+ categories: A comprehensive study
1451
+ International Journal of Computer Vision 2007
1452
+ https://hal.archives-ouvertes.fr/hal-00171412/document
1453
+ """
1454
+ if issparse(X) or issparse(Y):
1455
+ raise ValueError("additive_chi2 does not support sparse matrices.")
1456
+ X, Y = check_pairwise_arrays(X, Y)
1457
+ if (X < 0).any():
1458
+ raise ValueError("X contains negative values.")
1459
+ if Y is not X and (Y < 0).any():
1460
+ raise ValueError("Y contains negative values.")
1461
+
1462
+ result = np.zeros((X.shape[0], Y.shape[0]), dtype=X.dtype)
1463
+ _chi2_kernel_fast(X, Y, result)
1464
+ return result
1465
+
1466
+
1467
+ def chi2_kernel(X, Y=None, gamma=1.0):
1468
+ """Compute the exponential chi-squared kernel between X and Y.
1469
+
1470
+ The chi-squared kernel is computed between each pair of rows in X and Y. X
1471
+ and Y have to be non-negative. This kernel is most commonly applied to
1472
+ histograms.
1473
+
1474
+ The chi-squared kernel is given by::
1475
+
1476
+ k(x, y) = exp(-gamma Sum [(x - y)^2 / (x + y)])
1477
+
1478
+ It can be interpreted as a weighted difference per entry.
1479
+
1480
+ Read more in the :ref:`User Guide <chi2_kernel>`.
1481
+
1482
+ Parameters
1483
+ ----------
1484
+ X : array-like of shape (n_samples_X, n_features)
1485
+ A feature array.
1486
+
1487
+ Y : ndarray of shape (n_samples_Y, n_features), default=None
1488
+ An optional second feature array. If `None`, uses `Y=X`.
1489
+
1490
+ gamma : float, default=1
1491
+ Scaling parameter of the chi2 kernel.
1492
+
1493
+ Returns
1494
+ -------
1495
+ kernel_matrix : ndarray of shape (n_samples_X, n_samples_Y)
1496
+ The kernel matrix.
1497
+
1498
+ See Also
1499
+ --------
1500
+ additive_chi2_kernel : The additive version of this kernel.
1501
+ sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation
1502
+ to the additive version of this kernel.
1503
+
1504
+ References
1505
+ ----------
1506
+ * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C.
1507
+ Local features and kernels for classification of texture and object
1508
+ categories: A comprehensive study
1509
+ International Journal of Computer Vision 2007
1510
+ https://hal.archives-ouvertes.fr/hal-00171412/document
1511
+ """
1512
+ K = additive_chi2_kernel(X, Y)
1513
+ K *= gamma
1514
+ return np.exp(K, K)
1515
+
1516
+
1517
+ # Helper functions - distance
1518
+ PAIRWISE_DISTANCE_FUNCTIONS = {
1519
+ # If updating this dictionary, update the doc in both distance_metrics()
1520
+ # and also in pairwise_distances()!
1521
+ "cityblock": manhattan_distances,
1522
+ "cosine": cosine_distances,
1523
+ "euclidean": euclidean_distances,
1524
+ "haversine": haversine_distances,
1525
+ "l2": euclidean_distances,
1526
+ "l1": manhattan_distances,
1527
+ "manhattan": manhattan_distances,
1528
+ "precomputed": None, # HACK: precomputed is always allowed, never called
1529
+ "nan_euclidean": nan_euclidean_distances,
1530
+ }
1531
+
1532
+
1533
+ def distance_metrics():
1534
+ """Valid metrics for pairwise_distances.
1535
+
1536
+ This function simply returns the valid pairwise distance metrics.
1537
+ It exists to allow for a description of the mapping for
1538
+ each of the valid strings.
1539
+
1540
+ The valid distance metrics, and the function they map to, are:
1541
+
1542
+ =============== ========================================
1543
+ metric Function
1544
+ =============== ========================================
1545
+ 'cityblock' metrics.pairwise.manhattan_distances
1546
+ 'cosine' metrics.pairwise.cosine_distances
1547
+ 'euclidean' metrics.pairwise.euclidean_distances
1548
+ 'haversine' metrics.pairwise.haversine_distances
1549
+ 'l1' metrics.pairwise.manhattan_distances
1550
+ 'l2' metrics.pairwise.euclidean_distances
1551
+ 'manhattan' metrics.pairwise.manhattan_distances
1552
+ 'nan_euclidean' metrics.pairwise.nan_euclidean_distances
1553
+ =============== ========================================
1554
+
1555
+ Read more in the :ref:`User Guide <metrics>`.
1556
+
1557
+ Returns
1558
+ -------
1559
+ distance_metrics : dict
1560
+ Returns valid metrics for pairwise_distances.
1561
+ """
1562
+ return PAIRWISE_DISTANCE_FUNCTIONS
1563
+
1564
+
1565
+ def _dist_wrapper(dist_func, dist_matrix, slice_, *args, **kwargs):
1566
+ """Write in-place to a slice of a distance matrix."""
1567
+ dist_matrix[:, slice_] = dist_func(*args, **kwargs)
1568
+
1569
+
1570
+ def _parallel_pairwise(X, Y, func, n_jobs, **kwds):
1571
+ """Break the pairwise matrix in n_jobs even slices
1572
+ and compute them in parallel."""
1573
+
1574
+ if Y is None:
1575
+ Y = X
1576
+ X, Y, dtype = _return_float_dtype(X, Y)
1577
+
1578
+ if effective_n_jobs(n_jobs) == 1:
1579
+ return func(X, Y, **kwds)
1580
+
1581
+ # enforce a threading backend to prevent data communication overhead
1582
+ fd = delayed(_dist_wrapper)
1583
+ ret = np.empty((X.shape[0], Y.shape[0]), dtype=dtype, order="F")
1584
+ Parallel(backend="threading", n_jobs=n_jobs)(
1585
+ fd(func, ret, s, X, Y[s], **kwds)
1586
+ for s in gen_even_slices(_num_samples(Y), effective_n_jobs(n_jobs))
1587
+ )
1588
+
1589
+ if (X is Y or Y is None) and func is euclidean_distances:
1590
+ # zeroing diagonal for euclidean norm.
1591
+ # TODO: do it also for other norms.
1592
+ np.fill_diagonal(ret, 0)
1593
+
1594
+ return ret
1595
+
1596
+
1597
+ def _pairwise_callable(X, Y, metric, force_all_finite=True, **kwds):
1598
+ """Handle the callable case for pairwise_{distances,kernels}."""
1599
+ X, Y = check_pairwise_arrays(X, Y, force_all_finite=force_all_finite)
1600
+
1601
+ if X is Y:
1602
+ # Only calculate metric for upper triangle
1603
+ out = np.zeros((X.shape[0], Y.shape[0]), dtype="float")
1604
+ iterator = itertools.combinations(range(X.shape[0]), 2)
1605
+ for i, j in iterator:
1606
+ out[i, j] = metric(X[i], Y[j], **kwds)
1607
+
1608
+ # Make symmetric
1609
+ # NB: out += out.T will produce incorrect results
1610
+ out = out + out.T
1611
+
1612
+ # Calculate diagonal
1613
+ # NB: nonzero diagonals are allowed for both metrics and kernels
1614
+ for i in range(X.shape[0]):
1615
+ x = X[i]
1616
+ out[i, i] = metric(x, x, **kwds)
1617
+
1618
+ else:
1619
+ # Calculate all cells
1620
+ out = np.empty((X.shape[0], Y.shape[0]), dtype="float")
1621
+ iterator = itertools.product(range(X.shape[0]), range(Y.shape[0]))
1622
+ for i, j in iterator:
1623
+ out[i, j] = metric(X[i], Y[j], **kwds)
1624
+
1625
+ return out
1626
+
1627
+
1628
+ _VALID_METRICS = [
1629
+ "euclidean",
1630
+ "l2",
1631
+ "l1",
1632
+ "manhattan",
1633
+ "cityblock",
1634
+ "braycurtis",
1635
+ "canberra",
1636
+ "chebyshev",
1637
+ "correlation",
1638
+ "cosine",
1639
+ "dice",
1640
+ "hamming",
1641
+ "jaccard",
1642
+ "kulsinski",
1643
+ "mahalanobis",
1644
+ "matching",
1645
+ "minkowski",
1646
+ "rogerstanimoto",
1647
+ "russellrao",
1648
+ "seuclidean",
1649
+ "sokalmichener",
1650
+ "sokalsneath",
1651
+ "sqeuclidean",
1652
+ "yule",
1653
+ "wminkowski",
1654
+ "nan_euclidean",
1655
+ "haversine",
1656
+ ]
1657
+
1658
+ _NAN_METRICS = ["nan_euclidean"]
1659
+
1660
+
1661
+ def _check_chunk_size(reduced, chunk_size):
1662
+ """Checks chunk is a sequence of expected size or a tuple of same."""
1663
+ if reduced is None:
1664
+ return
1665
+ is_tuple = isinstance(reduced, tuple)
1666
+ if not is_tuple:
1667
+ reduced = (reduced,)
1668
+ if any(isinstance(r, tuple) or not hasattr(r, "__iter__") for r in reduced):
1669
+ raise TypeError(
1670
+ "reduce_func returned %r. Expected sequence(s) of length %d."
1671
+ % (reduced if is_tuple else reduced[0], chunk_size)
1672
+ )
1673
+ if any(_num_samples(r) != chunk_size for r in reduced):
1674
+ actual_size = tuple(_num_samples(r) for r in reduced)
1675
+ raise ValueError(
1676
+ "reduce_func returned object of length %s. "
1677
+ "Expected same length as input: %d."
1678
+ % (actual_size if is_tuple else actual_size[0], chunk_size)
1679
+ )
1680
+
1681
+
1682
+ def _precompute_metric_params(X, Y, metric=None, **kwds):
1683
+ """Precompute data-derived metric parameters if not provided."""
1684
+ if metric == "seuclidean" and "V" not in kwds:
1685
+ # There is a bug in scipy < 1.5 that will cause a crash if
1686
+ # X.dtype != np.double (float64). See PR #15730
1687
+ dtype = np.float64 if sp_version < parse_version("1.5") else None
1688
+ if X is Y:
1689
+ V = np.var(X, axis=0, ddof=1, dtype=dtype)
1690
+ else:
1691
+ raise ValueError(
1692
+ "The 'V' parameter is required for the seuclidean metric "
1693
+ "when Y is passed."
1694
+ )
1695
+ return {"V": V}
1696
+ if metric == "mahalanobis" and "VI" not in kwds:
1697
+ if X is Y:
1698
+ VI = np.linalg.inv(np.cov(X.T)).T
1699
+ else:
1700
+ raise ValueError(
1701
+ "The 'VI' parameter is required for the mahalanobis metric "
1702
+ "when Y is passed."
1703
+ )
1704
+ return {"VI": VI}
1705
+ return {}
1706
+
1707
+
1708
+ def pairwise_distances_chunked(
1709
+ X,
1710
+ Y=None,
1711
+ *,
1712
+ reduce_func=None,
1713
+ metric="euclidean",
1714
+ n_jobs=None,
1715
+ working_memory=None,
1716
+ **kwds,
1717
+ ):
1718
+ """Generate a distance matrix chunk by chunk with optional reduction.
1719
+
1720
+ In cases where not all of a pairwise distance matrix needs to be
1721
+ stored at once, this is used to calculate pairwise distances in
1722
+ ``working_memory``-sized chunks. If ``reduce_func`` is given, it is
1723
+ run on each chunk and its return values are concatenated into lists,
1724
+ arrays or sparse matrices.
1725
+
1726
+ Parameters
1727
+ ----------
1728
+ X : ndarray of shape (n_samples_X, n_samples_X) or \
1729
+ (n_samples_X, n_features)
1730
+ Array of pairwise distances between samples, or a feature array.
1731
+ The shape the array should be (n_samples_X, n_samples_X) if
1732
+ metric='precomputed' and (n_samples_X, n_features) otherwise.
1733
+
1734
+ Y : ndarray of shape (n_samples_Y, n_features), default=None
1735
+ An optional second feature array. Only allowed if
1736
+ metric != "precomputed".
1737
+
1738
+ reduce_func : callable, default=None
1739
+ The function which is applied on each chunk of the distance matrix,
1740
+ reducing it to needed values. ``reduce_func(D_chunk, start)``
1741
+ is called repeatedly, where ``D_chunk`` is a contiguous vertical
1742
+ slice of the pairwise distance matrix, starting at row ``start``.
1743
+ It should return one of: None; an array, a list, or a sparse matrix
1744
+ of length ``D_chunk.shape[0]``; or a tuple of such objects.
1745
+ Returning None is useful for in-place operations, rather than
1746
+ reductions.
1747
+
1748
+ If None, pairwise_distances_chunked returns a generator of vertical
1749
+ chunks of the distance matrix.
1750
+
1751
+ metric : str or callable, default='euclidean'
1752
+ The metric to use when calculating distance between instances in a
1753
+ feature array. If metric is a string, it must be one of the options
1754
+ allowed by scipy.spatial.distance.pdist for its metric parameter,
1755
+ or a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS.
1756
+ If metric is "precomputed", X is assumed to be a distance matrix.
1757
+ Alternatively, if metric is a callable function, it is called on
1758
+ each pair of instances (rows) and the resulting value recorded.
1759
+ The callable should take two arrays from X as input and return a
1760
+ value indicating the distance between them.
1761
+
1762
+ n_jobs : int, default=None
1763
+ The number of jobs to use for the computation. This works by
1764
+ breaking down the pairwise matrix into n_jobs even slices and
1765
+ computing them in parallel.
1766
+
1767
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
1768
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
1769
+ for more details.
1770
+
1771
+ working_memory : int, default=None
1772
+ The sought maximum memory for temporary distance matrix chunks.
1773
+ When None (default), the value of
1774
+ ``sklearn.get_config()['working_memory']`` is used.
1775
+
1776
+ **kwds : optional keyword parameters
1777
+ Any further parameters are passed directly to the distance function.
1778
+ If using a scipy.spatial.distance metric, the parameters are still
1779
+ metric dependent. See the scipy docs for usage examples.
1780
+
1781
+ Yields
1782
+ ------
1783
+ D_chunk : {ndarray, sparse matrix}
1784
+ A contiguous slice of distance matrix, optionally processed by
1785
+ ``reduce_func``.
1786
+
1787
+ Examples
1788
+ --------
1789
+ Without reduce_func:
1790
+
1791
+ >>> import numpy as np
1792
+ >>> from sklearn.metrics import pairwise_distances_chunked
1793
+ >>> X = np.random.RandomState(0).rand(5, 3)
1794
+ >>> D_chunk = next(pairwise_distances_chunked(X))
1795
+ >>> D_chunk
1796
+ array([[0. ..., 0.29..., 0.41..., 0.19..., 0.57...],
1797
+ [0.29..., 0. ..., 0.57..., 0.41..., 0.76...],
1798
+ [0.41..., 0.57..., 0. ..., 0.44..., 0.90...],
1799
+ [0.19..., 0.41..., 0.44..., 0. ..., 0.51...],
1800
+ [0.57..., 0.76..., 0.90..., 0.51..., 0. ...]])
1801
+
1802
+ Retrieve all neighbors and average distance within radius r:
1803
+
1804
+ >>> r = .2
1805
+ >>> def reduce_func(D_chunk, start):
1806
+ ... neigh = [np.flatnonzero(d < r) for d in D_chunk]
1807
+ ... avg_dist = (D_chunk * (D_chunk < r)).mean(axis=1)
1808
+ ... return neigh, avg_dist
1809
+ >>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func)
1810
+ >>> neigh, avg_dist = next(gen)
1811
+ >>> neigh
1812
+ [array([0, 3]), array([1]), array([2]), array([0, 3]), array([4])]
1813
+ >>> avg_dist
1814
+ array([0.039..., 0. , 0. , 0.039..., 0. ])
1815
+
1816
+ Where r is defined per sample, we need to make use of ``start``:
1817
+
1818
+ >>> r = [.2, .4, .4, .3, .1]
1819
+ >>> def reduce_func(D_chunk, start):
1820
+ ... neigh = [np.flatnonzero(d < r[i])
1821
+ ... for i, d in enumerate(D_chunk, start)]
1822
+ ... return neigh
1823
+ >>> neigh = next(pairwise_distances_chunked(X, reduce_func=reduce_func))
1824
+ >>> neigh
1825
+ [array([0, 3]), array([0, 1]), array([2]), array([0, 3]), array([4])]
1826
+
1827
+ Force row-by-row generation by reducing ``working_memory``:
1828
+
1829
+ >>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func,
1830
+ ... working_memory=0)
1831
+ >>> next(gen)
1832
+ [array([0, 3])]
1833
+ >>> next(gen)
1834
+ [array([0, 1])]
1835
+ """
1836
+ n_samples_X = _num_samples(X)
1837
+ if metric == "precomputed":
1838
+ slices = (slice(0, n_samples_X),)
1839
+ else:
1840
+ if Y is None:
1841
+ Y = X
1842
+ # We get as many rows as possible within our working_memory budget to
1843
+ # store len(Y) distances in each row of output.
1844
+ #
1845
+ # Note:
1846
+ # - this will get at least 1 row, even if 1 row of distances will
1847
+ # exceed working_memory.
1848
+ # - this does not account for any temporary memory usage while
1849
+ # calculating distances (e.g. difference of vectors in manhattan
1850
+ # distance.
1851
+ chunk_n_rows = get_chunk_n_rows(
1852
+ row_bytes=8 * _num_samples(Y),
1853
+ max_n_rows=n_samples_X,
1854
+ working_memory=working_memory,
1855
+ )
1856
+ slices = gen_batches(n_samples_X, chunk_n_rows)
1857
+
1858
+ # precompute data-derived metric params
1859
+ params = _precompute_metric_params(X, Y, metric=metric, **kwds)
1860
+ kwds.update(**params)
1861
+
1862
+ for sl in slices:
1863
+ if sl.start == 0 and sl.stop == n_samples_X:
1864
+ X_chunk = X # enable optimised paths for X is Y
1865
+ else:
1866
+ X_chunk = X[sl]
1867
+ D_chunk = pairwise_distances(X_chunk, Y, metric=metric, n_jobs=n_jobs, **kwds)
1868
+ if (X is Y or Y is None) and PAIRWISE_DISTANCE_FUNCTIONS.get(
1869
+ metric, None
1870
+ ) is euclidean_distances:
1871
+ # zeroing diagonal, taking care of aliases of "euclidean",
1872
+ # i.e. "l2"
1873
+ D_chunk.flat[sl.start :: _num_samples(X) + 1] = 0
1874
+ if reduce_func is not None:
1875
+ chunk_size = D_chunk.shape[0]
1876
+ D_chunk = reduce_func(D_chunk, sl.start)
1877
+ _check_chunk_size(D_chunk, chunk_size)
1878
+ yield D_chunk
1879
+
1880
+
1881
+ def pairwise_distances(
1882
+ X, Y=None, metric="euclidean", *, n_jobs=None, force_all_finite=True, **kwds
1883
+ ):
1884
+ """Compute the distance matrix from a vector array X and optional Y.
1885
+
1886
+ This method takes either a vector array or a distance matrix, and returns
1887
+ a distance matrix. If the input is a vector array, the distances are
1888
+ computed. If the input is a distances matrix, it is returned instead.
1889
+
1890
+ This method provides a safe way to take a distance matrix as input, while
1891
+ preserving compatibility with many other algorithms that take a vector
1892
+ array.
1893
+
1894
+ If Y is given (default is None), then the returned matrix is the pairwise
1895
+ distance between the arrays from both X and Y.
1896
+
1897
+ Valid values for metric are:
1898
+
1899
+ - From scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
1900
+ 'manhattan']. These metrics support sparse matrix
1901
+ inputs.
1902
+ ['nan_euclidean'] but it does not yet support sparse matrices.
1903
+
1904
+ - From scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
1905
+ 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis',
1906
+ 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean',
1907
+ 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule']
1908
+ See the documentation for scipy.spatial.distance for details on these
1909
+ metrics. These metrics do not support sparse matrix inputs.
1910
+
1911
+ Note that in the case of 'cityblock', 'cosine' and 'euclidean' (which are
1912
+ valid scipy.spatial.distance metrics), the scikit-learn implementation
1913
+ will be used, which is faster and has support for sparse matrices (except
1914
+ for 'cityblock'). For a verbose description of the metrics from
1915
+ scikit-learn, see :func:`sklearn.metrics.pairwise.distance_metrics`
1916
+ function.
1917
+
1918
+ Read more in the :ref:`User Guide <metrics>`.
1919
+
1920
+ Parameters
1921
+ ----------
1922
+ X : ndarray of shape (n_samples_X, n_samples_X) or \
1923
+ (n_samples_X, n_features)
1924
+ Array of pairwise distances between samples, or a feature array.
1925
+ The shape of the array should be (n_samples_X, n_samples_X) if
1926
+ metric == "precomputed" and (n_samples_X, n_features) otherwise.
1927
+
1928
+ Y : ndarray of shape (n_samples_Y, n_features), default=None
1929
+ An optional second feature array. Only allowed if
1930
+ metric != "precomputed".
1931
+
1932
+ metric : str or callable, default='euclidean'
1933
+ The metric to use when calculating distance between instances in a
1934
+ feature array. If metric is a string, it must be one of the options
1935
+ allowed by scipy.spatial.distance.pdist for its metric parameter, or
1936
+ a metric listed in ``pairwise.PAIRWISE_DISTANCE_FUNCTIONS``.
1937
+ If metric is "precomputed", X is assumed to be a distance matrix.
1938
+ Alternatively, if metric is a callable function, it is called on each
1939
+ pair of instances (rows) and the resulting value recorded. The callable
1940
+ should take two arrays from X as input and return a value indicating
1941
+ the distance between them.
1942
+
1943
+ n_jobs : int, default=None
1944
+ The number of jobs to use for the computation. This works by breaking
1945
+ down the pairwise matrix into n_jobs even slices and computing them in
1946
+ parallel.
1947
+
1948
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
1949
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
1950
+ for more details.
1951
+
1952
+ force_all_finite : bool or 'allow-nan', default=True
1953
+ Whether to raise an error on np.inf, np.nan, pd.NA in array. Ignored
1954
+ for a metric listed in ``pairwise.PAIRWISE_DISTANCE_FUNCTIONS``. The
1955
+ possibilities are:
1956
+
1957
+ - True: Force all values of array to be finite.
1958
+ - False: accepts np.inf, np.nan, pd.NA in array.
1959
+ - 'allow-nan': accepts only np.nan and pd.NA values in array. Values
1960
+ cannot be infinite.
1961
+
1962
+ .. versionadded:: 0.22
1963
+ ``force_all_finite`` accepts the string ``'allow-nan'``.
1964
+
1965
+ .. versionchanged:: 0.23
1966
+ Accepts `pd.NA` and converts it into `np.nan`.
1967
+
1968
+ **kwds : optional keyword parameters
1969
+ Any further parameters are passed directly to the distance function.
1970
+ If using a scipy.spatial.distance metric, the parameters are still
1971
+ metric dependent. See the scipy docs for usage examples.
1972
+
1973
+ Returns
1974
+ -------
1975
+ D : ndarray of shape (n_samples_X, n_samples_X) or \
1976
+ (n_samples_X, n_samples_Y)
1977
+ A distance matrix D such that D_{i, j} is the distance between the
1978
+ ith and jth vectors of the given matrix X, if Y is None.
1979
+ If Y is not None, then D_{i, j} is the distance between the ith array
1980
+ from X and the jth array from Y.
1981
+
1982
+ See Also
1983
+ --------
1984
+ pairwise_distances_chunked : Performs the same calculation as this
1985
+ function, but returns a generator of chunks of the distance matrix, in
1986
+ order to limit memory usage.
1987
+ paired_distances : Computes the distances between corresponding elements
1988
+ of two arrays.
1989
+ """
1990
+ if (
1991
+ metric not in _VALID_METRICS
1992
+ and not callable(metric)
1993
+ and metric != "precomputed"
1994
+ ):
1995
+ raise ValueError(
1996
+ "Unknown metric %s. Valid metrics are %s, or 'precomputed', or a callable"
1997
+ % (metric, _VALID_METRICS)
1998
+ )
1999
+
2000
+ if metric == "precomputed":
2001
+ X, _ = check_pairwise_arrays(
2002
+ X, Y, precomputed=True, force_all_finite=force_all_finite
2003
+ )
2004
+
2005
+ whom = (
2006
+ "`pairwise_distances`. Precomputed distance "
2007
+ " need to have non-negative values."
2008
+ )
2009
+ check_non_negative(X, whom=whom)
2010
+ return X
2011
+ elif metric in PAIRWISE_DISTANCE_FUNCTIONS:
2012
+ func = PAIRWISE_DISTANCE_FUNCTIONS[metric]
2013
+ elif callable(metric):
2014
+ func = partial(
2015
+ _pairwise_callable, metric=metric, force_all_finite=force_all_finite, **kwds
2016
+ )
2017
+ else:
2018
+ if issparse(X) or issparse(Y):
2019
+ raise TypeError("scipy distance metrics do not support sparse matrices.")
2020
+
2021
+ dtype = bool if metric in PAIRWISE_BOOLEAN_FUNCTIONS else None
2022
+
2023
+ if dtype == bool and (X.dtype != bool or (Y is not None and Y.dtype != bool)):
2024
+ msg = "Data was converted to boolean for metric %s" % metric
2025
+ warnings.warn(msg, DataConversionWarning)
2026
+
2027
+ X, Y = check_pairwise_arrays(
2028
+ X, Y, dtype=dtype, force_all_finite=force_all_finite
2029
+ )
2030
+
2031
+ # precompute data-derived metric params
2032
+ params = _precompute_metric_params(X, Y, metric=metric, **kwds)
2033
+ kwds.update(**params)
2034
+
2035
+ if effective_n_jobs(n_jobs) == 1 and X is Y:
2036
+ return distance.squareform(distance.pdist(X, metric=metric, **kwds))
2037
+ func = partial(distance.cdist, metric=metric, **kwds)
2038
+
2039
+ return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
2040
+
2041
+
2042
+ # These distances require boolean arrays, when using scipy.spatial.distance
2043
+ PAIRWISE_BOOLEAN_FUNCTIONS = [
2044
+ "dice",
2045
+ "jaccard",
2046
+ "kulsinski",
2047
+ "matching",
2048
+ "rogerstanimoto",
2049
+ "russellrao",
2050
+ "sokalmichener",
2051
+ "sokalsneath",
2052
+ "yule",
2053
+ ]
2054
+
2055
+ # Helper functions - distance
2056
+ PAIRWISE_KERNEL_FUNCTIONS = {
2057
+ # If updating this dictionary, update the doc in both distance_metrics()
2058
+ # and also in pairwise_distances()!
2059
+ "additive_chi2": additive_chi2_kernel,
2060
+ "chi2": chi2_kernel,
2061
+ "linear": linear_kernel,
2062
+ "polynomial": polynomial_kernel,
2063
+ "poly": polynomial_kernel,
2064
+ "rbf": rbf_kernel,
2065
+ "laplacian": laplacian_kernel,
2066
+ "sigmoid": sigmoid_kernel,
2067
+ "cosine": cosine_similarity,
2068
+ }
2069
+
2070
+
2071
+ def kernel_metrics():
2072
+ """Valid metrics for pairwise_kernels.
2073
+
2074
+ This function simply returns the valid pairwise distance metrics.
2075
+ It exists, however, to allow for a verbose description of the mapping for
2076
+ each of the valid strings.
2077
+
2078
+ The valid distance metrics, and the function they map to, are:
2079
+ =============== ========================================
2080
+ metric Function
2081
+ =============== ========================================
2082
+ 'additive_chi2' sklearn.pairwise.additive_chi2_kernel
2083
+ 'chi2' sklearn.pairwise.chi2_kernel
2084
+ 'linear' sklearn.pairwise.linear_kernel
2085
+ 'poly' sklearn.pairwise.polynomial_kernel
2086
+ 'polynomial' sklearn.pairwise.polynomial_kernel
2087
+ 'rbf' sklearn.pairwise.rbf_kernel
2088
+ 'laplacian' sklearn.pairwise.laplacian_kernel
2089
+ 'sigmoid' sklearn.pairwise.sigmoid_kernel
2090
+ 'cosine' sklearn.pairwise.cosine_similarity
2091
+ =============== ========================================
2092
+
2093
+ Read more in the :ref:`User Guide <metrics>`.
2094
+
2095
+ Returns
2096
+ -------
2097
+ kernal_metrics : dict
2098
+ Returns valid metrics for pairwise_kernels.
2099
+ """
2100
+ return PAIRWISE_KERNEL_FUNCTIONS
2101
+
2102
+
2103
+ KERNEL_PARAMS = {
2104
+ "additive_chi2": (),
2105
+ "chi2": frozenset(["gamma"]),
2106
+ "cosine": (),
2107
+ "linear": (),
2108
+ "poly": frozenset(["gamma", "degree", "coef0"]),
2109
+ "polynomial": frozenset(["gamma", "degree", "coef0"]),
2110
+ "rbf": frozenset(["gamma"]),
2111
+ "laplacian": frozenset(["gamma"]),
2112
+ "sigmoid": frozenset(["gamma", "coef0"]),
2113
+ }
2114
+
2115
+
2116
+ def pairwise_kernels(
2117
+ X, Y=None, metric="linear", *, filter_params=False, n_jobs=None, **kwds
2118
+ ):
2119
+ """Compute the kernel between arrays X and optional array Y.
2120
+
2121
+ This method takes either a vector array or a kernel matrix, and returns
2122
+ a kernel matrix. If the input is a vector array, the kernels are
2123
+ computed. If the input is a kernel matrix, it is returned instead.
2124
+
2125
+ This method provides a safe way to take a kernel matrix as input, while
2126
+ preserving compatibility with many other algorithms that take a vector
2127
+ array.
2128
+
2129
+ If Y is given (default is None), then the returned matrix is the pairwise
2130
+ kernel between the arrays from both X and Y.
2131
+
2132
+ Valid values for metric are:
2133
+ ['additive_chi2', 'chi2', 'linear', 'poly', 'polynomial', 'rbf',
2134
+ 'laplacian', 'sigmoid', 'cosine']
2135
+
2136
+ Read more in the :ref:`User Guide <metrics>`.
2137
+
2138
+ Parameters
2139
+ ----------
2140
+ X : ndarray of shape (n_samples_X, n_samples_X) or (n_samples_X, n_features)
2141
+ Array of pairwise kernels between samples, or a feature array.
2142
+ The shape of the array should be (n_samples_X, n_samples_X) if
2143
+ metric == "precomputed" and (n_samples_X, n_features) otherwise.
2144
+
2145
+ Y : ndarray of shape (n_samples_Y, n_features), default=None
2146
+ A second feature array only if X has shape (n_samples_X, n_features).
2147
+
2148
+ metric : str or callable, default="linear"
2149
+ The metric to use when calculating kernel between instances in a
2150
+ feature array. If metric is a string, it must be one of the metrics
2151
+ in pairwise.PAIRWISE_KERNEL_FUNCTIONS.
2152
+ If metric is "precomputed", X is assumed to be a kernel matrix.
2153
+ Alternatively, if metric is a callable function, it is called on each
2154
+ pair of instances (rows) and the resulting value recorded. The callable
2155
+ should take two rows from X as input and return the corresponding
2156
+ kernel value as a single number. This means that callables from
2157
+ :mod:`sklearn.metrics.pairwise` are not allowed, as they operate on
2158
+ matrices, not single samples. Use the string identifying the kernel
2159
+ instead.
2160
+
2161
+ filter_params : bool, default=False
2162
+ Whether to filter invalid parameters or not.
2163
+
2164
+ n_jobs : int, default=None
2165
+ The number of jobs to use for the computation. This works by breaking
2166
+ down the pairwise matrix into n_jobs even slices and computing them in
2167
+ parallel.
2168
+
2169
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
2170
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
2171
+ for more details.
2172
+
2173
+ **kwds : optional keyword parameters
2174
+ Any further parameters are passed directly to the kernel function.
2175
+
2176
+ Returns
2177
+ -------
2178
+ K : ndarray of shape (n_samples_X, n_samples_X) or (n_samples_X, n_samples_Y)
2179
+ A kernel matrix K such that K_{i, j} is the kernel between the
2180
+ ith and jth vectors of the given matrix X, if Y is None.
2181
+ If Y is not None, then K_{i, j} is the kernel between the ith array
2182
+ from X and the jth array from Y.
2183
+
2184
+ Notes
2185
+ -----
2186
+ If metric is 'precomputed', Y is ignored and X is returned.
2187
+ """
2188
+ # import GPKernel locally to prevent circular imports
2189
+ from ..gaussian_process.kernels import Kernel as GPKernel
2190
+
2191
+ if metric == "precomputed":
2192
+ X, _ = check_pairwise_arrays(X, Y, precomputed=True)
2193
+ return X
2194
+ elif isinstance(metric, GPKernel):
2195
+ func = metric.__call__
2196
+ elif metric in PAIRWISE_KERNEL_FUNCTIONS:
2197
+ if filter_params:
2198
+ kwds = {k: kwds[k] for k in kwds if k in KERNEL_PARAMS[metric]}
2199
+ func = PAIRWISE_KERNEL_FUNCTIONS[metric]
2200
+ elif callable(metric):
2201
+ func = partial(_pairwise_callable, metric=metric, **kwds)
2202
+ else:
2203
+ raise ValueError("Unknown kernel %r" % metric)
2204
+
2205
+ return _parallel_pairwise(X, Y, func, n_jobs, **kwds)
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (31.6 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_arpack.cpython-310.pyc ADDED
Binary file (1.33 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_array_api.cpython-310.pyc ADDED
Binary file (8.09 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_bunch.cpython-310.pyc ADDED
Binary file (1.58 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_estimator_html_repr.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_joblib.cpython-310.pyc ADDED
Binary file (730 Bytes). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_param_validation.cpython-310.pyc ADDED
Binary file (28.8 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_pprint.cpython-310.pyc ADDED
Binary file (11.5 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/class_weight.cpython-310.pyc ADDED
Binary file (5.35 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/discovery.cpython-310.pyc ADDED
Binary file (6.19 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/metaestimators.cpython-310.pyc ADDED
Binary file (7.76 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/parallel.cpython-310.pyc ADDED
Binary file (4.44 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/random.cpython-310.pyc ADDED
Binary file (2.53 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/sparsefuncs.cpython-310.pyc ADDED
Binary file (16.9 kB). View file
 
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_assert_async_cpu_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API void _assert_async(const at::Tensor & self);
21
+ TORCH_API void _assert_async(const at::Tensor & self, c10::string_view assert_msg);
22
+
23
+ } // namespace cpu
24
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Char_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor _cast_Char(const at::Tensor & self, bool non_blocking=false);
21
+
22
+ } // namespace compositeimplicitautograd
23
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_copy_from_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor & _copy_from_out(const at::Tensor & self, const at::Tensor & dst, bool non_blocking, at::Tensor & out);
20
+ } // namespace native
21
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _embedding_bag {
18
+ using schema = ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor> (const at::Tensor &, const at::Tensor &, const at::Tensor &, bool, int64_t, bool, const ::std::optional<at::Tensor> &, bool, int64_t);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_embedding_bag")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1) -> (Tensor, Tensor, Tensor, Tensor)")
24
+ static ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor> call(const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional<at::Tensor> & per_sample_weights, bool include_last_offset, int64_t padding_idx);
25
+ static ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional<at::Tensor> & per_sample_weights, bool include_last_offset, int64_t padding_idx);
26
+ };
27
+
28
+ struct TORCH_API _embedding_bag_out {
29
+ using schema = ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> (const at::Tensor &, const at::Tensor &, const at::Tensor &, bool, int64_t, bool, const ::std::optional<at::Tensor> &, bool, int64_t, at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_embedding_bag")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_embedding_bag.out(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!))")
35
+ static ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> call(const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional<at::Tensor> & per_sample_weights, bool include_last_offset, int64_t padding_idx, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3);
36
+ static ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional<at::Tensor> & per_sample_weights, bool include_last_offset, int64_t padding_idx, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3);
37
+ };
38
+
39
+ }} // namespace at::_ops
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_tanh_ops.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _foreach_tanh {
18
+ using schema = ::std::vector<at::Tensor> (at::TensorList);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_tanh")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_tanh(Tensor[] self) -> Tensor[]")
24
+ static ::std::vector<at::Tensor> call(at::TensorList self);
25
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self);
26
+ };
27
+
28
+ struct TORCH_API _foreach_tanh_ {
29
+ using schema = void (at::TensorList);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_tanh_")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_tanh_(Tensor(a!)[] self) -> ()")
35
+ static void call(at::TensorList self);
36
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self);
37
+ };
38
+
39
+ struct TORCH_API _foreach_tanh_out {
40
+ using schema = void (at::TensorList, at::TensorList);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_tanh")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_tanh.out(Tensor[] self, *, Tensor(a!)[] out) -> ()")
46
+ static void call(at::TensorList self, at::TensorList out);
47
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out);
48
+ };
49
+
50
+ }} // namespace at::_ops
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sobol_engine_draw_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _sobol_engine_draw {
18
+ using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &, int64_t, const at::Tensor &, int64_t, int64_t, ::std::optional<at::ScalarType>);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sobol_engine_draw")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sobol_engine_draw(Tensor quasi, int n, Tensor sobolstate, int dimension, int num_generated, ScalarType? dtype) -> (Tensor, Tensor)")
24
+ static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & quasi, int64_t n, const at::Tensor & sobolstate, int64_t dimension, int64_t num_generated, ::std::optional<at::ScalarType> dtype);
25
+ static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & quasi, int64_t n, const at::Tensor & sobolstate, int64_t dimension, int64_t num_generated, ::std::optional<at::ScalarType> dtype);
26
+ };
27
+
28
+ }} // namespace at::_ops
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_semi_structured_tile_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _sparse_semi_structured_tile {
18
+ using schema = ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> (const at::Tensor &, c10::string_view, bool);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_semi_structured_tile")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_semi_structured_tile(Tensor input, str algorithm=\"\", bool use_cutlass=True) -> (Tensor, Tensor, Tensor, Tensor, Tensor)")
24
+ static ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> call(const at::Tensor & input, c10::string_view algorithm, bool use_cutlass);
25
+ static ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, c10::string_view algorithm, bool use_cutlass);
26
+ };
27
+
28
+ }} // namespace at::_ops
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell_cuda_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _thnn_fused_lstm_cell(const at::Tensor & input_gates, const at::Tensor & hidden_gates, const at::Tensor & cx, const ::std::optional<at::Tensor> & input_bias={}, const ::std::optional<at::Tensor> & hidden_bias={});
21
+
22
+ } // namespace cuda
23
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/arccosh_native.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor arccosh(const at::Tensor & self);
20
+ TORCH_API at::Tensor & arccosh_out(const at::Tensor & self, at::Tensor & out);
21
+ TORCH_API at::Tensor & arccosh_(at::Tensor & self);
22
+ } // namespace native
23
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/batch_norm_update_stats.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/batch_norm_update_stats_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::batch_norm_update_stats(Tensor input, Tensor? running_mean, Tensor? running_var, float momentum) -> (Tensor, Tensor)
26
+ inline ::std::tuple<at::Tensor,at::Tensor> batch_norm_update_stats(const at::Tensor & input, const ::std::optional<at::Tensor> & running_mean, const ::std::optional<at::Tensor> & running_var, double momentum) {
27
+ return at::_ops::batch_norm_update_stats::call(input, running_mean, running_var, momentum);
28
+ }
29
+
30
+ // aten::batch_norm_update_stats.out(Tensor input, Tensor? running_mean, Tensor? running_var, float momentum, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))
31
+ inline ::std::tuple<at::Tensor &,at::Tensor &> batch_norm_update_stats_out(at::Tensor & out0, at::Tensor & out1, const at::Tensor & input, const ::std::optional<at::Tensor> & running_mean, const ::std::optional<at::Tensor> & running_var, double momentum) {
32
+ return at::_ops::batch_norm_update_stats_out::call(input, running_mean, running_var, momentum, out0, out1);
33
+ }
34
+ // aten::batch_norm_update_stats.out(Tensor input, Tensor? running_mean, Tensor? running_var, float momentum, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!))
35
+ inline ::std::tuple<at::Tensor &,at::Tensor &> batch_norm_update_stats_outf(const at::Tensor & input, const ::std::optional<at::Tensor> & running_mean, const ::std::optional<at::Tensor> & running_var, double momentum, at::Tensor & out0, at::Tensor & out1) {
36
+ return at::_ops::batch_norm_update_stats_out::call(input, running_mean, running_var, momentum, out0, out1);
37
+ }
38
+
39
+ }
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy_with_logits_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor binary_cross_entropy_with_logits(const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight={}, const ::std::optional<at::Tensor> & pos_weight={}, int64_t reduction=at::Reduction::Mean);
21
+ TORCH_API at::Tensor & binary_cross_entropy_with_logits_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight={}, const ::std::optional<at::Tensor> & pos_weight={}, int64_t reduction=at::Reduction::Mean);
22
+ TORCH_API at::Tensor & binary_cross_entropy_with_logits_outf(const at::Tensor & self, const at::Tensor & target, const ::std::optional<at::Tensor> & weight, const ::std::optional<at::Tensor> & pos_weight, int64_t reduction, at::Tensor & out);
23
+
24
+ } // namespace compositeexplicitautograd
25
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/conv_transpose3d_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor conv_transpose3d(const at::Tensor & input, const at::Tensor & weight, const ::std::optional<at::Tensor> & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, int64_t groups=1, at::IntArrayRef dilation=1);
21
+ TORCH_API at::Tensor conv_transpose3d_symint(const at::Tensor & input, const at::Tensor & weight, const ::std::optional<at::Tensor> & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymInt groups=1, c10::SymIntArrayRef dilation=c10::SymInt(1));
22
+
23
+ } // namespace compositeimplicitautograd
24
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/corrcoef_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor corrcoef(const at::Tensor & self);
20
+ } // namespace native
21
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_convolution_add_relu.h ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/cudnn_convolution_add_relu_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::cudnn_convolution_add_relu(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor
26
+ inline at::Tensor cudnn_convolution_add_relu(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional<at::Scalar> & alpha, const ::std::optional<at::Tensor> & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups) {
27
+ return at::_ops::cudnn_convolution_add_relu::call(self, weight, z, alpha, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups);
28
+ }
29
+ namespace symint {
30
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
31
+ at::Tensor cudnn_convolution_add_relu(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional<at::Scalar> & alpha, const ::std::optional<at::Tensor> & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups) {
32
+ return at::_ops::cudnn_convolution_add_relu::call(self, weight, z, alpha, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups);
33
+ }
34
+ }
35
+
36
+ // aten::cudnn_convolution_add_relu(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor
37
+ inline at::Tensor cudnn_convolution_add_relu_symint(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional<at::Scalar> & alpha, const ::std::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups) {
38
+ return at::_ops::cudnn_convolution_add_relu::call(self, weight, z, alpha, bias, stride, padding, dilation, groups);
39
+ }
40
+ namespace symint {
41
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
42
+ at::Tensor cudnn_convolution_add_relu(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional<at::Scalar> & alpha, const ::std::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups) {
43
+ return at::_ops::cudnn_convolution_add_relu::call(self, weight, z, alpha, bias, stride, padding, dilation, groups);
44
+ }
45
+ }
46
+
47
+ // aten::cudnn_convolution_add_relu.out(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!)
48
+ inline at::Tensor & cudnn_convolution_add_relu_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional<at::Scalar> & alpha, const ::std::optional<at::Tensor> & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups) {
49
+ return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups, out);
50
+ }
51
+ namespace symint {
52
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
53
+ at::Tensor & cudnn_convolution_add_relu_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional<at::Scalar> & alpha, const ::std::optional<at::Tensor> & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups) {
54
+ return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups, out);
55
+ }
56
+ }
57
+
58
+ // aten::cudnn_convolution_add_relu.out(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!)
59
+ inline at::Tensor & cudnn_convolution_add_relu_outf(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional<at::Scalar> & alpha, const ::std::optional<at::Tensor> & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups, at::Tensor & out) {
60
+ return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups, out);
61
+ }
62
+ namespace symint {
63
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
64
+ at::Tensor & cudnn_convolution_add_relu_outf(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional<at::Scalar> & alpha, const ::std::optional<at::Tensor> & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups, at::Tensor & out) {
65
+ return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups, out);
66
+ }
67
+ }
68
+
69
+ // aten::cudnn_convolution_add_relu.out(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!)
70
+ inline at::Tensor & cudnn_convolution_add_relu_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional<at::Scalar> & alpha, const ::std::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups) {
71
+ return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, stride, padding, dilation, groups, out);
72
+ }
73
+ namespace symint {
74
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
75
+ at::Tensor & cudnn_convolution_add_relu_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional<at::Scalar> & alpha, const ::std::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups) {
76
+ return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, stride, padding, dilation, groups, out);
77
+ }
78
+ }
79
+
80
+ // aten::cudnn_convolution_add_relu.out(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!)
81
+ inline at::Tensor & cudnn_convolution_add_relu_symint_outf(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional<at::Scalar> & alpha, const ::std::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups, at::Tensor & out) {
82
+ return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, stride, padding, dilation, groups, out);
83
+ }
84
+ namespace symint {
85
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
86
+ at::Tensor & cudnn_convolution_add_relu_outf(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional<at::Scalar> & alpha, const ::std::optional<at::Tensor> & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups, at::Tensor & out) {
87
+ return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, stride, padding, dilation, groups, out);
88
+ }
89
+ }
90
+
91
+ }
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/deg2rad.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/deg2rad_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::deg2rad(Tensor self) -> Tensor
26
+ inline at::Tensor deg2rad(const at::Tensor & self) {
27
+ return at::_ops::deg2rad::call(self);
28
+ }
29
+
30
+ // aten::deg2rad_(Tensor(a!) self) -> Tensor(a!)
31
+ inline at::Tensor & deg2rad_(at::Tensor & self) {
32
+ return at::_ops::deg2rad_::call(self);
33
+ }
34
+
35
+ // aten::deg2rad.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
36
+ inline at::Tensor & deg2rad_out(at::Tensor & out, const at::Tensor & self) {
37
+ return at::_ops::deg2rad_out::call(self, out);
38
+ }
39
+ // aten::deg2rad.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
40
+ inline at::Tensor & deg2rad_outf(const at::Tensor & self, at::Tensor & out) {
41
+ return at::_ops::deg2rad_out::call(self, out);
42
+ }
43
+
44
+ }