Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- videollama2/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.cpython-310-x86_64-linux-gnu.soAdded+3
- videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/base.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_base.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_common_curve_display.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_det_curve_display.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_predict_error_display.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/__init__.pyAdded+48
- videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_bicluster.pyAdded+90
- videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_supervised.pyAdded+1176
- videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_unsupervised.pyAdded+366
- videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/__init__.pyAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/__init__.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_classification.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_common.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_dist_metrics.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_pairwise.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_pairwise_distances_reduction.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_ranking.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_regression.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_score_objects.cpython-310.pycAdded
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_classification.pyAdded+2662
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_common.pyAdded+1734
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_dist_metrics.pyAdded+456
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise.pyAdded+1551
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_ranking.pyAdded+2117
- videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_score_objects.pyAdded+1200
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Half.hAdded+30
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_copy_from_ops.hAdded+39
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_backward_ops.hAdded+28
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_dense_backward_cpu_dispatch.hAdded+24
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_sparse_backward_compositeimplicitautograd_dispatch.hAdded+24
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_atan.hAdded+44
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sigmoid_cuda_dispatch.hAdded+24
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_fused_sdp_choice_cuda_dispatch.hAdded+23
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_gather_sparse_backward_native.hAdded+21
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_eigh_meta.hAdded+27
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_lu_with_info_native.hAdded+21
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_prelu_kernel_backward.hAdded+30
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_reshape_alias_cpu_dispatch.hAdded+24
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_differentiable_lstm_cell_backward_ops.hAdded+28
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bilinear2d_aa_backward.hAdded+91
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_wrapped_quantized_linear_prepacked_compositeimplicitautograd_dispatch.hAdded+23
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/absolute.hAdded+39
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/asinh.hAdded+44
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/batch_norm_gather_stats_cuda_dispatch.hAdded+23
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/cholesky.hAdded+39
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/clamp_compositeexplicitautogradnonfunctional_dispatch.hAdded+26
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/concat_ops.hAdded+61
- vllm/lib/python3.10/site-packages/torch/include/ATen/ops/exp_meta.hAdded+27
1937 unmodified lines1938193919401937 unmodified linesvideollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textvideollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textvideollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text1937 unmodified lines19381939194019411937 unmodified linesvideollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textvideollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textvideollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -textvideollama2/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
123version https://git-lfs.github.com/spec/v1oid sha256:b8a7904e6f8118aa6196cec5b8005c67baf3cc15d81aded7240751d890419498size 651001123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""The :mod:`sklearn.metrics.cluster` submodule contains evaluation metrics forcluster analysis results. There are two forms of evaluation:
- supervised, which uses a ground truth class values for each sample.- unsupervised, which does not and measures the 'quality' of the model itself."""from ._supervised import adjusted_mutual_info_scorefrom ._supervised import normalized_mutual_info_scorefrom ._supervised import adjusted_rand_scorefrom ._supervised import rand_scorefrom ._supervised import completeness_scorefrom ._supervised import contingency_matrixfrom ._supervised import pair_confusion_matrixfrom ._supervised import expected_mutual_informationfrom ._supervised import homogeneity_completeness_v_measurefrom ._supervised import homogeneity_scorefrom ._supervised import mutual_info_scorefrom ._supervised import v_measure_scorefrom ._supervised import fowlkes_mallows_scorefrom ._supervised import entropyfrom ._unsupervised import silhouette_samplesfrom ._unsupervised import silhouette_scorefrom ._unsupervised import calinski_harabasz_scorefrom ._unsupervised import davies_bouldin_scorefrom ._bicluster import consensus_score
__all__ = [ "adjusted_mutual_info_score", "normalized_mutual_info_score", "adjusted_rand_score", "rand_score", "completeness_score", "pair_confusion_matrix", "contingency_matrix", "expected_mutual_information", "homogeneity_completeness_v_measure", "homogeneity_score", "mutual_info_score", "v_measure_score", "fowlkes_mallows_score", "entropy", "silhouette_samples", "silhouette_score", "calinski_harabasz_score", "davies_bouldin_score", "consensus_score",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import numpy as npfrom scipy.optimize import linear_sum_assignment
from ...utils.validation import check_consistent_length, check_array
__all__ = ["consensus_score"]
def _check_rows_and_columns(a, b): """Unpacks the row and column arrays and checks their shape.""" check_consistent_length(*a) check_consistent_length(*b) checks = lambda x: check_array(x, ensure_2d=False) a_rows, a_cols = map(checks, a) b_rows, b_cols = map(checks, b) return a_rows, a_cols, b_rows, b_cols
def _jaccard(a_rows, a_cols, b_rows, b_cols): """Jaccard coefficient on the elements of the two biclusters.""" intersection = (a_rows * b_rows).sum() * (a_cols * b_cols).sum()
a_size = a_rows.sum() * a_cols.sum() b_size = b_rows.sum() * b_cols.sum()
return intersection / (a_size + b_size - intersection)
def _pairwise_similarity(a, b, similarity): """Computes pairwise similarity matrix.
result[i, j] is the Jaccard coefficient of a's bicluster i and b's bicluster j.
""" a_rows, a_cols, b_rows, b_cols = _check_rows_and_columns(a, b) n_a = a_rows.shape[0] n_b = b_rows.shape[0] result = np.array( [ [similarity(a_rows[i], a_cols[i], b_rows[j], b_cols[j]) for j in range(n_b)] for i in range(n_a) ] ) return result
def consensus_score(a, b, *, similarity="jaccard"): """The similarity of two sets of biclusters.
Similarity between individual biclusters is computed. Then the best matching between sets is found using the Hungarian algorithm. The final score is the sum of similarities divided by the size of the larger set.
Read more in the :ref:`User Guide <biclustering>`.
Parameters ---------- a : (rows, columns) Tuple of row and column indicators for a set of biclusters.
b : (rows, columns) Another set of biclusters like ``a``.
similarity : 'jaccard' or callable, default='jaccard' May be the string "jaccard" to use the Jaccard coefficient, or any function that takes four arguments, each of which is a 1d indicator vector: (a_rows, a_columns, b_rows, b_columns).
Returns ------- consensus_score : float Consensus score, a non-negative value, sum of similarities divided by size of larger set.
References ----------
* Hochreiter, Bodenhofer, et. al., 2010. `FABIA: factor analysis for bicluster acquisition <https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2881408/>`__. """ if similarity == "jaccard": similarity = _jaccard matrix = _pairwise_similarity(a, b, similarity) row_indices, col_indices = linear_sum_assignment(1.0 - matrix) n_a = len(a[0]) n_b = len(b[0]) return matrix[row_indices, col_indices].sum() / max(n_a, n_b)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176"""Utilities to evaluate the clustering performance of models.
Functions named as *_score return a scalar value to maximize: the higher thebetter."""
# Authors: Olivier Grisel <olivier.grisel@ensta.org># Wei LI <kuantkid@gmail.com># Diego Molla <dmolla-aliod@gmail.com># Arnaud Fouchet <foucheta@gmail.com># Thierry Guillemot <thierry.guillemot.work@gmail.com># Gregory Stupp <stuppie@gmail.com># Joel Nothman <joel.nothman@gmail.com># Arya McCarthy <arya@jhu.edu># Uwe F Mayer <uwe_f_mayer@yahoo.com># License: BSD 3 clause
import warningsfrom math import log
import numpy as npfrom scipy import sparse as sp
from ._expected_mutual_info_fast import expected_mutual_informationfrom ...utils.multiclass import type_of_targetfrom ...utils.validation import check_array, check_consistent_length
def check_clusterings(labels_true, labels_pred): """Check that the labels arrays are 1D and of same dimension.
Parameters ---------- labels_true : array-like of shape (n_samples,) The true labels.
labels_pred : array-like of shape (n_samples,) The predicted labels. """ labels_true = check_array( labels_true, ensure_2d=False, ensure_min_samples=0, dtype=None, )
labels_pred = check_array( labels_pred, ensure_2d=False, ensure_min_samples=0, dtype=None, )
type_label = type_of_target(labels_true) type_pred = type_of_target(labels_pred)
if "continuous" in (type_pred, type_label): msg = ( "Clustering metrics expects discrete values but received" f" {type_label} values for label, and {type_pred} values " "for target" ) warnings.warn(msg, UserWarning)
# input checks if labels_true.ndim != 1: raise ValueError("labels_true must be 1D: shape is %r" % (labels_true.shape,)) if labels_pred.ndim != 1: raise ValueError("labels_pred must be 1D: shape is %r" % (labels_pred.shape,)) check_consistent_length(labels_true, labels_pred)
return labels_true, labels_pred
def _generalized_average(U, V, average_method): """Return a particular mean of two numbers.""" if average_method == "min": return min(U, V) elif average_method == "geometric": return np.sqrt(U * V) elif average_method == "arithmetic": return np.mean([U, V]) elif average_method == "max": return max(U, V) else: raise ValueError( "'average_method' must be 'min', 'geometric', 'arithmetic', or 'max'" )
def contingency_matrix( labels_true, labels_pred, *, eps=None, sparse=False, dtype=np.int64): """Build a contingency matrix describing the relationship between labels.
Parameters ---------- labels_true : int array, shape = [n_samples] Ground truth class labels to be used as a reference.
labels_pred : array-like of shape (n_samples,) Cluster labels to evaluate.
eps : float, default=None If a float, that value is added to all values in the contingency matrix. This helps to stop NaN propagation. If ``None``, nothing is adjusted.
sparse : bool, default=False If `True`, return a sparse CSR continency matrix. If `eps` is not `None` and `sparse` is `True` will raise ValueError.
.. versionadded:: 0.18
dtype : numeric type, default=np.int64 Output dtype. Ignored if `eps` is not `None`.
.. versionadded:: 0.24
Returns ------- contingency : {array-like, sparse}, shape=[n_classes_true, n_classes_pred] Matrix :math:`C` such that :math:`C_{i, j}` is the number of samples in true class :math:`i` and in predicted class :math:`j`. If ``eps is None``, the dtype of this array will be integer unless set otherwise with the ``dtype`` argument. If ``eps`` is given, the dtype will be float. Will be a ``sklearn.sparse.csr_matrix`` if ``sparse=True``. """
if eps is not None and sparse: raise ValueError("Cannot set 'eps' when sparse=True")
classes, class_idx = np.unique(labels_true, return_inverse=True) clusters, cluster_idx = np.unique(labels_pred, return_inverse=True) n_classes = classes.shape[0] n_clusters = clusters.shape[0] # Using coo_matrix to accelerate simple histogram calculation, # i.e. bins are consecutive integers # Currently, coo_matrix is faster than histogram2d for simple cases contingency = sp.coo_matrix( (np.ones(class_idx.shape[0]), (class_idx, cluster_idx)), shape=(n_classes, n_clusters), dtype=dtype, ) if sparse: contingency = contingency.tocsr() contingency.sum_duplicates() else: contingency = contingency.toarray() if eps is not None: # don't use += as contingency is integer contingency = contingency + eps return contingency
# clustering measures
def pair_confusion_matrix(labels_true, labels_pred): """Pair confusion matrix arising from two clusterings [1]_.
The pair confusion matrix :math:`C` computes a 2 by 2 similarity matrix between two clusterings by considering all pairs of samples and counting pairs that are assigned into the same or into different clusters under the true and predicted clusterings.
Considering a pair of samples that is clustered together a positive pair, then as in binary classification the count of true negatives is :math:`C_{00}`, false negatives is :math:`C_{10}`, true positives is :math:`C_{11}` and false positives is :math:`C_{01}`.
Read more in the :ref:`User Guide <pair_confusion_matrix>`.
Parameters ---------- labels_true : array-like of shape (n_samples,), dtype=integral Ground truth class labels to be used as a reference.
labels_pred : array-like of shape (n_samples,), dtype=integral Cluster labels to evaluate.
Returns ------- C : ndarray of shape (2, 2), dtype=np.int64 The contingency matrix.
See Also -------- rand_score: Rand Score. adjusted_rand_score: Adjusted Rand Score. adjusted_mutual_info_score: Adjusted Mutual Information.
References ---------- .. [1] :doi:`Hubert, L., Arabie, P. "Comparing partitions." Journal of Classification 2, 193–218 (1985). <10.1007/BF01908075>`
Examples -------- Perfectly matching labelings have all non-zero entries on the diagonal regardless of actual label values:
>>> from sklearn.metrics.cluster import pair_confusion_matrix >>> pair_confusion_matrix([0, 0, 1, 1], [1, 1, 0, 0]) array([[8, 0], [0, 4]]...
Labelings that assign all classes members to the same clusters are complete but may be not always pure, hence penalized, and have some off-diagonal non-zero entries:
>>> pair_confusion_matrix([0, 0, 1, 2], [0, 0, 1, 1]) array([[8, 2], [0, 2]]...
Note that the matrix is not symmetric. """ labels_true, labels_pred = check_clusterings(labels_true, labels_pred) n_samples = np.int64(labels_true.shape[0])
# Computation using the contingency data contingency = contingency_matrix( labels_true, labels_pred, sparse=True, dtype=np.int64 ) n_c = np.ravel(contingency.sum(axis=1)) n_k = np.ravel(contingency.sum(axis=0)) sum_squares = (contingency.data**2).sum() C = np.empty((2, 2), dtype=np.int64) C[1, 1] = sum_squares - n_samples C[0, 1] = contingency.dot(n_k).sum() - sum_squares C[1, 0] = contingency.transpose().dot(n_c).sum() - sum_squares C[0, 0] = n_samples**2 - C[0, 1] - C[1, 0] - sum_squares return C
def rand_score(labels_true, labels_pred): """Rand index.
The Rand Index computes a similarity measure between two clusterings by considering all pairs of samples and counting pairs that are assigned in the same or different clusters in the predicted and true clusterings [1]_ [2]_.
The raw RI score [3]_ is:
RI = (number of agreeing pairs) / (number of pairs)
Read more in the :ref:`User Guide <rand_score>`.
Parameters ---------- labels_true : array-like of shape (n_samples,), dtype=integral Ground truth class labels to be used as a reference.
labels_pred : array-like of shape (n_samples,), dtype=integral Cluster labels to evaluate.
Returns ------- RI : float Similarity score between 0.0 and 1.0, inclusive, 1.0 stands for perfect match.
See Also -------- adjusted_rand_score: Adjusted Rand Score. adjusted_mutual_info_score: Adjusted Mutual Information.
References ---------- .. [1] :doi:`Hubert, L., Arabie, P. "Comparing partitions." Journal of Classification 2, 193–218 (1985). <10.1007/BF01908075>`.
.. [2] `Wikipedia: Simple Matching Coefficient <https://en.wikipedia.org/wiki/Simple_matching_coefficient>`_
.. [3] `Wikipedia: Rand Index <https://en.wikipedia.org/wiki/Rand_index>`_
Examples -------- Perfectly matching labelings have a score of 1 even
>>> from sklearn.metrics.cluster import rand_score >>> rand_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0
Labelings that assign all classes members to the same clusters are complete but may not always be pure, hence penalized:
>>> rand_score([0, 0, 1, 2], [0, 0, 1, 1]) 0.83... """ contingency = pair_confusion_matrix(labels_true, labels_pred) numerator = contingency.diagonal().sum() denominator = contingency.sum()
if numerator == denominator or denominator == 0: # Special limit cases: no clustering since the data is not split; # or trivial clustering where each document is assigned a unique # cluster. These are perfect matches hence return 1.0. return 1.0
return numerator / denominator
def adjusted_rand_score(labels_true, labels_pred): """Rand index adjusted for chance.
The Rand Index computes a similarity measure between two clusterings by considering all pairs of samples and counting pairs that are assigned in the same or different clusters in the predicted and true clusterings.
The raw RI score is then "adjusted for chance" into the ARI score using the following scheme::
ARI = (RI - Expected_RI) / (max(RI) - Expected_RI)
The adjusted Rand index is thus ensured to have a value close to 0.0 for random labeling independently of the number of clusters and samples and exactly 1.0 when the clusterings are identical (up to a permutation). The adjusted Rand index is bounded below by -0.5 for especially discordant clusterings.
ARI is a symmetric measure::
adjusted_rand_score(a, b) == adjusted_rand_score(b, a)
Read more in the :ref:`User Guide <adjusted_rand_score>`.
Parameters ---------- labels_true : int array, shape = [n_samples] Ground truth class labels to be used as a reference.
labels_pred : array-like of shape (n_samples,) Cluster labels to evaluate.
Returns ------- ARI : float Similarity score between -0.5 and 1.0. Random labelings have an ARI close to 0.0. 1.0 stands for perfect match.
See Also -------- adjusted_mutual_info_score : Adjusted Mutual Information.
References ---------- .. [Hubert1985] L. Hubert and P. Arabie, Comparing Partitions, Journal of Classification 1985 https://link.springer.com/article/10.1007%2FBF01908075
.. [Steinley2004] D. Steinley, Properties of the Hubert-Arabie adjusted Rand index, Psychological Methods 2004
.. [wk] https://en.wikipedia.org/wiki/Rand_index#Adjusted_Rand_index
.. [Chacon] :doi:`Minimum adjusted Rand index for two clusterings of a given size, 2022, J. E. Chacón and A. I. Rastrojo <10.1007/s11634-022-00491-w>`
Examples -------- Perfectly matching labelings have a score of 1 even
>>> from sklearn.metrics.cluster import adjusted_rand_score >>> adjusted_rand_score([0, 0, 1, 1], [0, 0, 1, 1]) 1.0 >>> adjusted_rand_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0
Labelings that assign all classes members to the same clusters are complete but may not always be pure, hence penalized::
>>> adjusted_rand_score([0, 0, 1, 2], [0, 0, 1, 1]) 0.57...
ARI is symmetric, so labelings that have pure clusters with members coming from the same classes but unnecessary splits are penalized::
>>> adjusted_rand_score([0, 0, 1, 1], [0, 0, 1, 2]) 0.57...
If classes members are completely split across different clusters, the assignment is totally incomplete, hence the ARI is very low::
>>> adjusted_rand_score([0, 0, 0, 0], [0, 1, 2, 3]) 0.0
ARI may take a negative value for especially discordant labelings that are a worse choice than the expected value of random labels::
>>> adjusted_rand_score([0, 0, 1, 1], [0, 1, 0, 1]) -0.5 """ (tn, fp), (fn, tp) = pair_confusion_matrix(labels_true, labels_pred) # convert to Python integer types, to avoid overflow or underflow tn, fp, fn, tp = int(tn), int(fp), int(fn), int(tp)
# Special cases: empty data or full agreement if fn == 0 and fp == 0: return 1.0
return 2.0 * (tp * tn - fn * fp) / ((tp + fn) * (fn + tn) + (tp + fp) * (fp + tn))
def homogeneity_completeness_v_measure(labels_true, labels_pred, *, beta=1.0): """Compute the homogeneity and completeness and V-Measure scores at once.
Those metrics are based on normalized conditional entropy measures of the clustering labeling to evaluate given the knowledge of a Ground Truth class labels of the same samples.
A clustering result satisfies homogeneity if all of its clusters contain only data points which are members of a single class.
A clustering result satisfies completeness if all the data points that are members of a given class are elements of the same cluster.
Both scores have positive values between 0.0 and 1.0, larger values being desirable.
Those 3 metrics are independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score values in any way.
V-Measure is furthermore symmetric: swapping ``labels_true`` and ``label_pred`` will give the same score. This does not hold for homogeneity and completeness. V-Measure is identical to :func:`normalized_mutual_info_score` with the arithmetic averaging method.
Read more in the :ref:`User Guide <homogeneity_completeness>`.
Parameters ---------- labels_true : int array, shape = [n_samples] Ground truth class labels to be used as a reference.
labels_pred : array-like of shape (n_samples,) Gluster labels to evaluate.
beta : float, default=1.0 Ratio of weight attributed to ``homogeneity`` vs ``completeness``. If ``beta`` is greater than 1, ``completeness`` is weighted more strongly in the calculation. If ``beta`` is less than 1, ``homogeneity`` is weighted more strongly.
Returns ------- homogeneity : float Score between 0.0 and 1.0. 1.0 stands for perfectly homogeneous labeling.
completeness : float Score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling.
v_measure : float Harmonic mean of the first two.
See Also -------- homogeneity_score : Homogeneity metric of cluster labeling. completeness_score : Completeness metric of cluster labeling. v_measure_score : V-Measure (NMI with arithmetic mean option). """ labels_true, labels_pred = check_clusterings(labels_true, labels_pred)
if len(labels_true) == 0: return 1.0, 1.0, 1.0
entropy_C = entropy(labels_true) entropy_K = entropy(labels_pred)
contingency = contingency_matrix(labels_true, labels_pred, sparse=True) MI = mutual_info_score(None, None, contingency=contingency)
homogeneity = MI / (entropy_C) if entropy_C else 1.0 completeness = MI / (entropy_K) if entropy_K else 1.0
if homogeneity + completeness == 0.0: v_measure_score = 0.0 else: v_measure_score = ( (1 + beta) * homogeneity * completeness / (beta * homogeneity + completeness) )
return homogeneity, completeness, v_measure_score
def homogeneity_score(labels_true, labels_pred): """Homogeneity metric of a cluster labeling given a ground truth.
A clustering result satisfies homogeneity if all of its clusters contain only data points which are members of a single class.
This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way.
This metric is not symmetric: switching ``label_true`` with ``label_pred`` will return the :func:`completeness_score` which will be different in general.
Read more in the :ref:`User Guide <homogeneity_completeness>`.
Parameters ---------- labels_true : int array, shape = [n_samples] Ground truth class labels to be used as a reference.
labels_pred : array-like of shape (n_samples,) Cluster labels to evaluate.
Returns ------- homogeneity : float Score between 0.0 and 1.0. 1.0 stands for perfectly homogeneous labeling.
See Also -------- completeness_score : Completeness metric of cluster labeling. v_measure_score : V-Measure (NMI with arithmetic mean option).
References ----------
.. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A conditional entropy-based external cluster evaluation measure <https://aclweb.org/anthology/D/D07/D07-1043.pdf>`_
Examples --------
Perfect labelings are homogeneous::
>>> from sklearn.metrics.cluster import homogeneity_score >>> homogeneity_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0
Non-perfect labelings that further split classes into more clusters can be perfectly homogeneous::
>>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 0, 1, 2])) 1.000000 >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 1, 2, 3])) 1.000000
Clusters that include samples from different classes do not make for an homogeneous labeling::
>>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 1, 0, 1])) 0.0... >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 0, 0, 0])) 0.0... """ return homogeneity_completeness_v_measure(labels_true, labels_pred)[0]
def completeness_score(labels_true, labels_pred): """Compute completeness metric of a cluster labeling given a ground truth.
A clustering result satisfies completeness if all the data points that are members of a given class are elements of the same cluster.
This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way.
This metric is not symmetric: switching ``label_true`` with ``label_pred`` will return the :func:`homogeneity_score` which will be different in general.
Read more in the :ref:`User Guide <homogeneity_completeness>`.
Parameters ---------- labels_true : int array, shape = [n_samples] Ground truth class labels to be used as a reference.
labels_pred : array-like of shape (n_samples,) Cluster labels to evaluate.
Returns ------- completeness : float Score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling.
See Also -------- homogeneity_score : Homogeneity metric of cluster labeling. v_measure_score : V-Measure (NMI with arithmetic mean option).
References ----------
.. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A conditional entropy-based external cluster evaluation measure <https://aclweb.org/anthology/D/D07/D07-1043.pdf>`_
Examples --------
Perfect labelings are complete::
>>> from sklearn.metrics.cluster import completeness_score >>> completeness_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0
Non-perfect labelings that assign all classes members to the same clusters are still complete::
>>> print(completeness_score([0, 0, 1, 1], [0, 0, 0, 0])) 1.0 >>> print(completeness_score([0, 1, 2, 3], [0, 0, 1, 1])) 0.999...
If classes members are split across different clusters, the assignment cannot be complete::
>>> print(completeness_score([0, 0, 1, 1], [0, 1, 0, 1])) 0.0 >>> print(completeness_score([0, 0, 0, 0], [0, 1, 2, 3])) 0.0 """ return homogeneity_completeness_v_measure(labels_true, labels_pred)[1]
def v_measure_score(labels_true, labels_pred, *, beta=1.0): """V-measure cluster labeling given a ground truth.
This score is identical to :func:`normalized_mutual_info_score` with the ``'arithmetic'`` option for averaging.
The V-measure is the harmonic mean between homogeneity and completeness::
v = (1 + beta) * homogeneity * completeness / (beta * homogeneity + completeness)
This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way.
This metric is furthermore symmetric: switching ``label_true`` with ``label_pred`` will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known.
Read more in the :ref:`User Guide <homogeneity_completeness>`.
Parameters ---------- labels_true : int array, shape = [n_samples] Ground truth class labels to be used as a reference.
labels_pred : array-like of shape (n_samples,) Cluster labels to evaluate.
beta : float, default=1.0 Ratio of weight attributed to ``homogeneity`` vs ``completeness``. If ``beta`` is greater than 1, ``completeness`` is weighted more strongly in the calculation. If ``beta`` is less than 1, ``homogeneity`` is weighted more strongly.
Returns ------- v_measure : float Score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling.
See Also -------- homogeneity_score : Homogeneity metric of cluster labeling. completeness_score : Completeness metric of cluster labeling. normalized_mutual_info_score : Normalized Mutual Information.
References ----------
.. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A conditional entropy-based external cluster evaluation measure <https://aclweb.org/anthology/D/D07/D07-1043.pdf>`_
Examples -------- Perfect labelings are both homogeneous and complete, hence have score 1.0::
>>> from sklearn.metrics.cluster import v_measure_score >>> v_measure_score([0, 0, 1, 1], [0, 0, 1, 1]) 1.0 >>> v_measure_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0
Labelings that assign all classes members to the same clusters are complete but not homogeneous, hence penalized::
>>> print("%.6f" % v_measure_score([0, 0, 1, 2], [0, 0, 1, 1])) 0.8... >>> print("%.6f" % v_measure_score([0, 1, 2, 3], [0, 0, 1, 1])) 0.66...
Labelings that have pure clusters with members coming from the same classes are homogeneous but un-necessary splits harm completeness and thus penalize V-measure as well::
>>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 0, 1, 2])) 0.8... >>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 1, 2, 3])) 0.66...
If classes members are completely split across different clusters, the assignment is totally incomplete, hence the V-Measure is null::
>>> print("%.6f" % v_measure_score([0, 0, 0, 0], [0, 1, 2, 3])) 0.0...
Clusters that include samples from totally different classes totally destroy the homogeneity of the labeling, hence::
>>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 0, 0, 0])) 0.0... """ return homogeneity_completeness_v_measure(labels_true, labels_pred, beta=beta)[2]
def mutual_info_score(labels_true, labels_pred, *, contingency=None): """Mutual Information between two clusterings.
The Mutual Information is a measure of the similarity between two labels of the same data. Where :math:`|U_i|` is the number of the samples in cluster :math:`U_i` and :math:`|V_j|` is the number of the samples in cluster :math:`V_j`, the Mutual Information between clusterings :math:`U` and :math:`V` is given as:
.. math::
MI(U,V)=\\sum_{i=1}^{|U|} \\sum_{j=1}^{|V|} \\frac{|U_i\\cap V_j|}{N} \\log\\frac{N|U_i \\cap V_j|}{|U_i||V_j|}
This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way.
This metric is furthermore symmetric: switching :math:`U` (i.e ``label_true``) with :math:`V` (i.e. ``label_pred``) will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known.
Read more in the :ref:`User Guide <mutual_info_score>`.
Parameters ---------- labels_true : int array, shape = [n_samples] A clustering of the data into disjoint subsets, called :math:`U` in the above formula.
labels_pred : int array-like of shape (n_samples,) A clustering of the data into disjoint subsets, called :math:`V` in the above formula.
contingency : {ndarray, sparse matrix} of shape \ (n_classes_true, n_classes_pred), default=None A contingency matrix given by the :func:`contingency_matrix` function. If value is ``None``, it will be computed, otherwise the given value is used, with ``labels_true`` and ``labels_pred`` ignored.
Returns ------- mi : float Mutual information, a non-negative value, measured in nats using the natural logarithm.
See Also -------- adjusted_mutual_info_score : Adjusted against chance Mutual Information. normalized_mutual_info_score : Normalized Mutual Information.
Notes ----- The logarithm used is the natural logarithm (base-e). """ if contingency is None: labels_true, labels_pred = check_clusterings(labels_true, labels_pred) contingency = contingency_matrix(labels_true, labels_pred, sparse=True) else: contingency = check_array( contingency, accept_sparse=["csr", "csc", "coo"], dtype=[int, np.int32, np.int64], )
if isinstance(contingency, np.ndarray): # For an array nzx, nzy = np.nonzero(contingency) nz_val = contingency[nzx, nzy] elif sp.issparse(contingency): # For a sparse matrix nzx, nzy, nz_val = sp.find(contingency) else: raise ValueError("Unsupported type for 'contingency': %s" % type(contingency))
contingency_sum = contingency.sum() pi = np.ravel(contingency.sum(axis=1)) pj = np.ravel(contingency.sum(axis=0))
# Since MI <= min(H(X), H(Y)), any labelling with zero entropy, i.e. containing a # single cluster, implies MI = 0 if pi.size == 1 or pj.size == 1: return 0.0
log_contingency_nm = np.log(nz_val) contingency_nm = nz_val / contingency_sum # Don't need to calculate the full outer product, just for non-zeroes outer = pi.take(nzx).astype(np.int64, copy=False) * pj.take(nzy).astype( np.int64, copy=False ) log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum()) mi = ( contingency_nm * (log_contingency_nm - log(contingency_sum)) + contingency_nm * log_outer ) mi = np.where(np.abs(mi) < np.finfo(mi.dtype).eps, 0.0, mi) return np.clip(mi.sum(), 0.0, None)
def adjusted_mutual_info_score( labels_true, labels_pred, *, average_method="arithmetic"): """Adjusted Mutual Information between two clusterings.
Adjusted Mutual Information (AMI) is an adjustment of the Mutual Information (MI) score to account for chance. It accounts for the fact that the MI is generally higher for two clusterings with a larger number of clusters, regardless of whether there is actually more information shared. For two clusterings :math:`U` and :math:`V`, the AMI is given as::
AMI(U, V) = [MI(U, V) - E(MI(U, V))] / [avg(H(U), H(V)) - E(MI(U, V))]
This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way.
This metric is furthermore symmetric: switching :math:`U` (``label_true``) with :math:`V` (``labels_pred``) will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known.
Be mindful that this function is an order of magnitude slower than other metrics, such as the Adjusted Rand Index.
Read more in the :ref:`User Guide <mutual_info_score>`.
Parameters ---------- labels_true : int array, shape = [n_samples] A clustering of the data into disjoint subsets, called :math:`U` in the above formula.
labels_pred : int array-like of shape (n_samples,) A clustering of the data into disjoint subsets, called :math:`V` in the above formula.
average_method : str, default='arithmetic' How to compute the normalizer in the denominator. Possible options are 'min', 'geometric', 'arithmetic', and 'max'.
.. versionadded:: 0.20
.. versionchanged:: 0.22 The default value of ``average_method`` changed from 'max' to 'arithmetic'.
Returns ------- ami: float (upperlimited by 1.0) The AMI returns a value of 1 when the two partitions are identical (ie perfectly matched). Random partitions (independent labellings) have an expected AMI around 0 on average hence can be negative. The value is in adjusted nats (based on the natural logarithm).
See Also -------- adjusted_rand_score : Adjusted Rand Index. mutual_info_score : Mutual Information (not adjusted for chance).
References ---------- .. [1] `Vinh, Epps, and Bailey, (2010). Information Theoretic Measures for Clusterings Comparison: Variants, Properties, Normalization and Correction for Chance, JMLR <http://jmlr.csail.mit.edu/papers/volume11/vinh10a/vinh10a.pdf>`_
.. [2] `Wikipedia entry for the Adjusted Mutual Information <https://en.wikipedia.org/wiki/Adjusted_Mutual_Information>`_
Examples --------
Perfect labelings are both homogeneous and complete, hence have score 1.0::
>>> from sklearn.metrics.cluster import adjusted_mutual_info_score >>> adjusted_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1]) ... # doctest: +SKIP 1.0 >>> adjusted_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0]) ... # doctest: +SKIP 1.0
If classes members are completely split across different clusters, the assignment is totally in-complete, hence the AMI is null::
>>> adjusted_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3]) ... # doctest: +SKIP 0.0 """ labels_true, labels_pred = check_clusterings(labels_true, labels_pred) n_samples = labels_true.shape[0] classes = np.unique(labels_true) clusters = np.unique(labels_pred)
# Special limit cases: no clustering since the data is not split. # It corresponds to both labellings having zero entropy. # This is a perfect match hence return 1.0. if ( classes.shape[0] == clusters.shape[0] == 1 or classes.shape[0] == clusters.shape[0] == 0 ): return 1.0
contingency = contingency_matrix(labels_true, labels_pred, sparse=True) contingency = contingency.astype(np.float64, copy=False) # Calculate the MI for the two clusterings mi = mutual_info_score(labels_true, labels_pred, contingency=contingency) # Calculate the expected value for the mutual information emi = expected_mutual_information(contingency, n_samples) # Calculate entropy for each labeling h_true, h_pred = entropy(labels_true), entropy(labels_pred) normalizer = _generalized_average(h_true, h_pred, average_method) denominator = normalizer - emi # Avoid 0.0 / 0.0 when expectation equals maximum, i.e a perfect match. # normalizer should always be >= emi, but because of floating-point # representation, sometimes emi is slightly larger. Correct this # by preserving the sign. if denominator < 0: denominator = min(denominator, -np.finfo("float64").eps) else: denominator = max(denominator, np.finfo("float64").eps) ami = (mi - emi) / denominator return ami
def normalized_mutual_info_score( labels_true, labels_pred, *, average_method="arithmetic"): """Normalized Mutual Information between two clusterings.
Normalized Mutual Information (NMI) is a normalization of the Mutual Information (MI) score to scale the results between 0 (no mutual information) and 1 (perfect correlation). In this function, mutual information is normalized by some generalized mean of ``H(labels_true)`` and ``H(labels_pred))``, defined by the `average_method`.
This measure is not adjusted for chance. Therefore :func:`adjusted_mutual_info_score` might be preferred.
This metric is independent of the absolute values of the labels: a permutation of the class or cluster label values won't change the score value in any way.
This metric is furthermore symmetric: switching ``label_true`` with ``label_pred`` will return the same score value. This can be useful to measure the agreement of two independent label assignments strategies on the same dataset when the real ground truth is not known.
Read more in the :ref:`User Guide <mutual_info_score>`.
Parameters ---------- labels_true : int array, shape = [n_samples] A clustering of the data into disjoint subsets.
labels_pred : int array-like of shape (n_samples,) A clustering of the data into disjoint subsets.
average_method : str, default='arithmetic' How to compute the normalizer in the denominator. Possible options are 'min', 'geometric', 'arithmetic', and 'max'.
.. versionadded:: 0.20
.. versionchanged:: 0.22 The default value of ``average_method`` changed from 'geometric' to 'arithmetic'.
Returns ------- nmi : float Score between 0.0 and 1.0 in normalized nats (based on the natural logarithm). 1.0 stands for perfectly complete labeling.
See Also -------- v_measure_score : V-Measure (NMI with arithmetic mean option). adjusted_rand_score : Adjusted Rand Index. adjusted_mutual_info_score : Adjusted Mutual Information (adjusted against chance).
Examples --------
Perfect labelings are both homogeneous and complete, hence have score 1.0::
>>> from sklearn.metrics.cluster import normalized_mutual_info_score >>> normalized_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1]) ... # doctest: +SKIP 1.0 >>> normalized_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0]) ... # doctest: +SKIP 1.0
If classes members are completely split across different clusters, the assignment is totally in-complete, hence the NMI is null::
>>> normalized_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3]) ... # doctest: +SKIP 0.0 """ labels_true, labels_pred = check_clusterings(labels_true, labels_pred) classes = np.unique(labels_true) clusters = np.unique(labels_pred)
# Special limit cases: no clustering since the data is not split. # It corresponds to both labellings having zero entropy. # This is a perfect match hence return 1.0. if ( classes.shape[0] == clusters.shape[0] == 1 or classes.shape[0] == clusters.shape[0] == 0 ): return 1.0
contingency = contingency_matrix(labels_true, labels_pred, sparse=True) contingency = contingency.astype(np.float64, copy=False) # Calculate the MI for the two clusterings mi = mutual_info_score(labels_true, labels_pred, contingency=contingency)
# At this point mi = 0 can't be a perfect match (the special case of a single # cluster has been dealt with before). Hence, if mi = 0, the nmi must be 0 whatever # the normalization. if mi == 0: return 0.0
# Calculate entropy for each labeling h_true, h_pred = entropy(labels_true), entropy(labels_pred)
normalizer = _generalized_average(h_true, h_pred, average_method) return mi / normalizer
def fowlkes_mallows_score(labels_true, labels_pred, *, sparse=False): """Measure the similarity of two clusterings of a set of points.
.. versionadded:: 0.18
The Fowlkes-Mallows index (FMI) is defined as the geometric mean between of the precision and recall::
FMI = TP / sqrt((TP + FP) * (TP + FN))
Where ``TP`` is the number of **True Positive** (i.e. the number of pair of points that belongs in the same clusters in both ``labels_true`` and ``labels_pred``), ``FP`` is the number of **False Positive** (i.e. the number of pair of points that belongs in the same clusters in ``labels_true`` and not in ``labels_pred``) and ``FN`` is the number of **False Negative** (i.e the number of pair of points that belongs in the same clusters in ``labels_pred`` and not in ``labels_True``).
The score ranges from 0 to 1. A high value indicates a good similarity between two clusters.
Read more in the :ref:`User Guide <fowlkes_mallows_scores>`.
Parameters ---------- labels_true : int array, shape = (``n_samples``,) A clustering of the data into disjoint subsets.
labels_pred : array, shape = (``n_samples``, ) A clustering of the data into disjoint subsets.
sparse : bool, default=False Compute contingency matrix internally with sparse matrix.
Returns ------- score : float The resulting Fowlkes-Mallows score.
References ---------- .. [1] `E. B. Fowkles and C. L. Mallows, 1983. "A method for comparing two hierarchical clusterings". Journal of the American Statistical Association <https://www.tandfonline.com/doi/abs/10.1080/01621459.1983.10478008>`_
.. [2] `Wikipedia entry for the Fowlkes-Mallows Index <https://en.wikipedia.org/wiki/Fowlkes-Mallows_index>`_
Examples --------
Perfect labelings are both homogeneous and complete, hence have score 1.0::
>>> from sklearn.metrics.cluster import fowlkes_mallows_score >>> fowlkes_mallows_score([0, 0, 1, 1], [0, 0, 1, 1]) 1.0 >>> fowlkes_mallows_score([0, 0, 1, 1], [1, 1, 0, 0]) 1.0
If classes members are completely split across different clusters, the assignment is totally random, hence the FMI is null::
>>> fowlkes_mallows_score([0, 0, 0, 0], [0, 1, 2, 3]) 0.0 """ labels_true, labels_pred = check_clusterings(labels_true, labels_pred) (n_samples,) = labels_true.shape
c = contingency_matrix(labels_true, labels_pred, sparse=True) c = c.astype(np.int64, copy=False) tk = np.dot(c.data, c.data) - n_samples pk = np.sum(np.asarray(c.sum(axis=0)).ravel() ** 2) - n_samples qk = np.sum(np.asarray(c.sum(axis=1)).ravel() ** 2) - n_samples return np.sqrt(tk / pk) * np.sqrt(tk / qk) if tk != 0.0 else 0.0
def entropy(labels): """Calculate the entropy for a labeling.
Parameters ---------- labels : array-like of shape (n_samples,), dtype=int The labels.
Returns ------- entropy : float The entropy for a labeling.
Notes ----- The logarithm used is the natural logarithm (base-e). """ if len(labels) == 0: return 1.0 label_idx = np.unique(labels, return_inverse=True)[1] pi = np.bincount(label_idx).astype(np.float64) pi = pi[pi > 0]
# single cluster => zero entropy if pi.size == 1: return 0.0
pi_sum = np.sum(pi) # log(a / b) should be calculated as log(a) - log(b) for # possible loss of precision return -np.sum((pi / pi_sum) * (np.log(pi) - log(pi_sum)))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366"""Unsupervised evaluation metrics."""
# Authors: Robert Layton <robertlayton@gmail.com># Arnaud Fouchet <foucheta@gmail.com># Thierry Guillemot <thierry.guillemot.work@gmail.com># License: BSD 3 clause
import functools
import numpy as np
from ...utils import check_random_statefrom ...utils import check_X_yfrom ...utils import _safe_indexingfrom ..pairwise import pairwise_distances_chunkedfrom ..pairwise import pairwise_distancesfrom ...preprocessing import LabelEncoder
def check_number_of_labels(n_labels, n_samples): """Check that number of labels are valid.
Parameters ---------- n_labels : int Number of labels.
n_samples : int Number of samples. """ if not 1 < n_labels < n_samples: raise ValueError( "Number of labels is %d. Valid values are 2 to n_samples - 1 (inclusive)" % n_labels )
def silhouette_score( X, labels, *, metric="euclidean", sample_size=None, random_state=None, **kwds): """Compute the mean Silhouette Coefficient of all samples.
The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b``) for each sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. To clarify, ``b`` is the distance between a sample and the nearest cluster that the sample is not a part of. Note that Silhouette Coefficient is only defined if number of labels is ``2 <= n_labels <= n_samples - 1``.
This function returns the mean Silhouette Coefficient over all samples. To obtain the values for each sample, use :func:`silhouette_samples`.
The best value is 1 and the worst value is -1. Values near 0 indicate overlapping clusters. Negative values generally indicate that a sample has been assigned to the wrong cluster, as a different cluster is more similar.
Read more in the :ref:`User Guide <silhouette_coefficient>`.
Parameters ---------- X : array-like of shape (n_samples_a, n_samples_a) if metric == \ "precomputed" or (n_samples_a, n_features) otherwise An array of pairwise distances between samples, or a feature array.
labels : array-like of shape (n_samples,) Predicted labels for each sample.
metric : str or callable, default='euclidean' The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by :func:`metrics.pairwise.pairwise_distances <sklearn.metrics.pairwise.pairwise_distances>`. If ``X`` is the distance array itself, use ``metric="precomputed"``.
sample_size : int, default=None The size of the sample to use when computing the Silhouette Coefficient on a random subset of the data. If ``sample_size is None``, no sampling is used.
random_state : int, RandomState instance or None, default=None Determines random number generation for selecting a subset of samples. Used when ``sample_size is not None``. Pass an int for reproducible results across multiple function calls. See :term:`Glossary <random_state>`.
**kwds : optional keyword parameters Any further parameters are passed directly to the distance function. If using a scipy.spatial.distance metric, the parameters are still metric dependent. See the scipy docs for usage examples.
Returns ------- silhouette : float Mean Silhouette Coefficient for all samples.
References ----------
.. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the Interpretation and Validation of Cluster Analysis". Computational and Applied Mathematics 20: 53-65. <https://www.sciencedirect.com/science/article/pii/0377042787901257>`_
.. [2] `Wikipedia entry on the Silhouette Coefficient <https://en.wikipedia.org/wiki/Silhouette_(clustering)>`_ """ if sample_size is not None: X, labels = check_X_y(X, labels, accept_sparse=["csc", "csr"]) random_state = check_random_state(random_state) indices = random_state.permutation(X.shape[0])[:sample_size] if metric == "precomputed": X, labels = X[indices].T[indices].T, labels[indices] else: X, labels = X[indices], labels[indices] return np.mean(silhouette_samples(X, labels, metric=metric, **kwds))
def _silhouette_reduce(D_chunk, start, labels, label_freqs): """Accumulate silhouette statistics for vertical chunk of X.
Parameters ---------- D_chunk : array-like of shape (n_chunk_samples, n_samples) Precomputed distances for a chunk. start : int First index in the chunk. labels : array-like of shape (n_samples,) Corresponding cluster labels, encoded as {0, ..., n_clusters-1}. label_freqs : array-like Distribution of cluster labels in ``labels``. """ # accumulate distances from each sample to each cluster clust_dists = np.zeros((len(D_chunk), len(label_freqs)), dtype=D_chunk.dtype) for i in range(len(D_chunk)): clust_dists[i] += np.bincount( labels, weights=D_chunk[i], minlength=len(label_freqs) )
# intra_index selects intra-cluster distances within clust_dists intra_index = (np.arange(len(D_chunk)), labels[start : start + len(D_chunk)]) # intra_clust_dists are averaged over cluster size outside this function intra_clust_dists = clust_dists[intra_index] # of the remaining distances we normalise and extract the minimum clust_dists[intra_index] = np.inf clust_dists /= label_freqs inter_clust_dists = clust_dists.min(axis=1) return intra_clust_dists, inter_clust_dists
def silhouette_samples(X, labels, *, metric="euclidean", **kwds): """Compute the Silhouette Coefficient for each sample.
The Silhouette Coefficient is a measure of how well samples are clustered with samples that are similar to themselves. Clustering models with a high Silhouette Coefficient are said to be dense, where samples in the same cluster are similar to each other, and well separated, where samples in different clusters are not very similar to each other.
The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b``) for each sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, b)``. Note that Silhouette Coefficient is only defined if number of labels is 2 ``<= n_labels <= n_samples - 1``.
This function returns the Silhouette Coefficient for each sample.
The best value is 1 and the worst value is -1. Values near 0 indicate overlapping clusters.
Read more in the :ref:`User Guide <silhouette_coefficient>`.
Parameters ---------- X : array-like of shape (n_samples_a, n_samples_a) if metric == \ "precomputed" or (n_samples_a, n_features) otherwise An array of pairwise distances between samples, or a feature array.
labels : array-like of shape (n_samples,) Label values for each sample.
metric : str or callable, default='euclidean' The metric to use when calculating distance between instances in a feature array. If metric is a string, it must be one of the options allowed by :func:`sklearn.metrics.pairwise.pairwise_distances`. If ``X`` is the distance array itself, use "precomputed" as the metric. Precomputed distance matrices must have 0 along the diagonal.
**kwds : optional keyword parameters Any further parameters are passed directly to the distance function. If using a ``scipy.spatial.distance`` metric, the parameters are still metric dependent. See the scipy docs for usage examples.
Returns ------- silhouette : array-like of shape (n_samples,) Silhouette Coefficients for each sample.
References ----------
.. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the Interpretation and Validation of Cluster Analysis". Computational and Applied Mathematics 20: 53-65. <https://www.sciencedirect.com/science/article/pii/0377042787901257>`_
.. [2] `Wikipedia entry on the Silhouette Coefficient <https://en.wikipedia.org/wiki/Silhouette_(clustering)>`_ """ X, labels = check_X_y(X, labels, accept_sparse=["csc", "csr"])
# Check for non-zero diagonal entries in precomputed distance matrix if metric == "precomputed": error_msg = ValueError( "The precomputed distance matrix contains non-zero " "elements on the diagonal. Use np.fill_diagonal(X, 0)." ) if X.dtype.kind == "f": atol = np.finfo(X.dtype).eps * 100 if np.any(np.abs(np.diagonal(X)) > atol): raise ValueError(error_msg) elif np.any(np.diagonal(X) != 0): # integral dtype raise ValueError(error_msg)
le = LabelEncoder() labels = le.fit_transform(labels) n_samples = len(labels) label_freqs = np.bincount(labels) check_number_of_labels(len(le.classes_), n_samples)
kwds["metric"] = metric reduce_func = functools.partial( _silhouette_reduce, labels=labels, label_freqs=label_freqs ) results = zip(*pairwise_distances_chunked(X, reduce_func=reduce_func, **kwds)) intra_clust_dists, inter_clust_dists = results intra_clust_dists = np.concatenate(intra_clust_dists) inter_clust_dists = np.concatenate(inter_clust_dists)
denom = (label_freqs - 1).take(labels, mode="clip") with np.errstate(divide="ignore", invalid="ignore"): intra_clust_dists /= denom
sil_samples = inter_clust_dists - intra_clust_dists with np.errstate(divide="ignore", invalid="ignore"): sil_samples /= np.maximum(intra_clust_dists, inter_clust_dists) # nan values are for clusters of size 1, and should be 0 return np.nan_to_num(sil_samples)
def calinski_harabasz_score(X, labels): """Compute the Calinski and Harabasz score.
It is also known as the Variance Ratio Criterion.
The score is defined as ratio of the sum of between-cluster dispersion and of within-cluster dispersion.
Read more in the :ref:`User Guide <calinski_harabasz_index>`.
Parameters ---------- X : array-like of shape (n_samples, n_features) A list of ``n_features``-dimensional data points. Each row corresponds to a single data point.
labels : array-like of shape (n_samples,) Predicted labels for each sample.
Returns ------- score : float The resulting Calinski-Harabasz score.
References ---------- .. [1] `T. Calinski and J. Harabasz, 1974. "A dendrite method for cluster analysis". Communications in Statistics <https://www.tandfonline.com/doi/abs/10.1080/03610927408827101>`_ """ X, labels = check_X_y(X, labels) le = LabelEncoder() labels = le.fit_transform(labels)
n_samples, _ = X.shape n_labels = len(le.classes_)
check_number_of_labels(n_labels, n_samples)
extra_disp, intra_disp = 0.0, 0.0 mean = np.mean(X, axis=0) for k in range(n_labels): cluster_k = X[labels == k] mean_k = np.mean(cluster_k, axis=0) extra_disp += len(cluster_k) * np.sum((mean_k - mean) ** 2) intra_disp += np.sum((cluster_k - mean_k) ** 2)
return ( 1.0 if intra_disp == 0.0 else extra_disp * (n_samples - n_labels) / (intra_disp * (n_labels - 1.0)) )
def davies_bouldin_score(X, labels): """Compute the Davies-Bouldin score.
The score is defined as the average similarity measure of each cluster with its most similar cluster, where similarity is the ratio of within-cluster distances to between-cluster distances. Thus, clusters which are farther apart and less dispersed will result in a better score.
The minimum score is zero, with lower values indicating better clustering.
Read more in the :ref:`User Guide <davies-bouldin_index>`.
.. versionadded:: 0.20
Parameters ---------- X : array-like of shape (n_samples, n_features) A list of ``n_features``-dimensional data points. Each row corresponds to a single data point.
labels : array-like of shape (n_samples,) Predicted labels for each sample.
Returns ------- score: float The resulting Davies-Bouldin score.
References ---------- .. [1] Davies, David L.; Bouldin, Donald W. (1979). `"A Cluster Separation Measure" <https://ieeexplore.ieee.org/document/4766909>`__. IEEE Transactions on Pattern Analysis and Machine Intelligence. PAMI-1 (2): 224-227 """ X, labels = check_X_y(X, labels) le = LabelEncoder() labels = le.fit_transform(labels) n_samples, _ = X.shape n_labels = len(le.classes_) check_number_of_labels(n_labels, n_samples)
intra_dists = np.zeros(n_labels) centroids = np.zeros((n_labels, len(X[0])), dtype=float) for k in range(n_labels): cluster_k = _safe_indexing(X, labels == k) centroid = cluster_k.mean(axis=0) centroids[k] = centroid intra_dists[k] = np.average(pairwise_distances(cluster_k, [centroid]))
centroid_distances = pairwise_distances(centroids)
if np.allclose(intra_dists, 0) or np.allclose(centroid_distances, 0): return 0.0
centroid_distances[centroid_distances == 0] = np.inf combined_intra_dists = intra_dists[:, None] + intra_dists scores = np.max(combined_intra_dists / centroid_distances, axis=1) return np.mean(scores)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662from functools import partialfrom itertools import productfrom itertools import chainfrom itertools import permutationsimport warningsimport re
import numpy as npfrom scipy import linalgfrom scipy.stats import bernoulliimport pytest
from sklearn import datasetsfrom sklearn import svm
from sklearn.datasets import make_multilabel_classificationfrom sklearn.preprocessing import label_binarize, LabelBinarizerfrom sklearn.utils.validation import check_random_statefrom sklearn.utils._testing import assert_almost_equalfrom sklearn.utils._testing import assert_array_equalfrom sklearn.utils._testing import assert_array_almost_equalfrom sklearn.utils._testing import assert_allclosefrom sklearn.utils._testing import assert_no_warningsfrom sklearn.utils._testing import ignore_warningsfrom sklearn.utils._mocking import MockDataFrame
from sklearn.metrics import accuracy_scorefrom sklearn.metrics import average_precision_scorefrom sklearn.metrics import balanced_accuracy_scorefrom sklearn.metrics import class_likelihood_ratiosfrom sklearn.metrics import classification_reportfrom sklearn.metrics import cohen_kappa_scorefrom sklearn.metrics import confusion_matrixfrom sklearn.metrics import f1_scorefrom sklearn.metrics import fbeta_scorefrom sklearn.metrics import hamming_lossfrom sklearn.metrics import hinge_lossfrom sklearn.metrics import jaccard_scorefrom sklearn.metrics import log_lossfrom sklearn.metrics import matthews_corrcoeffrom sklearn.metrics import precision_recall_fscore_supportfrom sklearn.metrics import precision_scorefrom sklearn.metrics import recall_scorefrom sklearn.metrics import zero_one_lossfrom sklearn.metrics import brier_score_lossfrom sklearn.metrics import multilabel_confusion_matrix
from sklearn.metrics._classification import _check_targetsfrom sklearn.exceptions import UndefinedMetricWarning
from scipy.spatial.distance import hamming as sp_hamming
################################################################################ Utilities for testing
def make_prediction(dataset=None, binary=False): """Make some classification predictions on a toy dataset using a SVC
If binary is True restrict to a binary classification problem instead of a multiclass classification problem """
if dataset is None: # import some data to play with dataset = datasets.load_iris()
X = dataset.data y = dataset.target
if binary: # restrict to a binary classification task X, y = X[y < 2], y[y < 2]
n_samples, n_features = X.shape p = np.arange(n_samples)
rng = check_random_state(37) rng.shuffle(p) X, y = X[p], y[p] half = int(n_samples / 2)
# add noisy features to make the problem harder and avoid perfect results rng = np.random.RandomState(0) X = np.c_[X, rng.randn(n_samples, 200 * n_features)]
# run classifier, get class probabilities and label predictions clf = svm.SVC(kernel="linear", probability=True, random_state=0) probas_pred = clf.fit(X[:half], y[:half]).predict_proba(X[half:])
if binary: # only interested in probabilities of the positive case # XXX: do we really want a special API for the binary case? probas_pred = probas_pred[:, 1]
y_pred = clf.predict(X[half:]) y_true = y[half:] return y_true, y_pred, probas_pred
################################################################################ Tests
def test_classification_report_dictionary_output():
# Test performance report with dictionary output iris = datasets.load_iris() y_true, y_pred, _ = make_prediction(dataset=iris, binary=False)
# print classification report with class names expected_report = { "setosa": { "precision": 0.82608695652173914, "recall": 0.79166666666666663, "f1-score": 0.8085106382978724, "support": 24, }, "versicolor": { "precision": 0.33333333333333331, "recall": 0.096774193548387094, "f1-score": 0.15000000000000002, "support": 31, }, "virginica": { "precision": 0.41860465116279072, "recall": 0.90000000000000002, "f1-score": 0.57142857142857151, "support": 20, }, "macro avg": { "f1-score": 0.5099797365754813, "precision": 0.5260083136726211, "recall": 0.596146953405018, "support": 75, }, "accuracy": 0.5333333333333333, "weighted avg": { "f1-score": 0.47310435663627154, "precision": 0.5137535108414785, "recall": 0.5333333333333333, "support": 75, }, }
report = classification_report( y_true, y_pred, labels=np.arange(len(iris.target_names)), target_names=iris.target_names, output_dict=True, )
# assert the 2 dicts are equal. assert report.keys() == expected_report.keys() for key in expected_report: if key == "accuracy": assert isinstance(report[key], float) assert report[key] == expected_report[key] else: assert report[key].keys() == expected_report[key].keys() for metric in expected_report[key]: assert_almost_equal(expected_report[key][metric], report[key][metric])
assert type(expected_report["setosa"]["precision"]) == float assert type(expected_report["macro avg"]["precision"]) == float assert type(expected_report["setosa"]["support"]) == int assert type(expected_report["macro avg"]["support"]) == int
def test_classification_report_output_dict_empty_input(): report = classification_report(y_true=[], y_pred=[], output_dict=True) expected_report = { "accuracy": 0.0, "macro avg": { "f1-score": np.nan, "precision": np.nan, "recall": np.nan, "support": 0, }, "weighted avg": { "f1-score": 0.0, "precision": 0.0, "recall": 0.0, "support": 0, }, } assert isinstance(report, dict) # assert the 2 dicts are equal. assert report.keys() == expected_report.keys() for key in expected_report: if key == "accuracy": assert isinstance(report[key], float) assert report[key] == expected_report[key] else: assert report[key].keys() == expected_report[key].keys() for metric in expected_report[key]: assert_almost_equal(expected_report[key][metric], report[key][metric])
@pytest.mark.parametrize("zero_division", ["warn", 0, 1])def test_classification_report_zero_division_warning(zero_division): y_true, y_pred = ["a", "b", "c"], ["a", "b", "d"] with warnings.catch_warnings(record=True) as record: classification_report( y_true, y_pred, zero_division=zero_division, output_dict=True ) if zero_division == "warn": assert len(record) > 1 for item in record: msg = "Use `zero_division` parameter to control this behavior." assert msg in str(item.message) else: assert not record
def test_multilabel_accuracy_score_subset_accuracy(): # Dense label indicator matrix format y1 = np.array([[0, 1, 1], [1, 0, 1]]) y2 = np.array([[0, 0, 1], [1, 0, 1]])
assert accuracy_score(y1, y2) == 0.5 assert accuracy_score(y1, y1) == 1 assert accuracy_score(y2, y2) == 1 assert accuracy_score(y2, np.logical_not(y2)) == 0 assert accuracy_score(y1, np.logical_not(y1)) == 0 assert accuracy_score(y1, np.zeros(y1.shape)) == 0 assert accuracy_score(y2, np.zeros(y1.shape)) == 0
def test_precision_recall_f1_score_binary(): # Test Precision Recall and F1 Score for binary classification task y_true, y_pred, _ = make_prediction(binary=True)
# detailed measures for each class p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) assert_array_almost_equal(p, [0.73, 0.85], 2) assert_array_almost_equal(r, [0.88, 0.68], 2) assert_array_almost_equal(f, [0.80, 0.76], 2) assert_array_equal(s, [25, 25])
# individual scoring function that can be used for grid search: in the # binary class case the score is the value of the measure for the positive # class (e.g. label == 1). This is deprecated for average != 'binary'. for kwargs, my_assert in [ ({}, assert_no_warnings), ({"average": "binary"}, assert_no_warnings), ]: ps = my_assert(precision_score, y_true, y_pred, **kwargs) assert_array_almost_equal(ps, 0.85, 2)
rs = my_assert(recall_score, y_true, y_pred, **kwargs) assert_array_almost_equal(rs, 0.68, 2)
fs = my_assert(f1_score, y_true, y_pred, **kwargs) assert_array_almost_equal(fs, 0.76, 2)
assert_almost_equal( my_assert(fbeta_score, y_true, y_pred, beta=2, **kwargs), (1 + 2**2) * ps * rs / (2**2 * ps + rs), 2, )
@ignore_warningsdef test_precision_recall_f_binary_single_class(): # Test precision, recall and F-scores behave with a single positive or # negative class # Such a case may occur with non-stratified cross-validation assert 1.0 == precision_score([1, 1], [1, 1]) assert 1.0 == recall_score([1, 1], [1, 1]) assert 1.0 == f1_score([1, 1], [1, 1]) assert 1.0 == fbeta_score([1, 1], [1, 1], beta=0)
assert 0.0 == precision_score([-1, -1], [-1, -1]) assert 0.0 == recall_score([-1, -1], [-1, -1]) assert 0.0 == f1_score([-1, -1], [-1, -1]) assert 0.0 == fbeta_score([-1, -1], [-1, -1], beta=float("inf")) assert fbeta_score([-1, -1], [-1, -1], beta=float("inf")) == pytest.approx( fbeta_score([-1, -1], [-1, -1], beta=1e5) )
@ignore_warningsdef test_precision_recall_f_extra_labels(): # Test handling of explicit additional (not in input) labels to PRF y_true = [1, 3, 3, 2] y_pred = [1, 1, 3, 2] y_true_bin = label_binarize(y_true, classes=np.arange(5)) y_pred_bin = label_binarize(y_pred, classes=np.arange(5)) data = [(y_true, y_pred), (y_true_bin, y_pred_bin)]
for i, (y_true, y_pred) in enumerate(data): # No average: zeros in array actual = recall_score(y_true, y_pred, labels=[0, 1, 2, 3, 4], average=None) assert_array_almost_equal([0.0, 1.0, 1.0, 0.5, 0.0], actual)
# Macro average is changed actual = recall_score(y_true, y_pred, labels=[0, 1, 2, 3, 4], average="macro") assert_array_almost_equal(np.mean([0.0, 1.0, 1.0, 0.5, 0.0]), actual)
# No effect otherwise for average in ["micro", "weighted", "samples"]: if average == "samples" and i == 0: continue assert_almost_equal( recall_score(y_true, y_pred, labels=[0, 1, 2, 3, 4], average=average), recall_score(y_true, y_pred, labels=None, average=average), )
# Error when introducing invalid label in multilabel case # (although it would only affect performance if average='macro'/None) for average in [None, "macro", "micro", "samples"]: with pytest.raises(ValueError): recall_score(y_true_bin, y_pred_bin, labels=np.arange(6), average=average) with pytest.raises(ValueError): recall_score( y_true_bin, y_pred_bin, labels=np.arange(-1, 4), average=average )
# tests non-regression on issue #10307 y_true = np.array([[0, 1, 1], [1, 0, 0]]) y_pred = np.array([[1, 1, 1], [1, 0, 1]]) p, r, f, _ = precision_recall_fscore_support( y_true, y_pred, average="samples", labels=[0, 1] ) assert_almost_equal(np.array([p, r, f]), np.array([3 / 4, 1, 5 / 6]))
@ignore_warningsdef test_precision_recall_f_ignored_labels(): # Test a subset of labels may be requested for PRF y_true = [1, 1, 2, 3] y_pred = [1, 3, 3, 3] y_true_bin = label_binarize(y_true, classes=np.arange(5)) y_pred_bin = label_binarize(y_pred, classes=np.arange(5)) data = [(y_true, y_pred), (y_true_bin, y_pred_bin)]
for i, (y_true, y_pred) in enumerate(data): recall_13 = partial(recall_score, y_true, y_pred, labels=[1, 3]) recall_all = partial(recall_score, y_true, y_pred, labels=None)
assert_array_almost_equal([0.5, 1.0], recall_13(average=None)) assert_almost_equal((0.5 + 1.0) / 2, recall_13(average="macro")) assert_almost_equal((0.5 * 2 + 1.0 * 1) / 3, recall_13(average="weighted")) assert_almost_equal(2.0 / 3, recall_13(average="micro"))
# ensure the above were meaningful tests: for average in ["macro", "weighted", "micro"]: assert recall_13(average=average) != recall_all(average=average)
def test_average_precision_score_score_non_binary_class(): # Test that average_precision_score function returns an error when trying # to compute average_precision_score for multiclass task. rng = check_random_state(404) y_pred = rng.rand(10)
# y_true contains three different class values y_true = rng.randint(0, 3, size=10) err_msg = "multiclass format is not supported" with pytest.raises(ValueError, match=err_msg): average_precision_score(y_true, y_pred)
def test_average_precision_score_duplicate_values(): # Duplicate values with precision-recall require a different # processing than when computing the AUC of a ROC, because the # precision-recall curve is a decreasing curve # The following situation corresponds to a perfect # test statistic, the average_precision_score should be 1 y_true = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1] y_score = [0, 0.1, 0.1, 0.4, 0.5, 0.6, 0.6, 0.9, 0.9, 1, 1] assert average_precision_score(y_true, y_score) == 1
def test_average_precision_score_tied_values(): # Here if we go from left to right in y_true, the 0 values are # are separated from the 1 values, so it appears that we've # Correctly sorted our classifications. But in fact the first two # values have the same score (0.5) and so the first two values # could be swapped around, creating an imperfect sorting. This # imperfection should come through in the end score, making it less # than one. y_true = [0, 1, 1] y_score = [0.5, 0.5, 0.6] assert average_precision_score(y_true, y_score) != 1.0
@ignore_warningsdef test_precision_recall_fscore_support_errors(): y_true, y_pred, _ = make_prediction(binary=True)
# Bad beta with pytest.raises(ValueError): precision_recall_fscore_support(y_true, y_pred, beta=-0.1)
# Bad pos_label with pytest.raises(ValueError): precision_recall_fscore_support(y_true, y_pred, pos_label=2, average="binary")
# Bad average option with pytest.raises(ValueError): precision_recall_fscore_support([0, 1, 2], [1, 2, 0], average="mega")
def test_precision_recall_f_unused_pos_label(): # Check warning that pos_label unused when set to non-default value # but average != 'binary'; even if data is binary.
msg = ( r"Note that pos_label \(set to 2\) is " r"ignored when average != 'binary' \(got 'macro'\). You " r"may use labels=\[pos_label\] to specify a single " "positive class." ) with pytest.warns(UserWarning, match=msg): precision_recall_fscore_support( [1, 2, 1], [1, 2, 2], pos_label=2, average="macro" )
def test_confusion_matrix_binary(): # Test confusion matrix - binary classification case y_true, y_pred, _ = make_prediction(binary=True)
def test(y_true, y_pred): cm = confusion_matrix(y_true, y_pred) assert_array_equal(cm, [[22, 3], [8, 17]])
tp, fp, fn, tn = cm.flatten() num = tp * tn - fp * fn den = np.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))
true_mcc = 0 if den == 0 else num / den mcc = matthews_corrcoef(y_true, y_pred) assert_array_almost_equal(mcc, true_mcc, decimal=2) assert_array_almost_equal(mcc, 0.57, decimal=2)
test(y_true, y_pred) test([str(y) for y in y_true], [str(y) for y in y_pred])
def test_multilabel_confusion_matrix_binary(): # Test multilabel confusion matrix - binary classification case y_true, y_pred, _ = make_prediction(binary=True)
def test(y_true, y_pred): cm = multilabel_confusion_matrix(y_true, y_pred) assert_array_equal(cm, [[[17, 8], [3, 22]], [[22, 3], [8, 17]]])
test(y_true, y_pred) test([str(y) for y in y_true], [str(y) for y in y_pred])
def test_multilabel_confusion_matrix_multiclass(): # Test multilabel confusion matrix - multi-class case y_true, y_pred, _ = make_prediction(binary=False)
def test(y_true, y_pred, string_type=False): # compute confusion matrix with default labels introspection cm = multilabel_confusion_matrix(y_true, y_pred) assert_array_equal( cm, [[[47, 4], [5, 19]], [[38, 6], [28, 3]], [[30, 25], [2, 18]]] )
# compute confusion matrix with explicit label ordering labels = ["0", "2", "1"] if string_type else [0, 2, 1] cm = multilabel_confusion_matrix(y_true, y_pred, labels=labels) assert_array_equal( cm, [[[47, 4], [5, 19]], [[30, 25], [2, 18]], [[38, 6], [28, 3]]] )
# compute confusion matrix with super set of present labels labels = ["0", "2", "1", "3"] if string_type else [0, 2, 1, 3] cm = multilabel_confusion_matrix(y_true, y_pred, labels=labels) assert_array_equal( cm, [ [[47, 4], [5, 19]], [[30, 25], [2, 18]], [[38, 6], [28, 3]], [[75, 0], [0, 0]], ], )
test(y_true, y_pred) test([str(y) for y in y_true], [str(y) for y in y_pred], string_type=True)
def test_multilabel_confusion_matrix_multilabel(): # Test multilabel confusion matrix - multilabel-indicator case from scipy.sparse import csc_matrix, csr_matrix
y_true = np.array([[1, 0, 1], [0, 1, 0], [1, 1, 0]]) y_pred = np.array([[1, 0, 0], [0, 1, 1], [0, 0, 1]]) y_true_csr = csr_matrix(y_true) y_pred_csr = csr_matrix(y_pred) y_true_csc = csc_matrix(y_true) y_pred_csc = csc_matrix(y_pred)
# cross test different types sample_weight = np.array([2, 1, 3]) real_cm = [[[1, 0], [1, 1]], [[1, 0], [1, 1]], [[0, 2], [1, 0]]] trues = [y_true, y_true_csr, y_true_csc] preds = [y_pred, y_pred_csr, y_pred_csc]
for y_true_tmp in trues: for y_pred_tmp in preds: cm = multilabel_confusion_matrix(y_true_tmp, y_pred_tmp) assert_array_equal(cm, real_cm)
# test support for samplewise cm = multilabel_confusion_matrix(y_true, y_pred, samplewise=True) assert_array_equal(cm, [[[1, 0], [1, 1]], [[1, 1], [0, 1]], [[0, 1], [2, 0]]])
# test support for labels cm = multilabel_confusion_matrix(y_true, y_pred, labels=[2, 0]) assert_array_equal(cm, [[[0, 2], [1, 0]], [[1, 0], [1, 1]]])
# test support for labels with samplewise cm = multilabel_confusion_matrix(y_true, y_pred, labels=[2, 0], samplewise=True) assert_array_equal(cm, [[[0, 0], [1, 1]], [[1, 1], [0, 0]], [[0, 1], [1, 0]]])
# test support for sample_weight with sample_wise cm = multilabel_confusion_matrix( y_true, y_pred, sample_weight=sample_weight, samplewise=True ) assert_array_equal(cm, [[[2, 0], [2, 2]], [[1, 1], [0, 1]], [[0, 3], [6, 0]]])
def test_multilabel_confusion_matrix_errors(): y_true = np.array([[1, 0, 1], [0, 1, 0], [1, 1, 0]]) y_pred = np.array([[1, 0, 0], [0, 1, 1], [0, 0, 1]])
# Bad sample_weight with pytest.raises(ValueError, match="inconsistent numbers of samples"): multilabel_confusion_matrix(y_true, y_pred, sample_weight=[1, 2]) with pytest.raises(ValueError, match="should be a 1d array"): multilabel_confusion_matrix( y_true, y_pred, sample_weight=[[1, 2, 3], [2, 3, 4], [3, 4, 5]] )
# Bad labels err_msg = r"All labels must be in \[0, n labels\)" with pytest.raises(ValueError, match=err_msg): multilabel_confusion_matrix(y_true, y_pred, labels=[-1]) err_msg = r"All labels must be in \[0, n labels\)" with pytest.raises(ValueError, match=err_msg): multilabel_confusion_matrix(y_true, y_pred, labels=[3])
# Using samplewise outside multilabel with pytest.raises(ValueError, match="Samplewise metrics"): multilabel_confusion_matrix([0, 1, 2], [1, 2, 0], samplewise=True)
# Bad y_type err_msg = "multiclass-multioutput is not supported" with pytest.raises(ValueError, match=err_msg): multilabel_confusion_matrix([[0, 1, 2], [2, 1, 0]], [[1, 2, 0], [1, 0, 2]])
@pytest.mark.parametrize( "normalize, cm_dtype, expected_results", [ ("true", "f", 0.333333333), ("pred", "f", 0.333333333), ("all", "f", 0.1111111111), (None, "i", 2), ],)def test_confusion_matrix_normalize(normalize, cm_dtype, expected_results): y_test = [0, 1, 2] * 6 y_pred = list(chain(*permutations([0, 1, 2]))) cm = confusion_matrix(y_test, y_pred, normalize=normalize) assert_allclose(cm, expected_results) assert cm.dtype.kind == cm_dtype
def test_confusion_matrix_normalize_wrong_option(): y_test = [0, 0, 0, 0, 1, 1, 1, 1] y_pred = [0, 0, 0, 0, 0, 0, 0, 0] with pytest.raises(ValueError, match="normalize must be one of"): confusion_matrix(y_test, y_pred, normalize=True)
def test_confusion_matrix_normalize_single_class(): y_test = [0, 0, 0, 0, 1, 1, 1, 1] y_pred = [0, 0, 0, 0, 0, 0, 0, 0]
cm_true = confusion_matrix(y_test, y_pred, normalize="true") assert cm_true.sum() == pytest.approx(2.0)
# additionally check that no warnings are raised due to a division by zero with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) cm_pred = confusion_matrix(y_test, y_pred, normalize="pred")
assert cm_pred.sum() == pytest.approx(1.0)
with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) confusion_matrix(y_pred, y_test, normalize="true")
@pytest.mark.parametrize( "params, warn_msg", [ # When y_test contains one class only and y_test==y_pred, LR+ is undefined ( { "y_true": np.array([0, 0, 0, 0, 0, 0]), "y_pred": np.array([0, 0, 0, 0, 0, 0]), }, "samples of only one class were seen during testing", ), # When `fp == 0` and `tp != 0`, LR+ is undefined ( { "y_true": np.array([1, 1, 1, 0, 0, 0]), "y_pred": np.array([1, 1, 1, 0, 0, 0]), }, "positive_likelihood_ratio ill-defined and being set to nan", ), # When `fp == 0` and `tp == 0`, LR+ is undefined ( { "y_true": np.array([1, 1, 1, 0, 0, 0]), "y_pred": np.array([0, 0, 0, 0, 0, 0]), }, "no samples predicted for the positive class", ), # When `tn == 0`, LR- is undefined ( { "y_true": np.array([1, 1, 1, 0, 0, 0]), "y_pred": np.array([0, 0, 0, 1, 1, 1]), }, "negative_likelihood_ratio ill-defined and being set to nan", ), # When `tp + fn == 0` both ratios are undefined ( { "y_true": np.array([0, 0, 0, 0, 0, 0]), "y_pred": np.array([1, 1, 1, 0, 0, 0]), }, "no samples of the positive class were present in the testing set", ), ],)def test_likelihood_ratios_warnings(params, warn_msg): # likelihood_ratios must raise warnings when at # least one of the ratios is ill-defined.
with pytest.warns(UserWarning, match=warn_msg): class_likelihood_ratios(**params)
@pytest.mark.parametrize( "params, err_msg", [ ( { "y_true": np.array([0, 1, 0, 1, 0]), "y_pred": np.array([1, 1, 0, 0, 2]), }, "class_likelihood_ratios only supports binary classification " "problems, got targets of type: multiclass", ), ],)def test_likelihood_ratios_errors(params, err_msg): # likelihood_ratios must raise error when attempting # non-binary classes to avoid Simpson's paradox with pytest.raises(ValueError, match=err_msg): class_likelihood_ratios(**params)
def test_likelihood_ratios(): # Build confusion matrix with tn=9, fp=8, fn=1, tp=2, # sensitivity=2/3, specificity=9/17, prevalence=3/20, # LR+=34/24, LR-=17/27 y_true = np.array([1] * 3 + [0] * 17) y_pred = np.array([1] * 2 + [0] * 10 + [1] * 8)
pos, neg = class_likelihood_ratios(y_true, y_pred) assert_allclose(pos, 34 / 24) assert_allclose(neg, 17 / 27)
# Build limit case with y_pred = y_true pos, neg = class_likelihood_ratios(y_true, y_true) assert_array_equal(pos, np.nan * 2) assert_allclose(neg, np.zeros(2), rtol=1e-12)
# Ignore last 5 samples to get tn=9, fp=3, fn=1, tp=2, # sensitivity=2/3, specificity=9/12, prevalence=3/20, # LR+=24/9, LR-=12/27 sample_weight = np.array([1.0] * 15 + [0.0] * 5) pos, neg = class_likelihood_ratios(y_true, y_pred, sample_weight=sample_weight) assert_allclose(pos, 24 / 9) assert_allclose(neg, 12 / 27)
def test_cohen_kappa(): # These label vectors reproduce the contingency matrix from Artstein and # Poesio (2008), Table 1: np.array([[20, 20], [10, 50]]). y1 = np.array([0] * 40 + [1] * 60) y2 = np.array([0] * 20 + [1] * 20 + [0] * 10 + [1] * 50) kappa = cohen_kappa_score(y1, y2) assert_almost_equal(kappa, 0.348, decimal=3) assert kappa == cohen_kappa_score(y2, y1)
# Add spurious labels and ignore them. y1 = np.append(y1, [2] * 4) y2 = np.append(y2, [2] * 4) assert cohen_kappa_score(y1, y2, labels=[0, 1]) == kappa
assert_almost_equal(cohen_kappa_score(y1, y1), 1.0)
# Multiclass example: Artstein and Poesio, Table 4. y1 = np.array([0] * 46 + [1] * 44 + [2] * 10) y2 = np.array([0] * 52 + [1] * 32 + [2] * 16) assert_almost_equal(cohen_kappa_score(y1, y2), 0.8013, decimal=4)
# Weighting example: none, linear, quadratic. y1 = np.array([0] * 46 + [1] * 44 + [2] * 10) y2 = np.array([0] * 50 + [1] * 40 + [2] * 10) assert_almost_equal(cohen_kappa_score(y1, y2), 0.9315, decimal=4) assert_almost_equal(cohen_kappa_score(y1, y2, weights="linear"), 0.9412, decimal=4) assert_almost_equal( cohen_kappa_score(y1, y2, weights="quadratic"), 0.9541, decimal=4 )
def test_matthews_corrcoef_nan(): assert matthews_corrcoef([0], [1]) == 0.0 assert matthews_corrcoef([0, 0], [0, 1]) == 0.0
def test_matthews_corrcoef_against_numpy_corrcoef(): rng = np.random.RandomState(0) y_true = rng.randint(0, 2, size=20) y_pred = rng.randint(0, 2, size=20)
assert_almost_equal( matthews_corrcoef(y_true, y_pred), np.corrcoef(y_true, y_pred)[0, 1], 10 )
def test_matthews_corrcoef_against_jurman(): # Check that the multiclass matthews_corrcoef agrees with the definition # presented in Jurman, Riccadonna, Furlanello, (2012). A Comparison of MCC # and CEN Error Measures in MultiClass Prediction rng = np.random.RandomState(0) y_true = rng.randint(0, 2, size=20) y_pred = rng.randint(0, 2, size=20) sample_weight = rng.rand(20)
C = confusion_matrix(y_true, y_pred, sample_weight=sample_weight) N = len(C) cov_ytyp = sum( [ C[k, k] * C[m, l] - C[l, k] * C[k, m] for k in range(N) for m in range(N) for l in range(N) ] ) cov_ytyt = sum( [ C[:, k].sum() * np.sum([C[g, f] for f in range(N) for g in range(N) if f != k]) for k in range(N) ] ) cov_ypyp = np.sum( [ C[k, :].sum() * np.sum([C[f, g] for f in range(N) for g in range(N) if f != k]) for k in range(N) ] ) mcc_jurman = cov_ytyp / np.sqrt(cov_ytyt * cov_ypyp) mcc_ours = matthews_corrcoef(y_true, y_pred, sample_weight=sample_weight)
assert_almost_equal(mcc_ours, mcc_jurman, 10)
def test_matthews_corrcoef(): rng = np.random.RandomState(0) y_true = ["a" if i == 0 else "b" for i in rng.randint(0, 2, size=20)]
# corrcoef of same vectors must be 1 assert_almost_equal(matthews_corrcoef(y_true, y_true), 1.0)
# corrcoef, when the two vectors are opposites of each other, should be -1 y_true_inv = ["b" if i == "a" else "a" for i in y_true] assert_almost_equal(matthews_corrcoef(y_true, y_true_inv), -1)
y_true_inv2 = label_binarize(y_true, classes=["a", "b"]) y_true_inv2 = np.where(y_true_inv2, "a", "b") assert_almost_equal(matthews_corrcoef(y_true, y_true_inv2), -1)
# For the zero vector case, the corrcoef cannot be calculated and should # output 0 assert_almost_equal(matthews_corrcoef([0, 0, 0, 0], [0, 0, 0, 0]), 0.0)
# And also for any other vector with 0 variance assert_almost_equal(matthews_corrcoef(y_true, ["a"] * len(y_true)), 0.0)
# These two vectors have 0 correlation and hence mcc should be 0 y_1 = [1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1] y_2 = [1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1] assert_almost_equal(matthews_corrcoef(y_1, y_2), 0.0)
# Check that sample weight is able to selectively exclude mask = [1] * 10 + [0] * 10 # Now the first half of the vector elements are alone given a weight of 1 # and hence the mcc will not be a perfect 0 as in the previous case with pytest.raises(AssertionError): assert_almost_equal(matthews_corrcoef(y_1, y_2, sample_weight=mask), 0.0)
def test_matthews_corrcoef_multiclass(): rng = np.random.RandomState(0) ord_a = ord("a") n_classes = 4 y_true = [chr(ord_a + i) for i in rng.randint(0, n_classes, size=20)]
# corrcoef of same vectors must be 1 assert_almost_equal(matthews_corrcoef(y_true, y_true), 1.0)
# with multiclass > 2 it is not possible to achieve -1 y_true = [0, 0, 1, 1, 2, 2] y_pred_bad = [2, 2, 0, 0, 1, 1] assert_almost_equal(matthews_corrcoef(y_true, y_pred_bad), -0.5)
# Maximizing false positives and negatives minimizes the MCC # The minimum will be different for depending on the input y_true = [0, 0, 1, 1, 2, 2] y_pred_min = [1, 1, 0, 0, 0, 0] assert_almost_equal(matthews_corrcoef(y_true, y_pred_min), -12 / np.sqrt(24 * 16))
# Zero variance will result in an mcc of zero y_true = [0, 1, 2] y_pred = [3, 3, 3] assert_almost_equal(matthews_corrcoef(y_true, y_pred), 0.0)
# Also for ground truth with zero variance y_true = [3, 3, 3] y_pred = [0, 1, 2] assert_almost_equal(matthews_corrcoef(y_true, y_pred), 0.0)
# These two vectors have 0 correlation and hence mcc should be 0 y_1 = [0, 1, 2, 0, 1, 2, 0, 1, 2] y_2 = [1, 1, 1, 2, 2, 2, 0, 0, 0] assert_almost_equal(matthews_corrcoef(y_1, y_2), 0.0)
# We can test that binary assumptions hold using the multiclass computation # by masking the weight of samples not in the first two classes
# Masking the last label should let us get an MCC of -1 y_true = [0, 0, 1, 1, 2] y_pred = [1, 1, 0, 0, 2] sample_weight = [1, 1, 1, 1, 0] assert_almost_equal( matthews_corrcoef(y_true, y_pred, sample_weight=sample_weight), -1 )
# For the zero vector case, the corrcoef cannot be calculated and should # output 0 y_true = [0, 0, 1, 2] y_pred = [0, 0, 1, 2] sample_weight = [1, 1, 0, 0] assert_almost_equal( matthews_corrcoef(y_true, y_pred, sample_weight=sample_weight), 0.0 )
@pytest.mark.parametrize("n_points", [100, 10000])def test_matthews_corrcoef_overflow(n_points): # https://github.com/scikit-learn/scikit-learn/issues/9622 rng = np.random.RandomState(20170906)
def mcc_safe(y_true, y_pred): conf_matrix = confusion_matrix(y_true, y_pred) true_pos = conf_matrix[1, 1] false_pos = conf_matrix[1, 0] false_neg = conf_matrix[0, 1] n_points = len(y_true) pos_rate = (true_pos + false_neg) / n_points activity = (true_pos + false_pos) / n_points mcc_numerator = true_pos / n_points - pos_rate * activity mcc_denominator = activity * pos_rate * (1 - activity) * (1 - pos_rate) return mcc_numerator / np.sqrt(mcc_denominator)
def random_ys(n_points): # binary x_true = rng.random_sample(n_points) x_pred = x_true + 0.2 * (rng.random_sample(n_points) - 0.5) y_true = x_true > 0.5 y_pred = x_pred > 0.5 return y_true, y_pred
arr = np.repeat([0.0, 1.0], n_points) # binary assert_almost_equal(matthews_corrcoef(arr, arr), 1.0) arr = np.repeat([0.0, 1.0, 2.0], n_points) # multiclass assert_almost_equal(matthews_corrcoef(arr, arr), 1.0)
y_true, y_pred = random_ys(n_points) assert_almost_equal(matthews_corrcoef(y_true, y_true), 1.0) assert_almost_equal(matthews_corrcoef(y_true, y_pred), mcc_safe(y_true, y_pred))
def test_precision_recall_f1_score_multiclass(): # Test Precision Recall and F1 Score for multiclass classification task y_true, y_pred, _ = make_prediction(binary=False)
# compute scores with default labels introspection p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) assert_array_almost_equal(p, [0.83, 0.33, 0.42], 2) assert_array_almost_equal(r, [0.79, 0.09, 0.90], 2) assert_array_almost_equal(f, [0.81, 0.15, 0.57], 2) assert_array_equal(s, [24, 31, 20])
# averaging tests ps = precision_score(y_true, y_pred, pos_label=1, average="micro") assert_array_almost_equal(ps, 0.53, 2)
rs = recall_score(y_true, y_pred, average="micro") assert_array_almost_equal(rs, 0.53, 2)
fs = f1_score(y_true, y_pred, average="micro") assert_array_almost_equal(fs, 0.53, 2)
ps = precision_score(y_true, y_pred, average="macro") assert_array_almost_equal(ps, 0.53, 2)
rs = recall_score(y_true, y_pred, average="macro") assert_array_almost_equal(rs, 0.60, 2)
fs = f1_score(y_true, y_pred, average="macro") assert_array_almost_equal(fs, 0.51, 2)
ps = precision_score(y_true, y_pred, average="weighted") assert_array_almost_equal(ps, 0.51, 2)
rs = recall_score(y_true, y_pred, average="weighted") assert_array_almost_equal(rs, 0.53, 2)
fs = f1_score(y_true, y_pred, average="weighted") assert_array_almost_equal(fs, 0.47, 2)
with pytest.raises(ValueError): precision_score(y_true, y_pred, average="samples") with pytest.raises(ValueError): recall_score(y_true, y_pred, average="samples") with pytest.raises(ValueError): f1_score(y_true, y_pred, average="samples") with pytest.raises(ValueError): fbeta_score(y_true, y_pred, average="samples", beta=0.5)
# same prediction but with and explicit label ordering p, r, f, s = precision_recall_fscore_support( y_true, y_pred, labels=[0, 2, 1], average=None ) assert_array_almost_equal(p, [0.83, 0.41, 0.33], 2) assert_array_almost_equal(r, [0.79, 0.90, 0.10], 2) assert_array_almost_equal(f, [0.81, 0.57, 0.15], 2) assert_array_equal(s, [24, 20, 31])
@pytest.mark.parametrize("average", ["samples", "micro", "macro", "weighted", None])def test_precision_refcall_f1_score_multilabel_unordered_labels(average): # test that labels need not be sorted in the multilabel case y_true = np.array([[1, 1, 0, 0]]) y_pred = np.array([[0, 0, 1, 1]]) p, r, f, s = precision_recall_fscore_support( y_true, y_pred, labels=[3, 0, 1, 2], warn_for=[], average=average ) assert_array_equal(p, 0) assert_array_equal(r, 0) assert_array_equal(f, 0) if average is None: assert_array_equal(s, [0, 1, 1, 0])
def test_precision_recall_f1_score_binary_averaged(): y_true = np.array([0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1]) y_pred = np.array([1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1])
# compute scores with default labels introspection ps, rs, fs, _ = precision_recall_fscore_support(y_true, y_pred, average=None) p, r, f, _ = precision_recall_fscore_support(y_true, y_pred, average="macro") assert p == np.mean(ps) assert r == np.mean(rs) assert f == np.mean(fs) p, r, f, _ = precision_recall_fscore_support(y_true, y_pred, average="weighted") support = np.bincount(y_true) assert p == np.average(ps, weights=support) assert r == np.average(rs, weights=support) assert f == np.average(fs, weights=support)
def test_zero_precision_recall(): # Check that pathological cases do not bring NaNs
old_error_settings = np.seterr(all="raise")
try: y_true = np.array([0, 1, 2, 0, 1, 2]) y_pred = np.array([2, 0, 1, 1, 2, 0])
assert_almost_equal(precision_score(y_true, y_pred, average="macro"), 0.0, 2) assert_almost_equal(recall_score(y_true, y_pred, average="macro"), 0.0, 2) assert_almost_equal(f1_score(y_true, y_pred, average="macro"), 0.0, 2)
finally: np.seterr(**old_error_settings)
def test_confusion_matrix_multiclass_subset_labels(): # Test confusion matrix - multi-class case with subset of labels y_true, y_pred, _ = make_prediction(binary=False)
# compute confusion matrix with only first two labels considered cm = confusion_matrix(y_true, y_pred, labels=[0, 1]) assert_array_equal(cm, [[19, 4], [4, 3]])
# compute confusion matrix with explicit label ordering for only subset # of labels cm = confusion_matrix(y_true, y_pred, labels=[2, 1]) assert_array_equal(cm, [[18, 2], [24, 3]])
# a label not in y_true should result in zeros for that row/column extra_label = np.max(y_true) + 1 cm = confusion_matrix(y_true, y_pred, labels=[2, extra_label]) assert_array_equal(cm, [[18, 0], [0, 0]])
@pytest.mark.parametrize( "labels, err_msg", [ ([], "'labels' should contains at least one label."), ([3, 4], "At least one label specified must be in y_true"), ], ids=["empty list", "unknown labels"],)def test_confusion_matrix_error(labels, err_msg): y_true, y_pred, _ = make_prediction(binary=False) with pytest.raises(ValueError, match=err_msg): confusion_matrix(y_true, y_pred, labels=labels)
@pytest.mark.parametrize( "labels", (None, [0, 1], [0, 1, 2]), ids=["None", "binary", "multiclass"])def test_confusion_matrix_on_zero_length_input(labels): expected_n_classes = len(labels) if labels else 0 expected = np.zeros((expected_n_classes, expected_n_classes), dtype=int) cm = confusion_matrix([], [], labels=labels) assert_array_equal(cm, expected)
def test_confusion_matrix_dtype(): y = [0, 1, 1] weight = np.ones(len(y)) # confusion_matrix returns int64 by default cm = confusion_matrix(y, y) assert cm.dtype == np.int64 # The dtype of confusion_matrix is always 64 bit for dtype in [np.bool_, np.int32, np.uint64]: cm = confusion_matrix(y, y, sample_weight=weight.astype(dtype, copy=False)) assert cm.dtype == np.int64 for dtype in [np.float32, np.float64, None, object]: cm = confusion_matrix(y, y, sample_weight=weight.astype(dtype, copy=False)) assert cm.dtype == np.float64
# np.iinfo(np.uint32).max should be accumulated correctly weight = np.full(len(y), 4294967295, dtype=np.uint32) cm = confusion_matrix(y, y, sample_weight=weight) assert cm[0, 0] == 4294967295 assert cm[1, 1] == 8589934590
# np.iinfo(np.int64).max should cause an overflow weight = np.full(len(y), 9223372036854775807, dtype=np.int64) cm = confusion_matrix(y, y, sample_weight=weight) assert cm[0, 0] == 9223372036854775807 assert cm[1, 1] == -2
@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean"])def test_confusion_matrix_pandas_nullable(dtype): """Checks that confusion_matrix works with pandas nullable dtypes.
Non-regression test for gh-25635. """ pd = pytest.importorskip("pandas")
y_ndarray = np.array([1, 0, 0, 1, 0, 1, 1, 0, 1]) y_true = pd.Series(y_ndarray, dtype=dtype) y_predicted = pd.Series([0, 0, 1, 1, 0, 1, 1, 1, 1], dtype="int64")
output = confusion_matrix(y_true, y_predicted) expected_output = confusion_matrix(y_ndarray, y_predicted)
assert_array_equal(output, expected_output)
def test_classification_report_multiclass(): # Test performance report iris = datasets.load_iris() y_true, y_pred, _ = make_prediction(dataset=iris, binary=False)
# print classification report with class names expected_report = """\ precision recall f1-score support
setosa 0.83 0.79 0.81 24 versicolor 0.33 0.10 0.15 31 virginica 0.42 0.90 0.57 20
accuracy 0.53 75 macro avg 0.53 0.60 0.51 75weighted avg 0.51 0.53 0.47 75""" report = classification_report( y_true, y_pred, labels=np.arange(len(iris.target_names)), target_names=iris.target_names, ) assert report == expected_report
def test_classification_report_multiclass_balanced(): y_true, y_pred = [0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2]
expected_report = """\ precision recall f1-score support
0 0.33 0.33 0.33 3 1 0.33 0.33 0.33 3 2 0.33 0.33 0.33 3
accuracy 0.33 9 macro avg 0.33 0.33 0.33 9weighted avg 0.33 0.33 0.33 9""" report = classification_report(y_true, y_pred) assert report == expected_report
def test_classification_report_multiclass_with_label_detection(): iris = datasets.load_iris() y_true, y_pred, _ = make_prediction(dataset=iris, binary=False)
# print classification report with label detection expected_report = """\ precision recall f1-score support
0 0.83 0.79 0.81 24 1 0.33 0.10 0.15 31 2 0.42 0.90 0.57 20
accuracy 0.53 75 macro avg 0.53 0.60 0.51 75weighted avg 0.51 0.53 0.47 75""" report = classification_report(y_true, y_pred) assert report == expected_report
def test_classification_report_multiclass_with_digits(): # Test performance report with added digits in floating point values iris = datasets.load_iris() y_true, y_pred, _ = make_prediction(dataset=iris, binary=False)
# print classification report with class names expected_report = """\ precision recall f1-score support
setosa 0.82609 0.79167 0.80851 24 versicolor 0.33333 0.09677 0.15000 31 virginica 0.41860 0.90000 0.57143 20
accuracy 0.53333 75 macro avg 0.52601 0.59615 0.50998 75weighted avg 0.51375 0.53333 0.47310 75""" report = classification_report( y_true, y_pred, labels=np.arange(len(iris.target_names)), target_names=iris.target_names, digits=5, ) assert report == expected_report
def test_classification_report_multiclass_with_string_label(): y_true, y_pred, _ = make_prediction(binary=False)
y_true = np.array(["blue", "green", "red"])[y_true] y_pred = np.array(["blue", "green", "red"])[y_pred]
expected_report = """\ precision recall f1-score support
blue 0.83 0.79 0.81 24 green 0.33 0.10 0.15 31 red 0.42 0.90 0.57 20
accuracy 0.53 75 macro avg 0.53 0.60 0.51 75weighted avg 0.51 0.53 0.47 75""" report = classification_report(y_true, y_pred) assert report == expected_report
expected_report = """\ precision recall f1-score support
a 0.83 0.79 0.81 24 b 0.33 0.10 0.15 31 c 0.42 0.90 0.57 20
accuracy 0.53 75 macro avg 0.53 0.60 0.51 75weighted avg 0.51 0.53 0.47 75""" report = classification_report(y_true, y_pred, target_names=["a", "b", "c"]) assert report == expected_report
def test_classification_report_multiclass_with_unicode_label(): y_true, y_pred, _ = make_prediction(binary=False)
labels = np.array(["blue\xa2", "green\xa2", "red\xa2"]) y_true = labels[y_true] y_pred = labels[y_pred]
expected_report = """\ precision recall f1-score support
blue\xa2 0.83 0.79 0.81 24 green\xa2 0.33 0.10 0.15 31 red\xa2 0.42 0.90 0.57 20
accuracy 0.53 75 macro avg 0.53 0.60 0.51 75weighted avg 0.51 0.53 0.47 75""" report = classification_report(y_true, y_pred) assert report == expected_report
def test_classification_report_multiclass_with_long_string_label(): y_true, y_pred, _ = make_prediction(binary=False)
labels = np.array(["blue", "green" * 5, "red"]) y_true = labels[y_true] y_pred = labels[y_pred]
expected_report = """\ precision recall f1-score support
blue 0.83 0.79 0.81 24greengreengreengreengreen 0.33 0.10 0.15 31 red 0.42 0.90 0.57 20
accuracy 0.53 75 macro avg 0.53 0.60 0.51 75 weighted avg 0.51 0.53 0.47 75"""
report = classification_report(y_true, y_pred) assert report == expected_report
def test_classification_report_labels_target_names_unequal_length(): y_true = [0, 0, 2, 0, 0] y_pred = [0, 2, 2, 0, 0] target_names = ["class 0", "class 1", "class 2"]
msg = "labels size, 2, does not match size of target_names, 3" with pytest.warns(UserWarning, match=msg): classification_report(y_true, y_pred, labels=[0, 2], target_names=target_names)
def test_classification_report_no_labels_target_names_unequal_length(): y_true = [0, 0, 2, 0, 0] y_pred = [0, 2, 2, 0, 0] target_names = ["class 0", "class 1", "class 2"]
err_msg = ( "Number of classes, 2, does not " "match size of target_names, 3. " "Try specifying the labels parameter" ) with pytest.raises(ValueError, match=err_msg): classification_report(y_true, y_pred, target_names=target_names)
@ignore_warningsdef test_multilabel_classification_report(): n_classes = 4 n_samples = 50
_, y_true = make_multilabel_classification( n_features=1, n_samples=n_samples, n_classes=n_classes, random_state=0 )
_, y_pred = make_multilabel_classification( n_features=1, n_samples=n_samples, n_classes=n_classes, random_state=1 )
expected_report = """\ precision recall f1-score support
0 0.50 0.67 0.57 24 1 0.51 0.74 0.61 27 2 0.29 0.08 0.12 26 3 0.52 0.56 0.54 27
micro avg 0.50 0.51 0.50 104 macro avg 0.45 0.51 0.46 104weighted avg 0.45 0.51 0.46 104 samples avg 0.46 0.42 0.40 104"""
report = classification_report(y_true, y_pred) assert report == expected_report
def test_multilabel_zero_one_loss_subset(): # Dense label indicator matrix format y1 = np.array([[0, 1, 1], [1, 0, 1]]) y2 = np.array([[0, 0, 1], [1, 0, 1]])
assert zero_one_loss(y1, y2) == 0.5 assert zero_one_loss(y1, y1) == 0 assert zero_one_loss(y2, y2) == 0 assert zero_one_loss(y2, np.logical_not(y2)) == 1 assert zero_one_loss(y1, np.logical_not(y1)) == 1 assert zero_one_loss(y1, np.zeros(y1.shape)) == 1 assert zero_one_loss(y2, np.zeros(y1.shape)) == 1
def test_multilabel_hamming_loss(): # Dense label indicator matrix format y1 = np.array([[0, 1, 1], [1, 0, 1]]) y2 = np.array([[0, 0, 1], [1, 0, 1]]) w = np.array([1, 3])
assert hamming_loss(y1, y2) == 1 / 6 assert hamming_loss(y1, y1) == 0 assert hamming_loss(y2, y2) == 0 assert hamming_loss(y2, 1 - y2) == 1 assert hamming_loss(y1, 1 - y1) == 1 assert hamming_loss(y1, np.zeros(y1.shape)) == 4 / 6 assert hamming_loss(y2, np.zeros(y1.shape)) == 0.5 assert hamming_loss(y1, y2, sample_weight=w) == 1.0 / 12 assert hamming_loss(y1, 1 - y2, sample_weight=w) == 11.0 / 12 assert hamming_loss(y1, np.zeros_like(y1), sample_weight=w) == 2.0 / 3 # sp_hamming only works with 1-D arrays assert hamming_loss(y1[0], y2[0]) == sp_hamming(y1[0], y2[0])
def test_jaccard_score_validation(): y_true = np.array([0, 1, 0, 1, 1]) y_pred = np.array([0, 1, 0, 1, 1]) err_msg = r"pos_label=2 is not a valid label. It should be one of \[0, 1\]" with pytest.raises(ValueError, match=err_msg): jaccard_score(y_true, y_pred, average="binary", pos_label=2)
y_true = np.array([[0, 1, 1], [1, 0, 0]]) y_pred = np.array([[1, 1, 1], [1, 0, 1]]) msg1 = ( r"Target is multilabel-indicator but average='binary'. " r"Please choose another average setting, one of \[None, " r"'micro', 'macro', 'weighted', 'samples'\]." ) with pytest.raises(ValueError, match=msg1): jaccard_score(y_true, y_pred, average="binary", pos_label=-1)
y_true = np.array([0, 1, 1, 0, 2]) y_pred = np.array([1, 1, 1, 1, 0]) msg2 = ( r"Target is multiclass but average='binary'. Please choose " r"another average setting, one of \[None, 'micro', 'macro', " r"'weighted'\]." ) with pytest.raises(ValueError, match=msg2): jaccard_score(y_true, y_pred, average="binary") msg3 = "Samplewise metrics are not available outside of multilabel classification." with pytest.raises(ValueError, match=msg3): jaccard_score(y_true, y_pred, average="samples")
msg = ( r"Note that pos_label \(set to 3\) is ignored when " r"average != 'binary' \(got 'micro'\). You may use " r"labels=\[pos_label\] to specify a single positive " "class." ) with pytest.warns(UserWarning, match=msg): jaccard_score(y_true, y_pred, average="micro", pos_label=3)
def test_multilabel_jaccard_score(recwarn): # Dense label indicator matrix format y1 = np.array([[0, 1, 1], [1, 0, 1]]) y2 = np.array([[0, 0, 1], [1, 0, 1]])
# size(y1 \inter y2) = [1, 2] # size(y1 \union y2) = [2, 2]
assert jaccard_score(y1, y2, average="samples") == 0.75 assert jaccard_score(y1, y1, average="samples") == 1 assert jaccard_score(y2, y2, average="samples") == 1 assert jaccard_score(y2, np.logical_not(y2), average="samples") == 0 assert jaccard_score(y1, np.logical_not(y1), average="samples") == 0 assert jaccard_score(y1, np.zeros(y1.shape), average="samples") == 0 assert jaccard_score(y2, np.zeros(y1.shape), average="samples") == 0
y_true = np.array([[0, 1, 1], [1, 0, 0]]) y_pred = np.array([[1, 1, 1], [1, 0, 1]]) # average='macro' assert_almost_equal(jaccard_score(y_true, y_pred, average="macro"), 2.0 / 3) # average='micro' assert_almost_equal(jaccard_score(y_true, y_pred, average="micro"), 3.0 / 5) # average='samples' assert_almost_equal(jaccard_score(y_true, y_pred, average="samples"), 7.0 / 12) assert_almost_equal( jaccard_score(y_true, y_pred, average="samples", labels=[0, 2]), 1.0 / 2 ) assert_almost_equal( jaccard_score(y_true, y_pred, average="samples", labels=[1, 2]), 1.0 / 2 ) # average=None assert_array_equal( jaccard_score(y_true, y_pred, average=None), np.array([1.0 / 2, 1.0, 1.0 / 2]) )
y_true = np.array([[0, 1, 1], [1, 0, 1]]) y_pred = np.array([[1, 1, 1], [1, 0, 1]]) assert_almost_equal(jaccard_score(y_true, y_pred, average="macro"), 5.0 / 6) # average='weighted' assert_almost_equal(jaccard_score(y_true, y_pred, average="weighted"), 7.0 / 8)
msg2 = "Got 4 > 2" with pytest.raises(ValueError, match=msg2): jaccard_score(y_true, y_pred, labels=[4], average="macro") msg3 = "Got -1 < 0" with pytest.raises(ValueError, match=msg3): jaccard_score(y_true, y_pred, labels=[-1], average="macro")
msg = ( "Jaccard is ill-defined and being set to 0.0 in labels " "with no true or predicted samples." )
with pytest.warns(UndefinedMetricWarning, match=msg): assert ( jaccard_score(np.array([[0, 1]]), np.array([[0, 1]]), average="macro") == 0.5 )
msg = ( "Jaccard is ill-defined and being set to 0.0 in samples " "with no true or predicted labels." )
with pytest.warns(UndefinedMetricWarning, match=msg): assert ( jaccard_score( np.array([[0, 0], [1, 1]]), np.array([[0, 0], [1, 1]]), average="samples", ) == 0.5 )
assert not list(recwarn)
def test_multiclass_jaccard_score(recwarn): y_true = ["ant", "ant", "cat", "cat", "ant", "cat", "bird", "bird"] y_pred = ["cat", "ant", "cat", "cat", "ant", "bird", "bird", "cat"] labels = ["ant", "bird", "cat"] lb = LabelBinarizer() lb.fit(labels) y_true_bin = lb.transform(y_true) y_pred_bin = lb.transform(y_pred) multi_jaccard_score = partial(jaccard_score, y_true, y_pred) bin_jaccard_score = partial(jaccard_score, y_true_bin, y_pred_bin) multi_labels_list = [ ["ant", "bird"], ["ant", "cat"], ["cat", "bird"], ["ant"], ["bird"], ["cat"], None, ] bin_labels_list = [[0, 1], [0, 2], [2, 1], [0], [1], [2], None]
# other than average='samples'/'none-samples', test everything else here for average in ("macro", "weighted", "micro", None): for m_label, b_label in zip(multi_labels_list, bin_labels_list): assert_almost_equal( multi_jaccard_score(average=average, labels=m_label), bin_jaccard_score(average=average, labels=b_label), )
y_true = np.array([[0, 0], [0, 0], [0, 0]]) y_pred = np.array([[0, 0], [0, 0], [0, 0]]) with ignore_warnings(): assert jaccard_score(y_true, y_pred, average="weighted") == 0
assert not list(recwarn)
def test_average_binary_jaccard_score(recwarn): # tp=0, fp=0, fn=1, tn=0 assert jaccard_score([1], [0], average="binary") == 0.0 # tp=0, fp=0, fn=0, tn=1 msg = ( "Jaccard is ill-defined and being set to 0.0 due to " "no true or predicted samples" ) with pytest.warns(UndefinedMetricWarning, match=msg): assert jaccard_score([0, 0], [0, 0], average="binary") == 0.0
# tp=1, fp=0, fn=0, tn=0 (pos_label=0) assert jaccard_score([0], [0], pos_label=0, average="binary") == 1.0 y_true = np.array([1, 0, 1, 1, 0]) y_pred = np.array([1, 0, 1, 1, 1]) assert_almost_equal(jaccard_score(y_true, y_pred, average="binary"), 3.0 / 4) assert_almost_equal( jaccard_score(y_true, y_pred, average="binary", pos_label=0), 1.0 / 2 )
assert not list(recwarn)
def test_jaccard_score_zero_division_warning(): # check that we raised a warning with default behavior if a zero division # happens y_true = np.array([[1, 0, 1], [0, 0, 0]]) y_pred = np.array([[0, 0, 0], [0, 0, 0]]) msg = ( "Jaccard is ill-defined and being set to 0.0 in " "samples with no true or predicted labels." " Use `zero_division` parameter to control this behavior." ) with pytest.warns(UndefinedMetricWarning, match=msg): score = jaccard_score(y_true, y_pred, average="samples", zero_division="warn") assert score == pytest.approx(0.0)
@pytest.mark.parametrize("zero_division, expected_score", [(0, 0), (1, 0.5)])def test_jaccard_score_zero_division_set_value(zero_division, expected_score): # check that we don't issue warning by passing the zero_division parameter y_true = np.array([[1, 0, 1], [0, 0, 0]]) y_pred = np.array([[0, 0, 0], [0, 0, 0]]) with warnings.catch_warnings(): warnings.simplefilter("error", UndefinedMetricWarning) score = jaccard_score( y_true, y_pred, average="samples", zero_division=zero_division ) assert score == pytest.approx(expected_score)
@ignore_warningsdef test_precision_recall_f1_score_multilabel_1(): # Test precision_recall_f1_score on a crafted multilabel example # First crafted example
y_true = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 1]]) y_pred = np.array([[0, 1, 0, 0], [0, 1, 0, 0], [1, 0, 1, 0]])
p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None)
# tp = [0, 1, 1, 0] # fn = [1, 0, 0, 1] # fp = [1, 1, 0, 0] # Check per class
assert_array_almost_equal(p, [0.0, 0.5, 1.0, 0.0], 2) assert_array_almost_equal(r, [0.0, 1.0, 1.0, 0.0], 2) assert_array_almost_equal(f, [0.0, 1 / 1.5, 1, 0.0], 2) assert_array_almost_equal(s, [1, 1, 1, 1], 2)
f2 = fbeta_score(y_true, y_pred, beta=2, average=None) support = s assert_array_almost_equal(f2, [0, 0.83, 1, 0], 2)
# Check macro p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="macro") assert_almost_equal(p, 1.5 / 4) assert_almost_equal(r, 0.5) assert_almost_equal(f, 2.5 / 1.5 * 0.25) assert s is None assert_almost_equal( fbeta_score(y_true, y_pred, beta=2, average="macro"), np.mean(f2) )
# Check micro p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="micro") assert_almost_equal(p, 0.5) assert_almost_equal(r, 0.5) assert_almost_equal(f, 0.5) assert s is None assert_almost_equal( fbeta_score(y_true, y_pred, beta=2, average="micro"), (1 + 4) * p * r / (4 * p + r), )
# Check weighted p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="weighted") assert_almost_equal(p, 1.5 / 4) assert_almost_equal(r, 0.5) assert_almost_equal(f, 2.5 / 1.5 * 0.25) assert s is None assert_almost_equal( fbeta_score(y_true, y_pred, beta=2, average="weighted"), np.average(f2, weights=support), ) # Check samples # |h(x_i) inter y_i | = [0, 1, 1] # |y_i| = [1, 1, 2] # |h(x_i)| = [1, 1, 2] p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="samples") assert_almost_equal(p, 0.5) assert_almost_equal(r, 0.5) assert_almost_equal(f, 0.5) assert s is None assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="samples"), 0.5)
@ignore_warningsdef test_precision_recall_f1_score_multilabel_2(): # Test precision_recall_f1_score on a crafted multilabel example 2 # Second crafted example y_true = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 1, 1, 0]]) y_pred = np.array([[0, 0, 0, 1], [0, 0, 0, 1], [1, 1, 0, 0]])
# tp = [ 0. 1. 0. 0.] # fp = [ 1. 0. 0. 2.] # fn = [ 1. 1. 1. 0.]
p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) assert_array_almost_equal(p, [0.0, 1.0, 0.0, 0.0], 2) assert_array_almost_equal(r, [0.0, 0.5, 0.0, 0.0], 2) assert_array_almost_equal(f, [0.0, 0.66, 0.0, 0.0], 2) assert_array_almost_equal(s, [1, 2, 1, 0], 2)
f2 = fbeta_score(y_true, y_pred, beta=2, average=None) support = s assert_array_almost_equal(f2, [0, 0.55, 0, 0], 2)
p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="micro") assert_almost_equal(p, 0.25) assert_almost_equal(r, 0.25) assert_almost_equal(f, 2 * 0.25 * 0.25 / 0.5) assert s is None assert_almost_equal( fbeta_score(y_true, y_pred, beta=2, average="micro"), (1 + 4) * p * r / (4 * p + r), )
p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="macro") assert_almost_equal(p, 0.25) assert_almost_equal(r, 0.125) assert_almost_equal(f, 2 / 12) assert s is None assert_almost_equal( fbeta_score(y_true, y_pred, beta=2, average="macro"), np.mean(f2) )
p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="weighted") assert_almost_equal(p, 2 / 4) assert_almost_equal(r, 1 / 4) assert_almost_equal(f, 2 / 3 * 2 / 4) assert s is None assert_almost_equal( fbeta_score(y_true, y_pred, beta=2, average="weighted"), np.average(f2, weights=support), )
p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="samples") # Check samples # |h(x_i) inter y_i | = [0, 0, 1] # |y_i| = [1, 1, 2] # |h(x_i)| = [1, 1, 2]
assert_almost_equal(p, 1 / 6) assert_almost_equal(r, 1 / 6) assert_almost_equal(f, 2 / 4 * 1 / 3) assert s is None assert_almost_equal( fbeta_score(y_true, y_pred, beta=2, average="samples"), 0.1666, 2 )
@ignore_warnings@pytest.mark.parametrize("zero_division", ["warn", 0, 1])def test_precision_recall_f1_score_with_an_empty_prediction(zero_division): y_true = np.array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 1, 1, 0]]) y_pred = np.array([[0, 0, 0, 0], [0, 0, 0, 1], [0, 1, 1, 0]])
# true_pos = [ 0. 1. 1. 0.] # false_pos = [ 0. 0. 0. 1.] # false_neg = [ 1. 1. 0. 0.] zero_division = 1.0 if zero_division == 1.0 else 0.0 p, r, f, s = precision_recall_fscore_support( y_true, y_pred, average=None, zero_division=zero_division ) assert_array_almost_equal(p, [zero_division, 1.0, 1.0, 0.0], 2) assert_array_almost_equal(r, [0.0, 0.5, 1.0, zero_division], 2) assert_array_almost_equal(f, [0.0, 1 / 1.5, 1, 0.0], 2) assert_array_almost_equal(s, [1, 2, 1, 0], 2)
f2 = fbeta_score(y_true, y_pred, beta=2, average=None, zero_division=zero_division) support = s assert_array_almost_equal(f2, [0, 0.55, 1, 0], 2)
p, r, f, s = precision_recall_fscore_support( y_true, y_pred, average="macro", zero_division=zero_division ) assert_almost_equal(p, (2 + zero_division) / 4) assert_almost_equal(r, (1.5 + zero_division) / 4) assert_almost_equal(f, 2.5 / (4 * 1.5)) assert s is None assert_almost_equal( fbeta_score(y_true, y_pred, beta=2, average="macro"), np.mean(f2) )
p, r, f, s = precision_recall_fscore_support( y_true, y_pred, average="micro", zero_division=zero_division ) assert_almost_equal(p, 2 / 3) assert_almost_equal(r, 0.5) assert_almost_equal(f, 2 / 3 / (2 / 3 + 0.5)) assert s is None assert_almost_equal( fbeta_score( y_true, y_pred, beta=2, average="micro", zero_division=zero_division ), (1 + 4) * p * r / (4 * p + r), )
p, r, f, s = precision_recall_fscore_support( y_true, y_pred, average="weighted", zero_division=zero_division ) assert_almost_equal(p, 3 / 4 if zero_division == 0 else 1.0) assert_almost_equal(r, 0.5) assert_almost_equal(f, (2 / 1.5 + 1) / 4) assert s is None assert_almost_equal( fbeta_score( y_true, y_pred, beta=2, average="weighted", zero_division=zero_division ), np.average(f2, weights=support), )
p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="samples") # |h(x_i) inter y_i | = [0, 0, 2] # |y_i| = [1, 1, 2] # |h(x_i)| = [0, 1, 2] assert_almost_equal(p, 1 / 3) assert_almost_equal(r, 1 / 3) assert_almost_equal(f, 1 / 3) assert s is None assert_almost_equal( fbeta_score( y_true, y_pred, beta=2, average="samples", zero_division=zero_division ), 0.333, 2, )
@pytest.mark.parametrize("beta", [1])@pytest.mark.parametrize("average", ["macro", "micro", "weighted", "samples"])@pytest.mark.parametrize("zero_division", [0, 1])def test_precision_recall_f1_no_labels(beta, average, zero_division): y_true = np.zeros((20, 3)) y_pred = np.zeros_like(y_true)
p, r, f, s = assert_no_warnings( precision_recall_fscore_support, y_true, y_pred, average=average, beta=beta, zero_division=zero_division, ) fbeta = assert_no_warnings( fbeta_score, y_true, y_pred, beta=beta, average=average, zero_division=zero_division, )
zero_division = float(zero_division) assert_almost_equal(p, zero_division) assert_almost_equal(r, zero_division) assert_almost_equal(f, zero_division) assert s is None
assert_almost_equal(fbeta, float(zero_division))
@pytest.mark.parametrize("average", ["macro", "micro", "weighted", "samples"])def test_precision_recall_f1_no_labels_check_warnings(average): y_true = np.zeros((20, 3)) y_pred = np.zeros_like(y_true)
func = precision_recall_fscore_support with pytest.warns(UndefinedMetricWarning): p, r, f, s = func(y_true, y_pred, average=average, beta=1.0)
assert_almost_equal(p, 0) assert_almost_equal(r, 0) assert_almost_equal(f, 0) assert s is None
with pytest.warns(UndefinedMetricWarning): fbeta = fbeta_score(y_true, y_pred, average=average, beta=1.0)
assert_almost_equal(fbeta, 0)
@pytest.mark.parametrize("zero_division", [0, 1])def test_precision_recall_f1_no_labels_average_none(zero_division): y_true = np.zeros((20, 3)) y_pred = np.zeros_like(y_true)
# tp = [0, 0, 0] # fn = [0, 0, 0] # fp = [0, 0, 0] # support = [0, 0, 0] # |y_hat_i inter y_i | = [0, 0, 0] # |y_i| = [0, 0, 0] # |y_hat_i| = [0, 0, 0]
p, r, f, s = assert_no_warnings( precision_recall_fscore_support, y_true, y_pred, average=None, beta=1.0, zero_division=zero_division, ) fbeta = assert_no_warnings( fbeta_score, y_true, y_pred, beta=1.0, average=None, zero_division=zero_division )
zero_division = float(zero_division) assert_array_almost_equal(p, [zero_division, zero_division, zero_division], 2) assert_array_almost_equal(r, [zero_division, zero_division, zero_division], 2) assert_array_almost_equal(f, [zero_division, zero_division, zero_division], 2) assert_array_almost_equal(s, [0, 0, 0], 2)
assert_array_almost_equal(fbeta, [zero_division, zero_division, zero_division], 2)
def test_precision_recall_f1_no_labels_average_none_warn(): y_true = np.zeros((20, 3)) y_pred = np.zeros_like(y_true)
# tp = [0, 0, 0] # fn = [0, 0, 0] # fp = [0, 0, 0] # support = [0, 0, 0] # |y_hat_i inter y_i | = [0, 0, 0] # |y_i| = [0, 0, 0] # |y_hat_i| = [0, 0, 0]
with pytest.warns(UndefinedMetricWarning): p, r, f, s = precision_recall_fscore_support( y_true, y_pred, average=None, beta=1 )
assert_array_almost_equal(p, [0, 0, 0], 2) assert_array_almost_equal(r, [0, 0, 0], 2) assert_array_almost_equal(f, [0, 0, 0], 2) assert_array_almost_equal(s, [0, 0, 0], 2)
with pytest.warns(UndefinedMetricWarning): fbeta = fbeta_score(y_true, y_pred, beta=1, average=None)
assert_array_almost_equal(fbeta, [0, 0, 0], 2)
def test_prf_warnings(): # average of per-label scores f, w = precision_recall_fscore_support, UndefinedMetricWarning for average in [None, "weighted", "macro"]:
msg = ( "Precision and F-score are ill-defined and " "being set to 0.0 in labels with no predicted samples." " Use `zero_division` parameter to control" " this behavior." ) with pytest.warns(w, match=msg): f([0, 1, 2], [1, 1, 2], average=average)
msg = ( "Recall and F-score are ill-defined and " "being set to 0.0 in labels with no true samples." " Use `zero_division` parameter to control" " this behavior." ) with pytest.warns(w, match=msg): f([1, 1, 2], [0, 1, 2], average=average)
# average of per-sample scores msg = ( "Precision and F-score are ill-defined and " "being set to 0.0 in samples with no predicted labels." " Use `zero_division` parameter to control" " this behavior." ) with pytest.warns(w, match=msg): f(np.array([[1, 0], [1, 0]]), np.array([[1, 0], [0, 0]]), average="samples")
msg = ( "Recall and F-score are ill-defined and " "being set to 0.0 in samples with no true labels." " Use `zero_division` parameter to control" " this behavior." ) with pytest.warns(w, match=msg): f(np.array([[1, 0], [0, 0]]), np.array([[1, 0], [1, 0]]), average="samples")
# single score: micro-average msg = ( "Precision and F-score are ill-defined and " "being set to 0.0 due to no predicted samples." " Use `zero_division` parameter to control" " this behavior." ) with pytest.warns(w, match=msg): f(np.array([[1, 1], [1, 1]]), np.array([[0, 0], [0, 0]]), average="micro")
msg = ( "Recall and F-score are ill-defined and " "being set to 0.0 due to no true samples." " Use `zero_division` parameter to control" " this behavior." ) with pytest.warns(w, match=msg): f(np.array([[0, 0], [0, 0]]), np.array([[1, 1], [1, 1]]), average="micro")
# single positive label msg = ( "Precision and F-score are ill-defined and " "being set to 0.0 due to no predicted samples." " Use `zero_division` parameter to control" " this behavior." ) with pytest.warns(w, match=msg): f([1, 1], [-1, -1], average="binary")
msg = ( "Recall and F-score are ill-defined and " "being set to 0.0 due to no true samples." " Use `zero_division` parameter to control" " this behavior." ) with pytest.warns(w, match=msg): f([-1, -1], [1, 1], average="binary")
with warnings.catch_warnings(record=True) as record: warnings.simplefilter("always") precision_recall_fscore_support([0, 0], [0, 0], average="binary") msg = ( "Recall and F-score are ill-defined and " "being set to 0.0 due to no true samples." " Use `zero_division` parameter to control" " this behavior." ) assert str(record.pop().message) == msg msg = ( "Precision and F-score are ill-defined and " "being set to 0.0 due to no predicted samples." " Use `zero_division` parameter to control" " this behavior." ) assert str(record.pop().message) == msg
@pytest.mark.parametrize("zero_division", [0, 1])def test_prf_no_warnings_if_zero_division_set(zero_division): # average of per-label scores f = precision_recall_fscore_support for average in [None, "weighted", "macro"]:
assert_no_warnings( f, [0, 1, 2], [1, 1, 2], average=average, zero_division=zero_division )
assert_no_warnings( f, [1, 1, 2], [0, 1, 2], average=average, zero_division=zero_division )
# average of per-sample scores assert_no_warnings( f, np.array([[1, 0], [1, 0]]), np.array([[1, 0], [0, 0]]), average="samples", zero_division=zero_division, )
assert_no_warnings( f, np.array([[1, 0], [0, 0]]), np.array([[1, 0], [1, 0]]), average="samples", zero_division=zero_division, )
# single score: micro-average assert_no_warnings( f, np.array([[1, 1], [1, 1]]), np.array([[0, 0], [0, 0]]), average="micro", zero_division=zero_division, )
assert_no_warnings( f, np.array([[0, 0], [0, 0]]), np.array([[1, 1], [1, 1]]), average="micro", zero_division=zero_division, )
# single positive label assert_no_warnings( f, [1, 1], [-1, -1], average="binary", zero_division=zero_division )
assert_no_warnings( f, [-1, -1], [1, 1], average="binary", zero_division=zero_division )
with warnings.catch_warnings(record=True) as record: warnings.simplefilter("always") precision_recall_fscore_support( [0, 0], [0, 0], average="binary", zero_division=zero_division ) assert len(record) == 0
@pytest.mark.parametrize("zero_division", ["warn", 0, 1])def test_recall_warnings(zero_division): assert_no_warnings( recall_score, np.array([[1, 1], [1, 1]]), np.array([[0, 0], [0, 0]]), average="micro", zero_division=zero_division, ) with warnings.catch_warnings(record=True) as record: warnings.simplefilter("always") recall_score( np.array([[0, 0], [0, 0]]), np.array([[1, 1], [1, 1]]), average="micro", zero_division=zero_division, ) if zero_division == "warn": assert ( str(record.pop().message) == "Recall is ill-defined and " "being set to 0.0 due to no true samples." " Use `zero_division` parameter to control" " this behavior." ) else: assert len(record) == 0
recall_score([0, 0], [0, 0]) if zero_division == "warn": assert ( str(record.pop().message) == "Recall is ill-defined and " "being set to 0.0 due to no true samples." " Use `zero_division` parameter to control" " this behavior." )
@pytest.mark.parametrize("zero_division", ["warn", 0, 1])def test_precision_warnings(zero_division): with warnings.catch_warnings(record=True) as record: warnings.simplefilter("always") precision_score( np.array([[1, 1], [1, 1]]), np.array([[0, 0], [0, 0]]), average="micro", zero_division=zero_division, ) if zero_division == "warn": assert ( str(record.pop().message) == "Precision is ill-defined and " "being set to 0.0 due to no predicted samples." " Use `zero_division` parameter to control" " this behavior." ) else: assert len(record) == 0
precision_score([0, 0], [0, 0]) if zero_division == "warn": assert ( str(record.pop().message) == "Precision is ill-defined and " "being set to 0.0 due to no predicted samples." " Use `zero_division` parameter to control" " this behavior." )
assert_no_warnings( precision_score, np.array([[0, 0], [0, 0]]), np.array([[1, 1], [1, 1]]), average="micro", zero_division=zero_division, )
@pytest.mark.parametrize("zero_division", ["warn", 0, 1])def test_fscore_warnings(zero_division): with warnings.catch_warnings(record=True) as record: warnings.simplefilter("always")
for score in [f1_score, partial(fbeta_score, beta=2)]: score( np.array([[1, 1], [1, 1]]), np.array([[0, 0], [0, 0]]), average="micro", zero_division=zero_division, ) assert len(record) == 0
score( np.array([[0, 0], [0, 0]]), np.array([[1, 1], [1, 1]]), average="micro", zero_division=zero_division, ) assert len(record) == 0
score( np.array([[0, 0], [0, 0]]), np.array([[0, 0], [0, 0]]), average="micro", zero_division=zero_division, ) if zero_division == "warn": assert ( str(record.pop().message) == "F-score is ill-defined and " "being set to 0.0 due to no true nor predicted " "samples. Use `zero_division` parameter to " "control this behavior." ) else: assert len(record) == 0
def test_prf_average_binary_data_non_binary(): # Error if user does not explicitly set non-binary average mode y_true_mc = [1, 2, 3, 3] y_pred_mc = [1, 2, 3, 1] msg_mc = ( r"Target is multiclass but average='binary'. Please " r"choose another average setting, one of \[" r"None, 'micro', 'macro', 'weighted'\]." ) y_true_ind = np.array([[0, 1, 1], [1, 0, 0], [0, 0, 1]]) y_pred_ind = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]]) msg_ind = ( r"Target is multilabel-indicator but average='binary'. Please " r"choose another average setting, one of \[" r"None, 'micro', 'macro', 'weighted', 'samples'\]." )
for y_true, y_pred, msg in [ (y_true_mc, y_pred_mc, msg_mc), (y_true_ind, y_pred_ind, msg_ind), ]: for metric in [ precision_score, recall_score, f1_score, partial(fbeta_score, beta=2), ]: with pytest.raises(ValueError, match=msg): metric(y_true, y_pred)
def test__check_targets(): # Check that _check_targets correctly merges target types, squeezes # output and fails if input lengths differ. IND = "multilabel-indicator" MC = "multiclass" BIN = "binary" CNT = "continuous" MMC = "multiclass-multioutput" MCN = "continuous-multioutput" # all of length 3 EXAMPLES = [ (IND, np.array([[0, 1, 1], [1, 0, 0], [0, 0, 1]])), # must not be considered binary (IND, np.array([[0, 1], [1, 0], [1, 1]])), (MC, [2, 3, 1]), (BIN, [0, 1, 1]), (CNT, [0.0, 1.5, 1.0]), (MC, np.array([[2], [3], [1]])), (BIN, np.array([[0], [1], [1]])), (CNT, np.array([[0.0], [1.5], [1.0]])), (MMC, np.array([[0, 2], [1, 3], [2, 3]])), (MCN, np.array([[0.5, 2.0], [1.1, 3.0], [2.0, 3.0]])), ] # expected type given input types, or None for error # (types will be tried in either order) EXPECTED = { (IND, IND): IND, (MC, MC): MC, (BIN, BIN): BIN, (MC, IND): None, (BIN, IND): None, (BIN, MC): MC, # Disallowed types (CNT, CNT): None, (MMC, MMC): None, (MCN, MCN): None, (IND, CNT): None, (MC, CNT): None, (BIN, CNT): None, (MMC, CNT): None, (MCN, CNT): None, (IND, MMC): None, (MC, MMC): None, (BIN, MMC): None, (MCN, MMC): None, (IND, MCN): None, (MC, MCN): None, (BIN, MCN): None, }
for (type1, y1), (type2, y2) in product(EXAMPLES, repeat=2): try: expected = EXPECTED[type1, type2] except KeyError: expected = EXPECTED[type2, type1] if expected is None: with pytest.raises(ValueError): _check_targets(y1, y2)
if type1 != type2: err_msg = ( "Classification metrics can't handle a mix " "of {0} and {1} targets".format(type1, type2) ) with pytest.raises(ValueError, match=err_msg): _check_targets(y1, y2)
else: if type1 not in (BIN, MC, IND): err_msg = "{0} is not supported".format(type1) with pytest.raises(ValueError, match=err_msg): _check_targets(y1, y2)
else: merged_type, y1out, y2out = _check_targets(y1, y2) assert merged_type == expected if merged_type.startswith("multilabel"): assert y1out.format == "csr" assert y2out.format == "csr" else: assert_array_equal(y1out, np.squeeze(y1)) assert_array_equal(y2out, np.squeeze(y2)) with pytest.raises(ValueError): _check_targets(y1[:-1], y2)
# Make sure seq of seq is not supported y1 = [(1, 2), (0, 2, 3)] y2 = [(2,), (0, 2)] msg = ( "You appear to be using a legacy multi-label data representation. " "Sequence of sequences are no longer supported; use a binary array" " or sparse matrix instead - the MultiLabelBinarizer" " transformer can convert to this format." ) with pytest.raises(ValueError, match=msg): _check_targets(y1, y2)
def test__check_targets_multiclass_with_both_y_true_and_y_pred_binary(): # https://github.com/scikit-learn/scikit-learn/issues/8098 y_true = [0, 1] y_pred = [0, -1] assert _check_targets(y_true, y_pred)[0] == "multiclass"
def test_hinge_loss_binary(): y_true = np.array([-1, 1, 1, -1]) pred_decision = np.array([-8.5, 0.5, 1.5, -0.3]) assert hinge_loss(y_true, pred_decision) == 1.2 / 4
y_true = np.array([0, 2, 2, 0]) pred_decision = np.array([-8.5, 0.5, 1.5, -0.3]) assert hinge_loss(y_true, pred_decision) == 1.2 / 4
def test_hinge_loss_multiclass(): pred_decision = np.array( [ [+0.36, -0.17, -0.58, -0.99], [-0.54, -0.37, -0.48, -0.58], [-1.45, -0.58, -0.38, -0.17], [-0.54, -0.38, -0.48, -0.58], [-2.36, -0.79, -0.27, +0.24], [-1.45, -0.58, -0.38, -0.17], ] ) y_true = np.array([0, 1, 2, 1, 3, 2]) dummy_losses = np.array( [ 1 - pred_decision[0][0] + pred_decision[0][1], 1 - pred_decision[1][1] + pred_decision[1][2], 1 - pred_decision[2][2] + pred_decision[2][3], 1 - pred_decision[3][1] + pred_decision[3][2], 1 - pred_decision[4][3] + pred_decision[4][2], 1 - pred_decision[5][2] + pred_decision[5][3], ] ) np.clip(dummy_losses, 0, None, out=dummy_losses) dummy_hinge_loss = np.mean(dummy_losses) assert hinge_loss(y_true, pred_decision) == dummy_hinge_loss
def test_hinge_loss_multiclass_missing_labels_with_labels_none(): y_true = np.array([0, 1, 2, 2]) pred_decision = np.array( [ [+1.27, 0.034, -0.68, -1.40], [-1.45, -0.58, -0.38, -0.17], [-2.36, -0.79, -0.27, +0.24], [-2.36, -0.79, -0.27, +0.24], ] ) error_message = ( "Please include all labels in y_true or pass labels as third argument" ) with pytest.raises(ValueError, match=error_message): hinge_loss(y_true, pred_decision)
def test_hinge_loss_multiclass_no_consistent_pred_decision_shape(): # test for inconsistency between multiclass problem and pred_decision # argument y_true = np.array([2, 1, 0, 1, 0, 1, 1]) pred_decision = np.array([0, 1, 2, 1, 0, 2, 1]) error_message = ( "The shape of pred_decision cannot be 1d array" "with a multiclass target. pred_decision shape " "must be (n_samples, n_classes), that is " "(7, 3). Got: (7,)" ) with pytest.raises(ValueError, match=re.escape(error_message)): hinge_loss(y_true=y_true, pred_decision=pred_decision)
# test for inconsistency between pred_decision shape and labels number pred_decision = np.array([[0, 1], [0, 1], [0, 1], [0, 1], [2, 0], [0, 1], [1, 0]]) labels = [0, 1, 2] error_message = ( "The shape of pred_decision is not " "consistent with the number of classes. " "With a multiclass target, pred_decision " "shape must be (n_samples, n_classes), that is " "(7, 3). Got: (7, 2)" ) with pytest.raises(ValueError, match=re.escape(error_message)): hinge_loss(y_true=y_true, pred_decision=pred_decision, labels=labels)
def test_hinge_loss_multiclass_with_missing_labels(): pred_decision = np.array( [ [+0.36, -0.17, -0.58, -0.99], [-0.55, -0.38, -0.48, -0.58], [-1.45, -0.58, -0.38, -0.17], [-0.55, -0.38, -0.48, -0.58], [-1.45, -0.58, -0.38, -0.17], ] ) y_true = np.array([0, 1, 2, 1, 2]) labels = np.array([0, 1, 2, 3]) dummy_losses = np.array( [ 1 - pred_decision[0][0] + pred_decision[0][1], 1 - pred_decision[1][1] + pred_decision[1][2], 1 - pred_decision[2][2] + pred_decision[2][3], 1 - pred_decision[3][1] + pred_decision[3][2], 1 - pred_decision[4][2] + pred_decision[4][3], ] ) np.clip(dummy_losses, 0, None, out=dummy_losses) dummy_hinge_loss = np.mean(dummy_losses) assert hinge_loss(y_true, pred_decision, labels=labels) == dummy_hinge_loss
def test_hinge_loss_multiclass_missing_labels_only_two_unq_in_y_true(): # non-regression test for: # https://github.com/scikit-learn/scikit-learn/issues/17630 # check that we can compute the hinge loss when providing an array # with labels allowing to not have all labels in y_true pred_decision = np.array( [ [+0.36, -0.17, -0.58], [-0.15, -0.58, -0.48], [-1.45, -0.58, -0.38], [-0.55, -0.78, -0.42], [-1.45, -0.58, -0.38], ] ) y_true = np.array([0, 2, 2, 0, 2]) labels = np.array([0, 1, 2]) dummy_losses = np.array( [ 1 - pred_decision[0][0] + pred_decision[0][1], 1 - pred_decision[1][2] + pred_decision[1][0], 1 - pred_decision[2][2] + pred_decision[2][1], 1 - pred_decision[3][0] + pred_decision[3][2], 1 - pred_decision[4][2] + pred_decision[4][1], ] ) np.clip(dummy_losses, 0, None, out=dummy_losses) dummy_hinge_loss = np.mean(dummy_losses) assert_almost_equal( hinge_loss(y_true, pred_decision, labels=labels), dummy_hinge_loss )
def test_hinge_loss_multiclass_invariance_lists(): # Currently, invariance of string and integer labels cannot be tested # in common invariance tests because invariance tests for multiclass # decision functions is not implemented yet. y_true = ["blue", "green", "red", "green", "white", "red"] pred_decision = [ [+0.36, -0.17, -0.58, -0.99], [-0.55, -0.38, -0.48, -0.58], [-1.45, -0.58, -0.38, -0.17], [-0.55, -0.38, -0.48, -0.58], [-2.36, -0.79, -0.27, +0.24], [-1.45, -0.58, -0.38, -0.17], ] dummy_losses = np.array( [ 1 - pred_decision[0][0] + pred_decision[0][1], 1 - pred_decision[1][1] + pred_decision[1][2], 1 - pred_decision[2][2] + pred_decision[2][3], 1 - pred_decision[3][1] + pred_decision[3][2], 1 - pred_decision[4][3] + pred_decision[4][2], 1 - pred_decision[5][2] + pred_decision[5][3], ] ) np.clip(dummy_losses, 0, None, out=dummy_losses) dummy_hinge_loss = np.mean(dummy_losses) assert hinge_loss(y_true, pred_decision) == dummy_hinge_loss
def test_log_loss(): # binary case with symbolic labels ("no" < "yes") y_true = ["no", "no", "no", "yes", "yes", "yes"] y_pred = np.array( [[0.5, 0.5], [0.1, 0.9], [0.01, 0.99], [0.9, 0.1], [0.75, 0.25], [0.001, 0.999]] ) loss = log_loss(y_true, y_pred) loss_true = -np.mean(bernoulli.logpmf(np.array(y_true) == "yes", y_pred[:, 1])) assert_almost_equal(loss, loss_true)
# multiclass case; adapted from http://bit.ly/RJJHWA y_true = [1, 0, 2] y_pred = [[0.2, 0.7, 0.1], [0.6, 0.2, 0.2], [0.6, 0.1, 0.3]] loss = log_loss(y_true, y_pred, normalize=True) assert_almost_equal(loss, 0.6904911)
# check that we got all the shapes and axes right # by doubling the length of y_true and y_pred y_true *= 2 y_pred *= 2 loss = log_loss(y_true, y_pred, normalize=False) assert_almost_equal(loss, 0.6904911 * 6, decimal=6)
# check eps and handling of absolute zero and one probabilities y_pred = np.asarray(y_pred) > 0.5 loss = log_loss(y_true, y_pred, normalize=True, eps=0.1) assert_almost_equal(loss, log_loss(y_true, np.clip(y_pred, 0.1, 0.9)))
# binary case: check correct boundary values for eps = 0 assert log_loss([0, 1], [0, 1], eps=0) == 0 assert log_loss([0, 1], [0, 0], eps=0) == np.inf assert log_loss([0, 1], [1, 1], eps=0) == np.inf
# multiclass case: check correct boundary values for eps = 0 assert log_loss([0, 1, 2], [[1, 0, 0], [0, 1, 0], [0, 0, 1]], eps=0) == 0 assert log_loss([0, 1, 2], [[0, 0.5, 0.5], [0, 1, 0], [0, 0, 1]], eps=0) == np.inf
# raise error if number of classes are not equal. y_true = [1, 0, 2] y_pred = [[0.2, 0.7], [0.6, 0.5], [0.4, 0.1]] with pytest.raises(ValueError): log_loss(y_true, y_pred)
# case when y_true is a string array object y_true = ["ham", "spam", "spam", "ham"] y_pred = [[0.2, 0.7], [0.6, 0.5], [0.4, 0.1], [0.7, 0.2]] loss = log_loss(y_true, y_pred) assert_almost_equal(loss, 1.0383217, decimal=6)
# test labels option
y_true = [2, 2] y_pred = [[0.2, 0.7], [0.6, 0.5]] y_score = np.array([[0.1, 0.9], [0.1, 0.9]]) error_str = ( r"y_true contains only one label \(2\). Please provide " r"the true labels explicitly through the labels argument." ) with pytest.raises(ValueError, match=error_str): log_loss(y_true, y_pred)
y_pred = [[0.2, 0.7], [0.6, 0.5], [0.2, 0.3]] error_str = "Found input variables with inconsistent numbers of samples: [3, 2]" (ValueError, error_str, log_loss, y_true, y_pred)
# works when the labels argument is used
true_log_loss = -np.mean(np.log(y_score[:, 1])) calculated_log_loss = log_loss(y_true, y_score, labels=[1, 2]) assert_almost_equal(calculated_log_loss, true_log_loss)
# ensure labels work when len(np.unique(y_true)) != y_pred.shape[1] y_true = [1, 2, 2] y_score2 = [[0.2, 0.7, 0.3], [0.6, 0.5, 0.3], [0.3, 0.9, 0.1]] loss = log_loss(y_true, y_score2, labels=[1, 2, 3]) assert_almost_equal(loss, 1.0630345, decimal=6)
def test_log_loss_eps_auto(global_dtype): """Check the behaviour of `eps="auto"` that changes depending on the input array dtype. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/24315 """ y_true = np.array([0, 1], dtype=global_dtype) y_pred = y_true.copy()
loss = log_loss(y_true, y_pred, eps="auto") assert np.isfinite(loss)
def test_log_loss_eps_auto_float16(): """Check the behaviour of `eps="auto"` for np.float16""" y_true = np.array([0, 1], dtype=np.float16) y_pred = y_true.copy()
loss = log_loss(y_true, y_pred, eps="auto") assert np.isfinite(loss)
def test_log_loss_pandas_input(): # case when input is a pandas series and dataframe gh-5715 y_tr = np.array(["ham", "spam", "spam", "ham"]) y_pr = np.array([[0.2, 0.7], [0.6, 0.5], [0.4, 0.1], [0.7, 0.2]]) types = [(MockDataFrame, MockDataFrame)] try: from pandas import Series, DataFrame
types.append((Series, DataFrame)) except ImportError: pass for TrueInputType, PredInputType in types: # y_pred dataframe, y_true series y_true, y_pred = TrueInputType(y_tr), PredInputType(y_pr) loss = log_loss(y_true, y_pred) assert_almost_equal(loss, 1.0383217, decimal=6)
def test_brier_score_loss(): # Check brier_score_loss function y_true = np.array([0, 1, 1, 0, 1, 1]) y_pred = np.array([0.1, 0.8, 0.9, 0.3, 1.0, 0.95]) true_score = linalg.norm(y_true - y_pred) ** 2 / len(y_true)
assert_almost_equal(brier_score_loss(y_true, y_true), 0.0) assert_almost_equal(brier_score_loss(y_true, y_pred), true_score) assert_almost_equal(brier_score_loss(1.0 + y_true, y_pred), true_score) assert_almost_equal(brier_score_loss(2 * y_true - 1, y_pred), true_score) with pytest.raises(ValueError): brier_score_loss(y_true, y_pred[1:]) with pytest.raises(ValueError): brier_score_loss(y_true, y_pred + 1.0) with pytest.raises(ValueError): brier_score_loss(y_true, y_pred - 1.0)
# ensure to raise an error for multiclass y_true y_true = np.array([0, 1, 2, 0]) y_pred = np.array([0.8, 0.6, 0.4, 0.2]) error_message = ( "Only binary classification is supported. The type of the target is multiclass" )
with pytest.raises(ValueError, match=error_message): brier_score_loss(y_true, y_pred)
# calculate correctly when there's only one class in y_true assert_almost_equal(brier_score_loss([-1], [0.4]), 0.16) assert_almost_equal(brier_score_loss([0], [0.4]), 0.16) assert_almost_equal(brier_score_loss([1], [0.4]), 0.36) assert_almost_equal(brier_score_loss(["foo"], [0.4], pos_label="bar"), 0.16) assert_almost_equal(brier_score_loss(["foo"], [0.4], pos_label="foo"), 0.36)
def test_balanced_accuracy_score_unseen(): msg = "y_pred contains classes not in y_true" with pytest.warns(UserWarning, match=msg): balanced_accuracy_score([0, 0, 0], [0, 0, 1])
@pytest.mark.parametrize( "y_true,y_pred", [ (["a", "b", "a", "b"], ["a", "a", "a", "b"]), (["a", "b", "c", "b"], ["a", "a", "a", "b"]), (["a", "a", "a", "b"], ["a", "b", "c", "b"]), ],)def test_balanced_accuracy_score(y_true, y_pred): macro_recall = recall_score( y_true, y_pred, average="macro", labels=np.unique(y_true) ) with ignore_warnings(): # Warnings are tested in test_balanced_accuracy_score_unseen balanced = balanced_accuracy_score(y_true, y_pred) assert balanced == pytest.approx(macro_recall) adjusted = balanced_accuracy_score(y_true, y_pred, adjusted=True) chance = balanced_accuracy_score(y_true, np.full_like(y_true, y_true[0])) assert adjusted == (balanced - chance) / (1 - chance)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734from functools import partialfrom inspect import signaturefrom itertools import productfrom itertools import chainfrom itertools import permutations
import numpy as npimport scipy.sparse as sp
import pytest
from sklearn.datasets import make_multilabel_classificationfrom sklearn.preprocessing import LabelBinarizerfrom sklearn.utils.multiclass import type_of_targetfrom sklearn.utils.validation import _num_samplesfrom sklearn.utils.validation import check_random_statefrom sklearn.utils import shuffle
from sklearn.utils._testing import assert_allclosefrom sklearn.utils._testing import assert_almost_equalfrom sklearn.utils._testing import assert_array_equalfrom sklearn.utils._testing import assert_array_lessfrom sklearn.utils._testing import ignore_warnings
from sklearn.metrics import accuracy_scorefrom sklearn.metrics import average_precision_scorefrom sklearn.metrics import balanced_accuracy_scorefrom sklearn.metrics import brier_score_lossfrom sklearn.metrics import cohen_kappa_scorefrom sklearn.metrics import confusion_matrixfrom sklearn.metrics import coverage_errorfrom sklearn.metrics import d2_tweedie_scorefrom sklearn.metrics import d2_pinball_scorefrom sklearn.metrics import d2_absolute_error_scorefrom sklearn.metrics import det_curvefrom sklearn.metrics import explained_variance_scorefrom sklearn.metrics import f1_scorefrom sklearn.metrics import fbeta_scorefrom sklearn.metrics import hamming_lossfrom sklearn.metrics import hinge_lossfrom sklearn.metrics import jaccard_scorefrom sklearn.metrics import label_ranking_average_precision_scorefrom sklearn.metrics import label_ranking_lossfrom sklearn.metrics import log_lossfrom sklearn.metrics import max_errorfrom sklearn.metrics import matthews_corrcoeffrom sklearn.metrics import mean_absolute_errorfrom sklearn.metrics import mean_absolute_percentage_errorfrom sklearn.metrics import mean_squared_errorfrom sklearn.metrics import mean_tweedie_deviancefrom sklearn.metrics import mean_poisson_deviancefrom sklearn.metrics import mean_gamma_deviancefrom sklearn.metrics import median_absolute_errorfrom sklearn.metrics import multilabel_confusion_matrixfrom sklearn.metrics import mean_pinball_lossfrom sklearn.metrics import precision_recall_curvefrom sklearn.metrics import precision_scorefrom sklearn.metrics import r2_scorefrom sklearn.metrics import recall_scorefrom sklearn.metrics import roc_auc_scorefrom sklearn.metrics import roc_curvefrom sklearn.metrics import zero_one_lossfrom sklearn.metrics import ndcg_scorefrom sklearn.metrics import dcg_scorefrom sklearn.metrics import top_k_accuracy_score
from sklearn.metrics._base import _average_binary_score
# Note toward developers about metric testing# -------------------------------------------# It is often possible to write one general test for several metrics:## - invariance properties, e.g. invariance to sample order# - common behavior for an argument, e.g. the "normalize" with value True# will return the mean of the metrics and with value False will return# the sum of the metrics.## In order to improve the overall metric testing, it is a good idea to write# first a specific test for the given metric and then add a general test for# all metrics that have the same behavior.## Two types of datastructures are used in order to implement this system:# dictionaries of metrics and lists of metrics with common properties.## Dictionaries of metrics# ------------------------# The goal of having those dictionaries is to have an easy way to call a# particular metric and associate a name to each function:## - REGRESSION_METRICS: all regression metrics.# - CLASSIFICATION_METRICS: all classification metrics# which compare a ground truth and the estimated targets as returned by a# classifier.# - THRESHOLDED_METRICS: all classification metrics which# compare a ground truth and a score, e.g. estimated probabilities or# decision function (format might vary)## Those dictionaries will be used to test systematically some invariance# properties, e.g. invariance toward several input layout.#
REGRESSION_METRICS = { "max_error": max_error, "mean_absolute_error": mean_absolute_error, "mean_squared_error": mean_squared_error, "mean_pinball_loss": mean_pinball_loss, "median_absolute_error": median_absolute_error, "mean_absolute_percentage_error": mean_absolute_percentage_error, "explained_variance_score": explained_variance_score, "r2_score": partial(r2_score, multioutput="variance_weighted"), "mean_normal_deviance": partial(mean_tweedie_deviance, power=0), "mean_poisson_deviance": mean_poisson_deviance, "mean_gamma_deviance": mean_gamma_deviance, "mean_compound_poisson_deviance": partial(mean_tweedie_deviance, power=1.4), "d2_tweedie_score": partial(d2_tweedie_score, power=1.4), "d2_pinball_score": d2_pinball_score, "d2_absolute_error_score": d2_absolute_error_score,}
CLASSIFICATION_METRICS = { "accuracy_score": accuracy_score, "balanced_accuracy_score": balanced_accuracy_score, "adjusted_balanced_accuracy_score": partial(balanced_accuracy_score, adjusted=True), "unnormalized_accuracy_score": partial(accuracy_score, normalize=False), # `confusion_matrix` returns absolute values and hence behaves unnormalized # . Naming it with an unnormalized_ prefix is necessary for this module to # skip sample_weight scaling checks which will fail for unnormalized # metrics. "unnormalized_confusion_matrix": confusion_matrix, "normalized_confusion_matrix": lambda *args, **kwargs: ( confusion_matrix(*args, **kwargs).astype("float") / confusion_matrix(*args, **kwargs).sum(axis=1)[:, np.newaxis] ), "unnormalized_multilabel_confusion_matrix": multilabel_confusion_matrix, "unnormalized_multilabel_confusion_matrix_sample": partial( multilabel_confusion_matrix, samplewise=True ), "hamming_loss": hamming_loss, "zero_one_loss": zero_one_loss, "unnormalized_zero_one_loss": partial(zero_one_loss, normalize=False), # These are needed to test averaging "jaccard_score": jaccard_score, "precision_score": precision_score, "recall_score": recall_score, "f1_score": f1_score, "f2_score": partial(fbeta_score, beta=2), "f0.5_score": partial(fbeta_score, beta=0.5), "matthews_corrcoef_score": matthews_corrcoef, "weighted_f0.5_score": partial(fbeta_score, average="weighted", beta=0.5), "weighted_f1_score": partial(f1_score, average="weighted"), "weighted_f2_score": partial(fbeta_score, average="weighted", beta=2), "weighted_precision_score": partial(precision_score, average="weighted"), "weighted_recall_score": partial(recall_score, average="weighted"), "weighted_jaccard_score": partial(jaccard_score, average="weighted"), "micro_f0.5_score": partial(fbeta_score, average="micro", beta=0.5), "micro_f1_score": partial(f1_score, average="micro"), "micro_f2_score": partial(fbeta_score, average="micro", beta=2), "micro_precision_score": partial(precision_score, average="micro"), "micro_recall_score": partial(recall_score, average="micro"), "micro_jaccard_score": partial(jaccard_score, average="micro"), "macro_f0.5_score": partial(fbeta_score, average="macro", beta=0.5), "macro_f1_score": partial(f1_score, average="macro"), "macro_f2_score": partial(fbeta_score, average="macro", beta=2), "macro_precision_score": partial(precision_score, average="macro"), "macro_recall_score": partial(recall_score, average="macro"), "macro_jaccard_score": partial(jaccard_score, average="macro"), "samples_f0.5_score": partial(fbeta_score, average="samples", beta=0.5), "samples_f1_score": partial(f1_score, average="samples"), "samples_f2_score": partial(fbeta_score, average="samples", beta=2), "samples_precision_score": partial(precision_score, average="samples"), "samples_recall_score": partial(recall_score, average="samples"), "samples_jaccard_score": partial(jaccard_score, average="samples"), "cohen_kappa_score": cohen_kappa_score,}
def precision_recall_curve_padded_thresholds(*args, **kwargs): """ The dimensions of precision-recall pairs and the threshold array as returned by the precision_recall_curve do not match. See func:`sklearn.metrics.precision_recall_curve`
This prevents implicit conversion of return value triple to an higher dimensional np.array of dtype('float64') (it will be of dtype('object) instead). This again is needed for assert_array_equal to work correctly.
As a workaround we pad the threshold array with NaN values to match the dimension of precision and recall arrays respectively. """ precision, recall, thresholds = precision_recall_curve(*args, **kwargs)
pad_threshholds = len(precision) - len(thresholds)
return np.array( [ precision, recall, np.pad( thresholds.astype(np.float64), pad_width=(0, pad_threshholds), mode="constant", constant_values=[np.nan], ), ] )
CURVE_METRICS = { "roc_curve": roc_curve, "precision_recall_curve": precision_recall_curve_padded_thresholds, "det_curve": det_curve,}
THRESHOLDED_METRICS = { "coverage_error": coverage_error, "label_ranking_loss": label_ranking_loss, "log_loss": log_loss, "unnormalized_log_loss": partial(log_loss, normalize=False), "hinge_loss": hinge_loss, "brier_score_loss": brier_score_loss, "roc_auc_score": roc_auc_score, # default: average="macro" "weighted_roc_auc": partial(roc_auc_score, average="weighted"), "samples_roc_auc": partial(roc_auc_score, average="samples"), "micro_roc_auc": partial(roc_auc_score, average="micro"), "ovr_roc_auc": partial(roc_auc_score, average="macro", multi_class="ovr"), "weighted_ovr_roc_auc": partial( roc_auc_score, average="weighted", multi_class="ovr" ), "ovo_roc_auc": partial(roc_auc_score, average="macro", multi_class="ovo"), "weighted_ovo_roc_auc": partial( roc_auc_score, average="weighted", multi_class="ovo" ), "partial_roc_auc": partial(roc_auc_score, max_fpr=0.5), "average_precision_score": average_precision_score, # default: average="macro" "weighted_average_precision_score": partial( average_precision_score, average="weighted" ), "samples_average_precision_score": partial( average_precision_score, average="samples" ), "micro_average_precision_score": partial(average_precision_score, average="micro"), "label_ranking_average_precision_score": label_ranking_average_precision_score, "ndcg_score": ndcg_score, "dcg_score": dcg_score, "top_k_accuracy_score": top_k_accuracy_score,}
ALL_METRICS = dict()ALL_METRICS.update(THRESHOLDED_METRICS)ALL_METRICS.update(CLASSIFICATION_METRICS)ALL_METRICS.update(REGRESSION_METRICS)ALL_METRICS.update(CURVE_METRICS)
# Lists of metrics with common properties# ---------------------------------------# Lists of metrics with common properties are used to test systematically some# functionalities and invariance, e.g. SYMMETRIC_METRICS lists all metrics that# are symmetric with respect to their input argument y_true and y_pred.## When you add a new metric or functionality, check if a general test# is already written.
# Those metrics don't support binary inputsMETRIC_UNDEFINED_BINARY = { "samples_f0.5_score", "samples_f1_score", "samples_f2_score", "samples_precision_score", "samples_recall_score", "samples_jaccard_score", "coverage_error", "unnormalized_multilabel_confusion_matrix_sample", "label_ranking_loss", "label_ranking_average_precision_score", "dcg_score", "ndcg_score",}
# Those metrics don't support multiclass inputsMETRIC_UNDEFINED_MULTICLASS = { "brier_score_loss", "micro_roc_auc", "samples_roc_auc", "partial_roc_auc", "roc_auc_score", "weighted_roc_auc", "average_precision_score", "weighted_average_precision_score", "micro_average_precision_score", "samples_average_precision_score", "jaccard_score", # with default average='binary', multiclass is prohibited "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score", # curves "roc_curve", "precision_recall_curve", "det_curve",}
# Metric undefined with "binary" or "multiclass" inputMETRIC_UNDEFINED_BINARY_MULTICLASS = METRIC_UNDEFINED_BINARY.union( METRIC_UNDEFINED_MULTICLASS)
# Metrics with an "average" argumentMETRICS_WITH_AVERAGING = { "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score", "jaccard_score",}
# Threshold-based metrics with an "average" argumentTHRESHOLDED_METRICS_WITH_AVERAGING = { "roc_auc_score", "average_precision_score", "partial_roc_auc",}
# Metrics with a "pos_label" argumentMETRICS_WITH_POS_LABEL = { "roc_curve", "precision_recall_curve", "det_curve", "brier_score_loss", "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score", "jaccard_score", "average_precision_score", "weighted_average_precision_score", "micro_average_precision_score", "samples_average_precision_score",}
# Metrics with a "labels" argument# TODO: Handle multi_class metrics that has a labels argument as well as a# decision function argument. e.g hinge_lossMETRICS_WITH_LABELS = { "unnormalized_confusion_matrix", "normalized_confusion_matrix", "roc_curve", "precision_recall_curve", "det_curve", "precision_score", "recall_score", "f1_score", "f2_score", "f0.5_score", "jaccard_score", "weighted_f0.5_score", "weighted_f1_score", "weighted_f2_score", "weighted_precision_score", "weighted_recall_score", "weighted_jaccard_score", "micro_f0.5_score", "micro_f1_score", "micro_f2_score", "micro_precision_score", "micro_recall_score", "micro_jaccard_score", "macro_f0.5_score", "macro_f1_score", "macro_f2_score", "macro_precision_score", "macro_recall_score", "macro_jaccard_score", "unnormalized_multilabel_confusion_matrix", "unnormalized_multilabel_confusion_matrix_sample", "cohen_kappa_score",}
# Metrics with a "normalize" optionMETRICS_WITH_NORMALIZE_OPTION = { "accuracy_score", "top_k_accuracy_score", "zero_one_loss",}
# Threshold-based metrics with "multilabel-indicator" format supportTHRESHOLDED_MULTILABEL_METRICS = { "log_loss", "unnormalized_log_loss", "roc_auc_score", "weighted_roc_auc", "samples_roc_auc", "micro_roc_auc", "partial_roc_auc", "average_precision_score", "weighted_average_precision_score", "samples_average_precision_score", "micro_average_precision_score", "coverage_error", "label_ranking_loss", "ndcg_score", "dcg_score", "label_ranking_average_precision_score",}
# Classification metrics with "multilabel-indicator" formatMULTILABELS_METRICS = { "accuracy_score", "unnormalized_accuracy_score", "hamming_loss", "zero_one_loss", "unnormalized_zero_one_loss", "weighted_f0.5_score", "weighted_f1_score", "weighted_f2_score", "weighted_precision_score", "weighted_recall_score", "weighted_jaccard_score", "macro_f0.5_score", "macro_f1_score", "macro_f2_score", "macro_precision_score", "macro_recall_score", "macro_jaccard_score", "micro_f0.5_score", "micro_f1_score", "micro_f2_score", "micro_precision_score", "micro_recall_score", "micro_jaccard_score", "unnormalized_multilabel_confusion_matrix", "samples_f0.5_score", "samples_f1_score", "samples_f2_score", "samples_precision_score", "samples_recall_score", "samples_jaccard_score",}
# Regression metrics with "multioutput-continuous" format supportMULTIOUTPUT_METRICS = { "mean_absolute_error", "median_absolute_error", "mean_squared_error", "r2_score", "explained_variance_score", "mean_absolute_percentage_error", "mean_pinball_loss", "d2_pinball_score", "d2_absolute_error_score",}
# Symmetric with respect to their input arguments y_true and y_pred# metric(y_true, y_pred) == metric(y_pred, y_true).SYMMETRIC_METRICS = { "accuracy_score", "unnormalized_accuracy_score", "hamming_loss", "zero_one_loss", "unnormalized_zero_one_loss", "micro_jaccard_score", "macro_jaccard_score", "jaccard_score", "samples_jaccard_score", "f1_score", "micro_f1_score", "macro_f1_score", "weighted_recall_score", # P = R = F = accuracy in multiclass case "micro_f0.5_score", "micro_f1_score", "micro_f2_score", "micro_precision_score", "micro_recall_score", "matthews_corrcoef_score", "mean_absolute_error", "mean_squared_error", "median_absolute_error", "max_error", # Pinball loss is only symmetric for alpha=0.5 which is the default. "mean_pinball_loss", "cohen_kappa_score", "mean_normal_deviance",}
# Asymmetric with respect to their input arguments y_true and y_pred# metric(y_true, y_pred) != metric(y_pred, y_true).NOT_SYMMETRIC_METRICS = { "balanced_accuracy_score", "adjusted_balanced_accuracy_score", "explained_variance_score", "r2_score", "unnormalized_confusion_matrix", "normalized_confusion_matrix", "roc_curve", "precision_recall_curve", "det_curve", "precision_score", "recall_score", "f2_score", "f0.5_score", "weighted_f0.5_score", "weighted_f1_score", "weighted_f2_score", "weighted_precision_score", "weighted_jaccard_score", "unnormalized_multilabel_confusion_matrix", "macro_f0.5_score", "macro_f2_score", "macro_precision_score", "macro_recall_score", "hinge_loss", "mean_gamma_deviance", "mean_poisson_deviance", "mean_compound_poisson_deviance", "d2_tweedie_score", "d2_pinball_score", "d2_absolute_error_score", "mean_absolute_percentage_error",}
# No Sample weight supportMETRICS_WITHOUT_SAMPLE_WEIGHT = { "median_absolute_error", "max_error", "ovo_roc_auc", "weighted_ovo_roc_auc",}
METRICS_REQUIRE_POSITIVE_Y = { "mean_poisson_deviance", "mean_gamma_deviance", "mean_compound_poisson_deviance", "d2_tweedie_score",}
def _require_positive_targets(y1, y2): """Make targets strictly positive""" offset = abs(min(y1.min(), y2.min())) + 1 y1 += offset y2 += offset return y1, y2
def test_symmetry_consistency():
# We shouldn't forget any metrics assert ( SYMMETRIC_METRICS | NOT_SYMMETRIC_METRICS | set(THRESHOLDED_METRICS) | METRIC_UNDEFINED_BINARY_MULTICLASS ) == set(ALL_METRICS)
assert (SYMMETRIC_METRICS & NOT_SYMMETRIC_METRICS) == set()
@pytest.mark.parametrize("name", sorted(SYMMETRIC_METRICS))def test_symmetric_metric(name): # Test the symmetry of score and loss functions random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(20,)) y_pred = random_state.randint(0, 2, size=(20,))
if name in METRICS_REQUIRE_POSITIVE_Y: y_true, y_pred = _require_positive_targets(y_true, y_pred)
y_true_bin = random_state.randint(0, 2, size=(20, 25)) y_pred_bin = random_state.randint(0, 2, size=(20, 25))
metric = ALL_METRICS[name] if name in METRIC_UNDEFINED_BINARY: if name in MULTILABELS_METRICS: assert_allclose( metric(y_true_bin, y_pred_bin), metric(y_pred_bin, y_true_bin), err_msg="%s is not symmetric" % name, ) else: assert False, "This case is currently unhandled" else: assert_allclose( metric(y_true, y_pred), metric(y_pred, y_true), err_msg="%s is not symmetric" % name, )
@pytest.mark.parametrize("name", sorted(NOT_SYMMETRIC_METRICS))def test_not_symmetric_metric(name): # Test the symmetry of score and loss functions random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(20,)) y_pred = random_state.randint(0, 2, size=(20,))
if name in METRICS_REQUIRE_POSITIVE_Y: y_true, y_pred = _require_positive_targets(y_true, y_pred)
metric = ALL_METRICS[name]
# use context manager to supply custom error message with pytest.raises(AssertionError): assert_array_equal(metric(y_true, y_pred), metric(y_pred, y_true)) raise ValueError("%s seems to be symmetric" % name)
@pytest.mark.parametrize( "name", sorted(set(ALL_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS))def test_sample_order_invariance(name): random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(20,)) y_pred = random_state.randint(0, 2, size=(20,))
if name in METRICS_REQUIRE_POSITIVE_Y: y_true, y_pred = _require_positive_targets(y_true, y_pred)
y_true_shuffle, y_pred_shuffle = shuffle(y_true, y_pred, random_state=0)
with ignore_warnings(): metric = ALL_METRICS[name] assert_allclose( metric(y_true, y_pred), metric(y_true_shuffle, y_pred_shuffle), err_msg="%s is not sample order invariant" % name, )
@ignore_warningsdef test_sample_order_invariance_multilabel_and_multioutput(): random_state = check_random_state(0)
# Generate some data y_true = random_state.randint(0, 2, size=(20, 25)) y_pred = random_state.randint(0, 2, size=(20, 25)) y_score = random_state.normal(size=y_true.shape)
y_true_shuffle, y_pred_shuffle, y_score_shuffle = shuffle( y_true, y_pred, y_score, random_state=0 )
for name in MULTILABELS_METRICS: metric = ALL_METRICS[name] assert_allclose( metric(y_true, y_pred), metric(y_true_shuffle, y_pred_shuffle), err_msg="%s is not sample order invariant" % name, )
for name in THRESHOLDED_MULTILABEL_METRICS: metric = ALL_METRICS[name] assert_allclose( metric(y_true, y_score), metric(y_true_shuffle, y_score_shuffle), err_msg="%s is not sample order invariant" % name, )
for name in MULTIOUTPUT_METRICS: metric = ALL_METRICS[name] assert_allclose( metric(y_true, y_score), metric(y_true_shuffle, y_score_shuffle), err_msg="%s is not sample order invariant" % name, ) assert_allclose( metric(y_true, y_pred), metric(y_true_shuffle, y_pred_shuffle), err_msg="%s is not sample order invariant" % name, )
@pytest.mark.parametrize( "name", sorted(set(ALL_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS))def test_format_invariance_with_1d_vectors(name): random_state = check_random_state(0) y1 = random_state.randint(0, 2, size=(20,)) y2 = random_state.randint(0, 2, size=(20,))
if name in METRICS_REQUIRE_POSITIVE_Y: y1, y2 = _require_positive_targets(y1, y2)
y1_list = list(y1) y2_list = list(y2)
y1_1d, y2_1d = np.array(y1), np.array(y2) assert_array_equal(y1_1d.ndim, 1) assert_array_equal(y2_1d.ndim, 1) y1_column = np.reshape(y1_1d, (-1, 1)) y2_column = np.reshape(y2_1d, (-1, 1)) y1_row = np.reshape(y1_1d, (1, -1)) y2_row = np.reshape(y2_1d, (1, -1))
with ignore_warnings(): metric = ALL_METRICS[name]
measure = metric(y1, y2)
assert_allclose( metric(y1_list, y2_list), measure, err_msg="%s is not representation invariant with list" % name, )
assert_allclose( metric(y1_1d, y2_1d), measure, err_msg="%s is not representation invariant with np-array-1d" % name, )
assert_allclose( metric(y1_column, y2_column), measure, err_msg="%s is not representation invariant with np-array-column" % name, )
# Mix format support assert_allclose( metric(y1_1d, y2_list), measure, err_msg="%s is not representation invariant with mix np-array-1d and list" % name, )
assert_allclose( metric(y1_list, y2_1d), measure, err_msg="%s is not representation invariant with mix np-array-1d and list" % name, )
assert_allclose( metric(y1_1d, y2_column), measure, err_msg=( "%s is not representation invariant with mix " "np-array-1d and np-array-column" ) % name, )
assert_allclose( metric(y1_column, y2_1d), measure, err_msg=( "%s is not representation invariant with mix " "np-array-1d and np-array-column" ) % name, )
assert_allclose( metric(y1_list, y2_column), measure, err_msg=( "%s is not representation invariant with mix list and np-array-column" ) % name, )
assert_allclose( metric(y1_column, y2_list), measure, err_msg=( "%s is not representation invariant with mix list and np-array-column" ) % name, )
# These mix representations aren't allowed with pytest.raises(ValueError): metric(y1_1d, y2_row) with pytest.raises(ValueError): metric(y1_row, y2_1d) with pytest.raises(ValueError): metric(y1_list, y2_row) with pytest.raises(ValueError): metric(y1_row, y2_list) with pytest.raises(ValueError): metric(y1_column, y2_row) with pytest.raises(ValueError): metric(y1_row, y2_column)
# NB: We do not test for y1_row, y2_row as these may be # interpreted as multilabel or multioutput data. if name not in ( MULTIOUTPUT_METRICS | THRESHOLDED_MULTILABEL_METRICS | MULTILABELS_METRICS ): with pytest.raises(ValueError): metric(y1_row, y2_row)
@pytest.mark.parametrize( "name", sorted(set(CLASSIFICATION_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS))def test_classification_invariance_string_vs_numbers_labels(name): # Ensure that classification metrics with string labels are invariant random_state = check_random_state(0) y1 = random_state.randint(0, 2, size=(20,)) y2 = random_state.randint(0, 2, size=(20,))
y1_str = np.array(["eggs", "spam"])[y1] y2_str = np.array(["eggs", "spam"])[y2]
pos_label_str = "spam" labels_str = ["eggs", "spam"]
with ignore_warnings(): metric = CLASSIFICATION_METRICS[name] measure_with_number = metric(y1, y2)
# Ugly, but handle case with a pos_label and label metric_str = metric if name in METRICS_WITH_POS_LABEL: metric_str = partial(metric_str, pos_label=pos_label_str)
measure_with_str = metric_str(y1_str, y2_str)
assert_array_equal( measure_with_number, measure_with_str, err_msg="{0} failed string vs number invariance test".format(name), )
measure_with_strobj = metric_str(y1_str.astype("O"), y2_str.astype("O")) assert_array_equal( measure_with_number, measure_with_strobj, err_msg="{0} failed string object vs number invariance test".format(name), )
if name in METRICS_WITH_LABELS: metric_str = partial(metric_str, labels=labels_str) measure_with_str = metric_str(y1_str, y2_str) assert_array_equal( measure_with_number, measure_with_str, err_msg="{0} failed string vs number invariance test".format(name), )
measure_with_strobj = metric_str(y1_str.astype("O"), y2_str.astype("O")) assert_array_equal( measure_with_number, measure_with_strobj, err_msg="{0} failed string vs number invariance test".format(name), )
@pytest.mark.parametrize("name", THRESHOLDED_METRICS)def test_thresholded_invariance_string_vs_numbers_labels(name): # Ensure that thresholded metrics with string labels are invariant random_state = check_random_state(0) y1 = random_state.randint(0, 2, size=(20,)) y2 = random_state.randint(0, 2, size=(20,))
y1_str = np.array(["eggs", "spam"])[y1]
pos_label_str = "spam"
with ignore_warnings(): metric = THRESHOLDED_METRICS[name] if name not in METRIC_UNDEFINED_BINARY: # Ugly, but handle case with a pos_label and label metric_str = metric if name in METRICS_WITH_POS_LABEL: metric_str = partial(metric_str, pos_label=pos_label_str)
measure_with_number = metric(y1, y2) measure_with_str = metric_str(y1_str, y2) assert_array_equal( measure_with_number, measure_with_str, err_msg="{0} failed string vs number invariance test".format(name), )
measure_with_strobj = metric_str(y1_str.astype("O"), y2) assert_array_equal( measure_with_number, measure_with_strobj, err_msg="{0} failed string object vs number invariance test".format( name ), ) else: # TODO those metrics doesn't support string label yet with pytest.raises(ValueError): metric(y1_str, y2) with pytest.raises(ValueError): metric(y1_str.astype("O"), y2)
invalids_nan_inf = [ ([0, 1], [np.inf, np.inf]), ([0, 1], [np.nan, np.nan]), ([0, 1], [np.nan, np.inf]), ([0, 1], [np.inf, 1]), ([0, 1], [np.nan, 1]),]
@pytest.mark.parametrize( "metric", chain(THRESHOLDED_METRICS.values(), REGRESSION_METRICS.values()))@pytest.mark.parametrize("y_true, y_score", invalids_nan_inf)def test_regression_thresholded_inf_nan_input(metric, y_true, y_score): # Reshape since coverage_error only accepts 2D arrays. if metric == coverage_error: y_true = [y_true] y_score = [y_score] with pytest.raises(ValueError, match=r"contains (NaN|infinity)"): metric(y_true, y_score)
@pytest.mark.parametrize("metric", CLASSIFICATION_METRICS.values())@pytest.mark.parametrize( "y_true, y_score", invalids_nan_inf + # Add an additional case for classification only # non-regression test for: # https://github.com/scikit-learn/scikit-learn/issues/6809 [ ([np.nan, 1, 2], [1, 2, 3]), ([np.inf, 1, 2], [1, 2, 3]), ], # type: ignore)def test_classification_inf_nan_input(metric, y_true, y_score): """check that classification metrics raise a message mentioning the occurrence of non-finite values in the target vectors.""" if not np.isfinite(y_true).all(): input_name = "y_true" if np.isnan(y_true).any(): unexpected_value = "NaN" else: unexpected_value = "infinity or a value too large" else: input_name = "y_pred" if np.isnan(y_score).any(): unexpected_value = "NaN" else: unexpected_value = "infinity or a value too large"
err_msg = f"Input {input_name} contains {unexpected_value}"
with pytest.raises(ValueError, match=err_msg): metric(y_true, y_score)
@pytest.mark.parametrize("metric", CLASSIFICATION_METRICS.values())def test_classification_binary_continuous_input(metric): """check that classification metrics raise a message of mixed type data with continuous/binary target vectors.""" y_true, y_score = ["a", "b", "a"], [0.1, 0.2, 0.3] err_msg = ( "Classification metrics can't handle a mix of binary and continuous targets" ) with pytest.raises(ValueError, match=err_msg): metric(y_true, y_score)
@ignore_warningsdef check_single_sample(name): # Non-regression test: scores should work with a single sample. # This is important for leave-one-out cross validation. # Score functions tested are those that formerly called np.squeeze, # which turns an array of size 1 into a 0-d array (!). metric = ALL_METRICS[name]
# assert that no exception is thrown if name in METRICS_REQUIRE_POSITIVE_Y: values = [1, 2] else: values = [0, 1] for i, j in product(values, repeat=2): metric([i], [j])
@ignore_warningsdef check_single_sample_multioutput(name): metric = ALL_METRICS[name] for i, j, k, l in product([0, 1], repeat=4): metric(np.array([[i, j]]), np.array([[k, l]]))
@pytest.mark.parametrize( "name", sorted( set(ALL_METRICS) # Those metrics are not always defined with one sample # or in multiclass classification - METRIC_UNDEFINED_BINARY_MULTICLASS - set(THRESHOLDED_METRICS) ),)def test_single_sample(name): check_single_sample(name)
@pytest.mark.parametrize("name", sorted(MULTIOUTPUT_METRICS | MULTILABELS_METRICS))def test_single_sample_multioutput(name): check_single_sample_multioutput(name)
@pytest.mark.parametrize("name", sorted(MULTIOUTPUT_METRICS))def test_multioutput_number_of_output_differ(name): y_true = np.array([[1, 0, 0, 1], [0, 1, 1, 1], [1, 1, 0, 1]]) y_pred = np.array([[0, 0], [1, 0], [0, 0]])
metric = ALL_METRICS[name] with pytest.raises(ValueError): metric(y_true, y_pred)
@pytest.mark.parametrize("name", sorted(MULTIOUTPUT_METRICS))def test_multioutput_regression_invariance_to_dimension_shuffling(name): # test invariance to dimension shuffling random_state = check_random_state(0) y_true = random_state.uniform(0, 2, size=(20, 5)) y_pred = random_state.uniform(0, 2, size=(20, 5))
metric = ALL_METRICS[name] error = metric(y_true, y_pred)
for _ in range(3): perm = random_state.permutation(y_true.shape[1]) assert_allclose( metric(y_true[:, perm], y_pred[:, perm]), error, err_msg="%s is not dimension shuffling invariant" % (name), )
@ignore_warningsdef test_multilabel_representation_invariance(): # Generate some data n_classes = 4 n_samples = 50
_, y1 = make_multilabel_classification( n_features=1, n_classes=n_classes, random_state=0, n_samples=n_samples, allow_unlabeled=True, ) _, y2 = make_multilabel_classification( n_features=1, n_classes=n_classes, random_state=1, n_samples=n_samples, allow_unlabeled=True, )
# To make sure at least one empty label is present y1 = np.vstack([y1, [[0] * n_classes]]) y2 = np.vstack([y2, [[0] * n_classes]])
y1_sparse_indicator = sp.coo_matrix(y1) y2_sparse_indicator = sp.coo_matrix(y2)
y1_list_array_indicator = list(y1) y2_list_array_indicator = list(y2)
y1_list_list_indicator = [list(a) for a in y1_list_array_indicator] y2_list_list_indicator = [list(a) for a in y2_list_array_indicator]
for name in MULTILABELS_METRICS: metric = ALL_METRICS[name]
# XXX cruel hack to work with partial functions if isinstance(metric, partial): metric.__module__ = "tmp" metric.__name__ = name
measure = metric(y1, y2)
# Check representation invariance assert_allclose( metric(y1_sparse_indicator, y2_sparse_indicator), measure, err_msg=( "%s failed representation invariance between " "dense and sparse indicator formats." ) % name, ) assert_almost_equal( metric(y1_list_list_indicator, y2_list_list_indicator), measure, err_msg=( "%s failed representation invariance " "between dense array and list of list " "indicator formats." ) % name, ) assert_almost_equal( metric(y1_list_array_indicator, y2_list_array_indicator), measure, err_msg=( "%s failed representation invariance " "between dense and list of array " "indicator formats." ) % name, )
@pytest.mark.parametrize("name", sorted(MULTILABELS_METRICS))def test_raise_value_error_multilabel_sequences(name): # make sure the multilabel-sequence format raises ValueError multilabel_sequences = [ [[1], [2], [0, 1]], [(), (2), (0, 1)], [[]], [()], np.array([[], [1, 2]], dtype="object"), ]
metric = ALL_METRICS[name] for seq in multilabel_sequences: with pytest.raises(ValueError): metric(seq, seq)
@pytest.mark.parametrize("name", sorted(METRICS_WITH_NORMALIZE_OPTION))def test_normalize_option_binary_classification(name): # Test in the binary case n_classes = 2 n_samples = 20 random_state = check_random_state(0)
y_true = random_state.randint(0, n_classes, size=(n_samples,)) y_pred = random_state.randint(0, n_classes, size=(n_samples,)) y_score = random_state.normal(size=y_true.shape)
metrics = ALL_METRICS[name] pred = y_score if name in THRESHOLDED_METRICS else y_pred measure_normalized = metrics(y_true, pred, normalize=True) measure_not_normalized = metrics(y_true, pred, normalize=False)
assert_array_less( -1.0 * measure_normalized, 0, err_msg="We failed to test correctly the normalize option", )
assert_allclose( measure_normalized, measure_not_normalized / n_samples, err_msg=f"Failed with {name}", )
@pytest.mark.parametrize("name", sorted(METRICS_WITH_NORMALIZE_OPTION))def test_normalize_option_multiclass_classification(name): # Test in the multiclass case n_classes = 4 n_samples = 20 random_state = check_random_state(0)
y_true = random_state.randint(0, n_classes, size=(n_samples,)) y_pred = random_state.randint(0, n_classes, size=(n_samples,)) y_score = random_state.uniform(size=(n_samples, n_classes))
metrics = ALL_METRICS[name] pred = y_score if name in THRESHOLDED_METRICS else y_pred measure_normalized = metrics(y_true, pred, normalize=True) measure_not_normalized = metrics(y_true, pred, normalize=False)
assert_array_less( -1.0 * measure_normalized, 0, err_msg="We failed to test correctly the normalize option", )
assert_allclose( measure_normalized, measure_not_normalized / n_samples, err_msg=f"Failed with {name}", )
@pytest.mark.parametrize( "name", sorted(METRICS_WITH_NORMALIZE_OPTION.intersection(MULTILABELS_METRICS)))def test_normalize_option_multilabel_classification(name): # Test in the multilabel case n_classes = 4 n_samples = 100 random_state = check_random_state(0)
# for both random_state 0 and 1, y_true and y_pred has at least one # unlabelled entry _, y_true = make_multilabel_classification( n_features=1, n_classes=n_classes, random_state=0, allow_unlabeled=True, n_samples=n_samples, ) _, y_pred = make_multilabel_classification( n_features=1, n_classes=n_classes, random_state=1, allow_unlabeled=True, n_samples=n_samples, )
y_score = random_state.uniform(size=y_true.shape)
# To make sure at least one empty label is present y_true += [0] * n_classes y_pred += [0] * n_classes
metrics = ALL_METRICS[name] pred = y_score if name in THRESHOLDED_METRICS else y_pred measure_normalized = metrics(y_true, pred, normalize=True) measure_not_normalized = metrics(y_true, pred, normalize=False)
assert_array_less( -1.0 * measure_normalized, 0, err_msg="We failed to test correctly the normalize option", )
assert_allclose( measure_normalized, measure_not_normalized / n_samples, err_msg=f"Failed with {name}", )
@ignore_warningsdef _check_averaging( metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel): n_samples, n_classes = y_true_binarize.shape
# No averaging label_measure = metric(y_true, y_pred, average=None) assert_allclose( label_measure, [ metric(y_true_binarize[:, i], y_pred_binarize[:, i]) for i in range(n_classes) ], )
# Micro measure micro_measure = metric(y_true, y_pred, average="micro") assert_allclose( micro_measure, metric(y_true_binarize.ravel(), y_pred_binarize.ravel()) )
# Macro measure macro_measure = metric(y_true, y_pred, average="macro") assert_allclose(macro_measure, np.mean(label_measure))
# Weighted measure weights = np.sum(y_true_binarize, axis=0, dtype=int)
if np.sum(weights) != 0: weighted_measure = metric(y_true, y_pred, average="weighted") assert_allclose(weighted_measure, np.average(label_measure, weights=weights)) else: weighted_measure = metric(y_true, y_pred, average="weighted") assert_allclose(weighted_measure, 0)
# Sample measure if is_multilabel: sample_measure = metric(y_true, y_pred, average="samples") assert_allclose( sample_measure, np.mean( [ metric(y_true_binarize[i], y_pred_binarize[i]) for i in range(n_samples) ] ), )
with pytest.raises(ValueError): metric(y_true, y_pred, average="unknown") with pytest.raises(ValueError): metric(y_true, y_pred, average="garbage")
def check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score): is_multilabel = type_of_target(y_true).startswith("multilabel")
metric = ALL_METRICS[name]
if name in METRICS_WITH_AVERAGING: _check_averaging( metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel ) elif name in THRESHOLDED_METRICS_WITH_AVERAGING: _check_averaging( metric, y_true, y_score, y_true_binarize, y_score, is_multilabel ) else: raise ValueError("Metric is not recorded as having an average option")
@pytest.mark.parametrize("name", sorted(METRICS_WITH_AVERAGING))def test_averaging_multiclass(name): n_samples, n_classes = 50, 3 random_state = check_random_state(0) y_true = random_state.randint(0, n_classes, size=(n_samples,)) y_pred = random_state.randint(0, n_classes, size=(n_samples,)) y_score = random_state.uniform(size=(n_samples, n_classes))
lb = LabelBinarizer().fit(y_true) y_true_binarize = lb.transform(y_true) y_pred_binarize = lb.transform(y_pred)
check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score)
@pytest.mark.parametrize( "name", sorted(METRICS_WITH_AVERAGING | THRESHOLDED_METRICS_WITH_AVERAGING))def test_averaging_multilabel(name): n_samples, n_classes = 40, 5 _, y = make_multilabel_classification( n_features=1, n_classes=n_classes, random_state=5, n_samples=n_samples, allow_unlabeled=False, ) y_true = y[:20] y_pred = y[20:] y_score = check_random_state(0).normal(size=(20, n_classes)) y_true_binarize = y_true y_pred_binarize = y_pred
check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score)
@pytest.mark.parametrize("name", sorted(METRICS_WITH_AVERAGING))def test_averaging_multilabel_all_zeroes(name): y_true = np.zeros((20, 3)) y_pred = np.zeros((20, 3)) y_score = np.zeros((20, 3)) y_true_binarize = y_true y_pred_binarize = y_pred
check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score)
def test_averaging_binary_multilabel_all_zeroes(): y_true = np.zeros((20, 3)) y_pred = np.zeros((20, 3)) y_true_binarize = y_true y_pred_binarize = y_pred # Test _average_binary_score for weight.sum() == 0 binary_metric = lambda y_true, y_score, average="macro": _average_binary_score( precision_score, y_true, y_score, average ) _check_averaging( binary_metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel=True, )
@pytest.mark.parametrize("name", sorted(METRICS_WITH_AVERAGING))def test_averaging_multilabel_all_ones(name): y_true = np.ones((20, 3)) y_pred = np.ones((20, 3)) y_score = np.ones((20, 3)) y_true_binarize = y_true y_pred_binarize = y_pred
check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score)
@ignore_warningsdef check_sample_weight_invariance(name, metric, y1, y2): rng = np.random.RandomState(0) sample_weight = rng.randint(1, 10, size=len(y1))
# top_k_accuracy_score always lead to a perfect score for k > 1 in the # binary case metric = partial(metric, k=1) if name == "top_k_accuracy_score" else metric
# check that unit weights gives the same score as no weight unweighted_score = metric(y1, y2, sample_weight=None)
assert_allclose( unweighted_score, metric(y1, y2, sample_weight=np.ones(shape=len(y1))), err_msg="For %s sample_weight=None is not equivalent to sample_weight=ones" % name, )
# check that the weighted and unweighted scores are unequal weighted_score = metric(y1, y2, sample_weight=sample_weight)
# use context manager to supply custom error message with pytest.raises(AssertionError): assert_allclose(unweighted_score, weighted_score) raise ValueError( "Unweighted and weighted scores are unexpectedly " "almost equal (%s) and (%s) " "for %s" % (unweighted_score, weighted_score, name) )
# check that sample_weight can be a list weighted_score_list = metric(y1, y2, sample_weight=sample_weight.tolist()) assert_allclose( weighted_score, weighted_score_list, err_msg=( "Weighted scores for array and list " "sample_weight input are not equal (%s != %s) for %s" ) % (weighted_score, weighted_score_list, name), )
# check that integer weights is the same as repeated samples repeat_weighted_score = metric( np.repeat(y1, sample_weight, axis=0), np.repeat(y2, sample_weight, axis=0), sample_weight=None, ) assert_allclose( weighted_score, repeat_weighted_score, err_msg="Weighting %s is not equal to repeating samples" % name, )
# check that ignoring a fraction of the samples is equivalent to setting # the corresponding weights to zero sample_weight_subset = sample_weight[1::2] sample_weight_zeroed = np.copy(sample_weight) sample_weight_zeroed[::2] = 0 y1_subset = y1[1::2] y2_subset = y2[1::2] weighted_score_subset = metric( y1_subset, y2_subset, sample_weight=sample_weight_subset ) weighted_score_zeroed = metric(y1, y2, sample_weight=sample_weight_zeroed) assert_allclose( weighted_score_subset, weighted_score_zeroed, err_msg=( "Zeroing weights does not give the same result as " "removing the corresponding samples (%s != %s) for %s" ) % (weighted_score_zeroed, weighted_score_subset, name), )
if not name.startswith("unnormalized"): # check that the score is invariant under scaling of the weights by a # common factor for scaling in [2, 0.3]: assert_allclose( weighted_score, metric(y1, y2, sample_weight=sample_weight * scaling), err_msg="%s sample_weight is not invariant under scaling" % name, )
# Check that if number of samples in y_true and sample_weight are not # equal, meaningful error is raised. error_message = ( r"Found input variables with inconsistent numbers of " r"samples: \[{}, {}, {}\]".format( _num_samples(y1), _num_samples(y2), _num_samples(sample_weight) * 2 ) ) with pytest.raises(ValueError, match=error_message): metric(y1, y2, sample_weight=np.hstack([sample_weight, sample_weight]))
@pytest.mark.parametrize( "name", sorted( set(ALL_METRICS).intersection(set(REGRESSION_METRICS)) - METRICS_WITHOUT_SAMPLE_WEIGHT ),)def test_regression_sample_weight_invariance(name): n_samples = 50 random_state = check_random_state(0) # regression y_true = random_state.random_sample(size=(n_samples,)) y_pred = random_state.random_sample(size=(n_samples,)) metric = ALL_METRICS[name] check_sample_weight_invariance(name, metric, y_true, y_pred)
@pytest.mark.parametrize( "name", sorted( set(ALL_METRICS) - set(REGRESSION_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT - METRIC_UNDEFINED_BINARY ),)def test_binary_sample_weight_invariance(name): # binary n_samples = 50 random_state = check_random_state(0) y_true = random_state.randint(0, 2, size=(n_samples,)) y_pred = random_state.randint(0, 2, size=(n_samples,)) y_score = random_state.random_sample(size=(n_samples,)) metric = ALL_METRICS[name] if name in THRESHOLDED_METRICS: check_sample_weight_invariance(name, metric, y_true, y_score) else: check_sample_weight_invariance(name, metric, y_true, y_pred)
@pytest.mark.parametrize( "name", sorted( set(ALL_METRICS) - set(REGRESSION_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT - METRIC_UNDEFINED_BINARY_MULTICLASS ),)def test_multiclass_sample_weight_invariance(name): # multiclass n_samples = 50 random_state = check_random_state(0) y_true = random_state.randint(0, 5, size=(n_samples,)) y_pred = random_state.randint(0, 5, size=(n_samples,)) y_score = random_state.random_sample(size=(n_samples, 5)) metric = ALL_METRICS[name] if name in THRESHOLDED_METRICS: # softmax temp = np.exp(-y_score) y_score_norm = temp / temp.sum(axis=-1).reshape(-1, 1) check_sample_weight_invariance(name, metric, y_true, y_score_norm) else: check_sample_weight_invariance(name, metric, y_true, y_pred)
@pytest.mark.parametrize( "name", sorted( (MULTILABELS_METRICS | THRESHOLDED_MULTILABEL_METRICS | MULTIOUTPUT_METRICS) - METRICS_WITHOUT_SAMPLE_WEIGHT ),)def test_multilabel_sample_weight_invariance(name): # multilabel indicator random_state = check_random_state(0) _, ya = make_multilabel_classification( n_features=1, n_classes=10, random_state=0, n_samples=50, allow_unlabeled=False ) _, yb = make_multilabel_classification( n_features=1, n_classes=10, random_state=1, n_samples=50, allow_unlabeled=False ) y_true = np.vstack([ya, yb]) y_pred = np.vstack([ya, ya]) y_score = random_state.randint(1, 4, size=y_true.shape)
metric = ALL_METRICS[name] if name in THRESHOLDED_METRICS: check_sample_weight_invariance(name, metric, y_true, y_score) else: check_sample_weight_invariance(name, metric, y_true, y_pred)
@ignore_warningsdef test_no_averaging_labels(): # test labels argument when not using averaging # in multi-class and multi-label cases y_true_multilabel = np.array([[1, 1, 0, 0], [1, 1, 0, 0]]) y_pred_multilabel = np.array([[0, 0, 1, 1], [0, 1, 1, 0]]) y_true_multiclass = np.array([0, 1, 2]) y_pred_multiclass = np.array([0, 2, 3]) labels = np.array([3, 0, 1, 2]) _, inverse_labels = np.unique(labels, return_inverse=True)
for name in METRICS_WITH_AVERAGING: for y_true, y_pred in [ [y_true_multiclass, y_pred_multiclass], [y_true_multilabel, y_pred_multilabel], ]: if name not in MULTILABELS_METRICS and y_pred.ndim > 1: continue
metric = ALL_METRICS[name]
score_labels = metric(y_true, y_pred, labels=labels, average=None) score = metric(y_true, y_pred, average=None) assert_array_equal(score_labels, score[inverse_labels])
@pytest.mark.parametrize( "name", sorted(MULTILABELS_METRICS - {"unnormalized_multilabel_confusion_matrix"}))def test_multilabel_label_permutations_invariance(name): random_state = check_random_state(0) n_samples, n_classes = 20, 4
y_true = random_state.randint(0, 2, size=(n_samples, n_classes)) y_score = random_state.randint(0, 2, size=(n_samples, n_classes))
metric = ALL_METRICS[name] score = metric(y_true, y_score)
for perm in permutations(range(n_classes), n_classes): y_score_perm = y_score[:, perm] y_true_perm = y_true[:, perm]
current_score = metric(y_true_perm, y_score_perm) assert_almost_equal(score, current_score)
@pytest.mark.parametrize( "name", sorted(THRESHOLDED_MULTILABEL_METRICS | MULTIOUTPUT_METRICS))def test_thresholded_multilabel_multioutput_permutations_invariance(name): random_state = check_random_state(0) n_samples, n_classes = 20, 4 y_true = random_state.randint(0, 2, size=(n_samples, n_classes)) y_score = random_state.normal(size=y_true.shape)
# Makes sure all samples have at least one label. This works around errors # when running metrics where average="sample" y_true[y_true.sum(1) == 4, 0] = 0 y_true[y_true.sum(1) == 0, 0] = 1
metric = ALL_METRICS[name] score = metric(y_true, y_score)
for perm in permutations(range(n_classes), n_classes): y_score_perm = y_score[:, perm] y_true_perm = y_true[:, perm]
current_score = metric(y_true_perm, y_score_perm) if metric == mean_absolute_percentage_error: assert np.isfinite(current_score) assert current_score > 1e6 # Here we are not comparing the values in case of MAPE because # whenever y_true value is exactly zero, the MAPE value doesn't # signify anything. Thus, in this case we are just expecting # very large finite value. else: assert_almost_equal(score, current_score)
@pytest.mark.parametrize( "name", sorted(set(THRESHOLDED_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS))def test_thresholded_metric_permutation_invariance(name): n_samples, n_classes = 100, 3 random_state = check_random_state(0)
y_score = random_state.rand(n_samples, n_classes) temp = np.exp(-y_score) y_score = temp / temp.sum(axis=-1).reshape(-1, 1) y_true = random_state.randint(0, n_classes, size=n_samples)
metric = ALL_METRICS[name] score = metric(y_true, y_score) for perm in permutations(range(n_classes), n_classes): inverse_perm = np.zeros(n_classes, dtype=int) inverse_perm[list(perm)] = np.arange(n_classes) y_score_perm = y_score[:, inverse_perm] y_true_perm = np.take(perm, y_true)
current_score = metric(y_true_perm, y_score_perm) assert_almost_equal(score, current_score)
@pytest.mark.parametrize("metric_name", CLASSIFICATION_METRICS)def test_metrics_consistent_type_error(metric_name): # check that an understable message is raised when the type between y_true # and y_pred mismatch rng = np.random.RandomState(42) y1 = np.array(["spam"] * 3 + ["eggs"] * 2, dtype=object) y2 = rng.randint(0, 2, size=y1.size)
err_msg = "Labels in y_true and y_pred should be of the same type." with pytest.raises(TypeError, match=err_msg): CLASSIFICATION_METRICS[metric_name](y1, y2)
@pytest.mark.parametrize( "metric, y_pred_threshold", [ (average_precision_score, True), (brier_score_loss, True), (f1_score, False), (partial(fbeta_score, beta=1), False), (jaccard_score, False), (precision_recall_curve, True), (precision_score, False), (recall_score, False), (roc_curve, True), ],)@pytest.mark.parametrize("dtype_y_str", [str, object])def test_metrics_pos_label_error_str(metric, y_pred_threshold, dtype_y_str): # check that the error message if `pos_label` is not specified and the # targets is made of strings. rng = np.random.RandomState(42) y1 = np.array(["spam"] * 3 + ["eggs"] * 2, dtype=dtype_y_str) y2 = rng.randint(0, 2, size=y1.size)
if not y_pred_threshold: y2 = np.array(["spam", "eggs"], dtype=dtype_y_str)[y2]
err_msg_pos_label_None = ( "y_true takes value in {'eggs', 'spam'} and pos_label is not " "specified: either make y_true take value in {0, 1} or {-1, 1} or " "pass pos_label explicit" ) err_msg_pos_label_1 = ( r"pos_label=1 is not a valid label. It should be one of " r"\['eggs', 'spam'\]" )
pos_label_default = signature(metric).parameters["pos_label"].default
err_msg = err_msg_pos_label_1 if pos_label_default == 1 else err_msg_pos_label_None with pytest.raises(ValueError, match=err_msg): metric(y1, y2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456import itertoolsimport pickleimport copy
import numpy as npimport pytest
import scipy.sparse as spfrom scipy.spatial.distance import cdistfrom sklearn.metrics import DistanceMetric
from sklearn.metrics._dist_metrics import ( BOOL_METRICS, # Unexposed private DistanceMetric for 32 bit DistanceMetric32,)
from sklearn.utils import check_random_statefrom sklearn.utils._testing import assert_allclose, create_memmap_backed_datafrom sklearn.utils.fixes import sp_version, parse_version
def dist_func(x1, x2, p): return np.sum((x1 - x2) ** p) ** (1.0 / p)
rng = check_random_state(0)d = 4n1 = 20n2 = 25X64 = rng.random_sample((n1, d))Y64 = rng.random_sample((n2, d))X32 = X64.astype("float32")Y32 = Y64.astype("float32")
[X_mmap, Y_mmap] = create_memmap_backed_data([X64, Y64])
# make boolean arrays: ones and zerosX_bool = (X64 < 0.3).astype(np.float64) # quite sparseY_bool = (Y64 < 0.7).astype(np.float64) # not too sparse
[X_bool_mmap, Y_bool_mmap] = create_memmap_backed_data([X_bool, Y_bool])
V = rng.random_sample((d, d))VI = np.dot(V, V.T)
METRICS_DEFAULT_PARAMS = [ ("euclidean", {}), ("cityblock", {}), ("minkowski", dict(p=(1, 1.5, 2, 3))), ("chebyshev", {}), ("seuclidean", dict(V=(rng.random_sample(d),))), ("mahalanobis", dict(VI=(VI,))), ("hamming", {}), ("canberra", {}), ("braycurtis", {}),]if sp_version >= parse_version("1.8.0.dev0"): # Starting from scipy 1.8.0.dev0, minkowski now accepts w, the weighting # parameter directly and using it is preferred over using wminkowski. METRICS_DEFAULT_PARAMS.append( ("minkowski", dict(p=(1, 1.5, 3), w=(rng.random_sample(d),))), )else: # For previous versions of scipy, this was possible through a dedicated # metric (deprecated in 1.6 and removed in 1.8). METRICS_DEFAULT_PARAMS.append( ("wminkowski", dict(p=(1, 1.5, 3), w=(rng.random_sample(d),))), )
# TODO: Remove filterwarnings in 1.3 when wminkowski is removed@pytest.mark.filterwarnings("ignore:WMinkowskiDistance:FutureWarning:sklearn")@pytest.mark.parametrize( "metric_param_grid", METRICS_DEFAULT_PARAMS, ids=lambda params: params[0])@pytest.mark.parametrize("X, Y", [(X64, Y64), (X32, Y32), (X_mmap, Y_mmap)])def test_cdist(metric_param_grid, X, Y): DistanceMetricInterface = ( DistanceMetric if X.dtype == Y.dtype == np.float64 else DistanceMetric32 ) metric, param_grid = metric_param_grid keys = param_grid.keys() X_csr, Y_csr = sp.csr_matrix(X), sp.csr_matrix(Y) for vals in itertools.product(*param_grid.values()): kwargs = dict(zip(keys, vals)) rtol_dict = {} if metric == "mahalanobis" and X.dtype == np.float32: # Computation of mahalanobis differs between # the scipy and scikit-learn implementation. # Hence, we increase the relative tolerance. # TODO: Inspect slight numerical discrepancy # with scipy rtol_dict = {"rtol": 1e-6}
if metric == "wminkowski": # wminkoski is deprecated in SciPy 1.6.0 and removed in 1.8.0 WarningToExpect = None if sp_version >= parse_version("1.6.0"): WarningToExpect = DeprecationWarning with pytest.warns(WarningToExpect): D_scipy_cdist = cdist(X, Y, metric, **kwargs) else: D_scipy_cdist = cdist(X, Y, metric, **kwargs)
dm = DistanceMetricInterface.get_metric(metric, **kwargs)
# DistanceMetric.pairwise must be consistent for all # combinations of formats in {sparse, dense}. D_sklearn = dm.pairwise(X, Y) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn, D_scipy_cdist, **rtol_dict)
D_sklearn = dm.pairwise(X_csr, Y_csr) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn, D_scipy_cdist, **rtol_dict)
D_sklearn = dm.pairwise(X_csr, Y) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn, D_scipy_cdist, **rtol_dict)
D_sklearn = dm.pairwise(X, Y_csr) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn, D_scipy_cdist, **rtol_dict)
@pytest.mark.parametrize("metric", BOOL_METRICS)@pytest.mark.parametrize( "X_bool, Y_bool", [(X_bool, Y_bool), (X_bool_mmap, Y_bool_mmap)])def test_cdist_bool_metric(metric, X_bool, Y_bool): D_scipy_cdist = cdist(X_bool, Y_bool, metric)
dm = DistanceMetric.get_metric(metric) D_sklearn = dm.pairwise(X_bool, Y_bool) assert_allclose(D_sklearn, D_scipy_cdist)
# DistanceMetric.pairwise must be consistent # on all combinations of format in {sparse, dense}². X_bool_csr, Y_bool_csr = sp.csr_matrix(X_bool), sp.csr_matrix(Y_bool)
D_sklearn = dm.pairwise(X_bool, Y_bool) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn, D_scipy_cdist)
D_sklearn = dm.pairwise(X_bool_csr, Y_bool_csr) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn, D_scipy_cdist)
D_sklearn = dm.pairwise(X_bool, Y_bool_csr) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn, D_scipy_cdist)
D_sklearn = dm.pairwise(X_bool_csr, Y_bool) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn, D_scipy_cdist)
# TODO: Remove filterwarnings in 1.3 when wminkowski is removed@pytest.mark.filterwarnings("ignore:WMinkowskiDistance:FutureWarning:sklearn")@pytest.mark.parametrize( "metric_param_grid", METRICS_DEFAULT_PARAMS, ids=lambda params: params[0])@pytest.mark.parametrize("X", [X64, X32, X_mmap])def test_pdist(metric_param_grid, X): DistanceMetricInterface = ( DistanceMetric if X.dtype == np.float64 else DistanceMetric32 ) metric, param_grid = metric_param_grid keys = param_grid.keys() X_csr = sp.csr_matrix(X) for vals in itertools.product(*param_grid.values()): kwargs = dict(zip(keys, vals)) rtol_dict = {} if metric == "mahalanobis" and X.dtype == np.float32: # Computation of mahalanobis differs between # the scipy and scikit-learn implementation. # Hence, we increase the relative tolerance. # TODO: Inspect slight numerical discrepancy # with scipy rtol_dict = {"rtol": 1e-6}
if metric == "wminkowski": if sp_version >= parse_version("1.8.0"): pytest.skip("wminkowski will be removed in SciPy 1.8.0")
# wminkoski is deprecated in SciPy 1.6.0 and removed in 1.8.0 ExceptionToAssert = None if sp_version >= parse_version("1.6.0"): ExceptionToAssert = DeprecationWarning with pytest.warns(ExceptionToAssert): D_scipy_pdist = cdist(X, X, metric, **kwargs) else: D_scipy_pdist = cdist(X, X, metric, **kwargs)
dm = DistanceMetricInterface.get_metric(metric, **kwargs) D_sklearn = dm.pairwise(X) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn, D_scipy_pdist, **rtol_dict)
D_sklearn_csr = dm.pairwise(X_csr) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn_csr, D_scipy_pdist, **rtol_dict)
D_sklearn_csr = dm.pairwise(X_csr, X_csr) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn_csr, D_scipy_pdist, **rtol_dict)
# TODO: Remove filterwarnings in 1.3 when wminkowski is removed@pytest.mark.filterwarnings("ignore:WMinkowskiDistance:FutureWarning:sklearn")@pytest.mark.parametrize( "metric_param_grid", METRICS_DEFAULT_PARAMS, ids=lambda params: params[0])def test_distance_metrics_dtype_consistency(metric_param_grid): # DistanceMetric must return similar distances for both float32 and float64 # input data. metric, param_grid = metric_param_grid keys = param_grid.keys()
# Choose rtol to make sure that this test is robust to changes in the random # seed in the module-level test data generation code. rtol = 1e-5
for vals in itertools.product(*param_grid.values()): kwargs = dict(zip(keys, vals)) dm64 = DistanceMetric.get_metric(metric, **kwargs) dm32 = DistanceMetric32.get_metric(metric, **kwargs)
D64 = dm64.pairwise(X64) D32 = dm32.pairwise(X32)
# Both results are np.float64 dtype because the accumulation accross # features is done in float64. However the input data and the element # wise arithmetic operations are done in float32 so we can expect a # small discrepancy. assert D64.dtype == D32.dtype == np.float64
# assert_allclose introspects the dtype of the input arrays to decide # which rtol value to use by default but in this case we know that D32 # is not computed with the same precision so we set rtol manually. assert_allclose(D64, D32, rtol=rtol)
D64 = dm64.pairwise(X64, Y64) D32 = dm32.pairwise(X32, Y32) assert_allclose(D64, D32, rtol=rtol)
@pytest.mark.parametrize("metric", BOOL_METRICS)@pytest.mark.parametrize("X_bool", [X_bool, X_bool_mmap])def test_pdist_bool_metrics(metric, X_bool): D_scipy_pdist = cdist(X_bool, X_bool, metric) dm = DistanceMetric.get_metric(metric) D_sklearn = dm.pairwise(X_bool) assert_allclose(D_sklearn, D_scipy_pdist)
X_bool_csr = sp.csr_matrix(X_bool) D_sklearn = dm.pairwise(X_bool_csr) assert_allclose(D_sklearn, D_scipy_pdist)
# TODO: Remove filterwarnings in 1.3 when wminkowski is removed@pytest.mark.filterwarnings("ignore:WMinkowskiDistance:FutureWarning:sklearn")@pytest.mark.parametrize("writable_kwargs", [True, False])@pytest.mark.parametrize( "metric_param_grid", METRICS_DEFAULT_PARAMS, ids=lambda params: params[0])@pytest.mark.parametrize("X", [X64, X32])def test_pickle(writable_kwargs, metric_param_grid, X): DistanceMetricInterface = ( DistanceMetric if X.dtype == np.float64 else DistanceMetric32 ) metric, param_grid = metric_param_grid keys = param_grid.keys() for vals in itertools.product(*param_grid.values()): if any(isinstance(val, np.ndarray) for val in vals): vals = copy.deepcopy(vals) for val in vals: if isinstance(val, np.ndarray): val.setflags(write=writable_kwargs) kwargs = dict(zip(keys, vals)) dm = DistanceMetricInterface.get_metric(metric, **kwargs) D1 = dm.pairwise(X) dm2 = pickle.loads(pickle.dumps(dm)) D2 = dm2.pairwise(X) assert_allclose(D1, D2)
# TODO: Remove filterwarnings in 1.3 when wminkowski is removed@pytest.mark.filterwarnings("ignore:WMinkowskiDistance:FutureWarning:sklearn")@pytest.mark.parametrize("metric", BOOL_METRICS)@pytest.mark.parametrize("X_bool", [X_bool, X_bool_mmap])def test_pickle_bool_metrics(metric, X_bool): dm = DistanceMetric.get_metric(metric) D1 = dm.pairwise(X_bool) dm2 = pickle.loads(pickle.dumps(dm)) D2 = dm2.pairwise(X_bool) assert_allclose(D1, D2)
@pytest.mark.parametrize("X, Y", [(X64, Y64), (X32, Y32), (X_mmap, Y_mmap)])def test_haversine_metric(X, Y): DistanceMetricInterface = ( DistanceMetric if X.dtype == np.float64 else DistanceMetric32 )
# The Haversine DistanceMetric only works on 2 features. X = np.asarray(X[:, :2]) Y = np.asarray(Y[:, :2])
X_csr, Y_csr = sp.csr_matrix(X), sp.csr_matrix(Y)
# Haversine is not supported by scipy.special.distance.{cdist,pdist} # So we reimplement it to have a reference. def haversine_slow(x1, x2): return 2 * np.arcsin( np.sqrt( np.sin(0.5 * (x1[0] - x2[0])) ** 2 + np.cos(x1[0]) * np.cos(x2[0]) * np.sin(0.5 * (x1[1] - x2[1])) ** 2 ) )
D_reference = np.zeros((X_csr.shape[0], Y_csr.shape[0])) for i, xi in enumerate(X): for j, yj in enumerate(Y): D_reference[i, j] = haversine_slow(xi, yj)
haversine = DistanceMetricInterface.get_metric("haversine")
D_sklearn = haversine.pairwise(X, Y) assert_allclose( haversine.dist_to_rdist(D_sklearn), np.sin(0.5 * D_reference) ** 2, rtol=1e-6 )
assert_allclose(D_sklearn, D_reference)
D_sklearn = haversine.pairwise(X_csr, Y_csr) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn, D_reference)
D_sklearn = haversine.pairwise(X_csr, Y) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn, D_reference)
D_sklearn = haversine.pairwise(X, Y_csr) assert D_sklearn.flags.c_contiguous assert_allclose(D_sklearn, D_reference)
def test_pyfunc_metric(): X = np.random.random((10, 3))
euclidean = DistanceMetric.get_metric("euclidean") pyfunc = DistanceMetric.get_metric("pyfunc", func=dist_func, p=2)
# Check if both callable metric and predefined metric initialized # DistanceMetric object is picklable euclidean_pkl = pickle.loads(pickle.dumps(euclidean)) pyfunc_pkl = pickle.loads(pickle.dumps(pyfunc))
D1 = euclidean.pairwise(X) D2 = pyfunc.pairwise(X)
D1_pkl = euclidean_pkl.pairwise(X) D2_pkl = pyfunc_pkl.pairwise(X)
assert_allclose(D1, D2) assert_allclose(D1_pkl, D2_pkl)
def test_input_data_size(): # Regression test for #6288 # Previously, a metric requiring a particular input dimension would fail def custom_metric(x, y): assert x.shape[0] == 3 return np.sum((x - y) ** 2)
rng = check_random_state(0) X = rng.rand(10, 3)
pyfunc = DistanceMetric.get_metric("pyfunc", func=custom_metric) eucl = DistanceMetric.get_metric("euclidean") assert_allclose(pyfunc.pairwise(X), eucl.pairwise(X) ** 2)
# TODO: Remove filterwarnings in 1.3 when wminkowski is removed@pytest.mark.filterwarnings("ignore:WMinkowskiDistance:FutureWarning:sklearn")def test_readonly_kwargs(): # Non-regression test for: # https://github.com/scikit-learn/scikit-learn/issues/21685
rng = check_random_state(0)
weights = rng.rand(100) VI = rng.rand(10, 10) weights.setflags(write=False) VI.setflags(write=False)
# Those distances metrics have to support readonly buffers. DistanceMetric.get_metric("seuclidean", V=weights) DistanceMetric.get_metric("wminkowski", p=1, w=weights) DistanceMetric.get_metric("mahalanobis", VI=VI)
@pytest.mark.parametrize( "w, err_type, err_msg", [ (np.array([1, 1.5, -13]), ValueError, "w cannot contain negative weights"), (np.array([1, 1.5, np.nan]), ValueError, "w contains NaN"), ( sp.csr_matrix([1, 1.5, 1]), TypeError, "A sparse matrix was passed, but dense data is required", ), (np.array(["a", "b", "c"]), ValueError, "could not convert string to float"), (np.array([]), ValueError, "a minimum of 1 is required"), ],)def test_minkowski_metric_validate_weights_values(w, err_type, err_msg): with pytest.raises(err_type, match=err_msg): DistanceMetric.get_metric("minkowski", p=3, w=w)
def test_minkowski_metric_validate_weights_size(): w2 = rng.random_sample(d + 1) dm = DistanceMetric.get_metric("minkowski", p=3, w=w2) msg = ( "MinkowskiDistance: the size of w must match " f"the number of features \\({X64.shape[1]}\\). " f"Currently len\\(w\\)={w2.shape[0]}." ) with pytest.raises(ValueError, match=msg): dm.pairwise(X64, Y64)
# TODO: Remove in 1.3 when wminkowski is removeddef test_wminkowski_deprecated(): w = rng.random_sample(d) msg = "WMinkowskiDistance is deprecated in version 1.1" with pytest.warns(FutureWarning, match=msg): DistanceMetric.get_metric("wminkowski", p=3, w=w)
# TODO: Remove in 1.3 when wminkowski is removed@pytest.mark.filterwarnings("ignore:WMinkowskiDistance:FutureWarning:sklearn")@pytest.mark.parametrize("p", [1, 1.5, 3])def test_wminkowski_minkowski_equivalence(p): w = rng.random_sample(d) # Weights are rescaled for consistency w.r.t scipy 1.8 refactoring of 'minkowski' dm_wmks = DistanceMetric.get_metric("wminkowski", p=p, w=(w) ** (1 / p)) dm_mks = DistanceMetric.get_metric("minkowski", p=p, w=w) D_wmks = dm_wmks.pairwise(X64, Y64) D_mks = dm_mks.pairwise(X64, Y64) assert_allclose(D_wmks, D_mks)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551import warningsfrom types import GeneratorType
import numpy as npfrom numpy import linalg
from scipy.sparse import dok_matrix, csr_matrix, issparsefrom scipy.spatial.distance import cosine, cityblock, minkowskifrom scipy.spatial.distance import cdist, pdist, squareform
try: from scipy.spatial.distance import wminkowskiexcept ImportError: # In scipy 1.6.0, wminkowski is deprecated and minkowski # should be used instead. from scipy.spatial.distance import minkowski as wminkowski
from sklearn.utils.fixes import sp_version, parse_version
import pytest
from sklearn import config_context
from sklearn.utils._testing import assert_allclosefrom sklearn.utils._testing import assert_almost_equalfrom sklearn.utils._testing import assert_array_equalfrom sklearn.utils._testing import ignore_warnings
from sklearn.metrics.pairwise import euclidean_distancesfrom sklearn.metrics.pairwise import nan_euclidean_distancesfrom sklearn.metrics.pairwise import manhattan_distancesfrom sklearn.metrics.pairwise import haversine_distancesfrom sklearn.metrics.pairwise import linear_kernelfrom sklearn.metrics.pairwise import chi2_kernel, additive_chi2_kernelfrom sklearn.metrics.pairwise import polynomial_kernelfrom sklearn.metrics.pairwise import rbf_kernelfrom sklearn.metrics.pairwise import laplacian_kernelfrom sklearn.metrics.pairwise import sigmoid_kernelfrom sklearn.metrics.pairwise import cosine_similarityfrom sklearn.metrics.pairwise import cosine_distancesfrom sklearn.metrics.pairwise import pairwise_distancesfrom sklearn.metrics.pairwise import pairwise_distances_chunkedfrom sklearn.metrics.pairwise import pairwise_distances_argmin_minfrom sklearn.metrics.pairwise import pairwise_distances_argminfrom sklearn.metrics.pairwise import pairwise_kernelsfrom sklearn.metrics.pairwise import PAIRWISE_KERNEL_FUNCTIONSfrom sklearn.metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONSfrom sklearn.metrics.pairwise import PAIRWISE_BOOLEAN_FUNCTIONSfrom sklearn.metrics.pairwise import PAIRED_DISTANCESfrom sklearn.metrics.pairwise import check_pairwise_arraysfrom sklearn.metrics.pairwise import check_paired_arraysfrom sklearn.metrics.pairwise import paired_distancesfrom sklearn.metrics.pairwise import paired_euclidean_distancesfrom sklearn.metrics.pairwise import paired_manhattan_distancesfrom sklearn.metrics.pairwise import _euclidean_distances_upcastfrom sklearn.preprocessing import normalizefrom sklearn.exceptions import DataConversionWarning
def test_pairwise_distances(global_dtype): # Test the pairwise_distance helper function. rng = np.random.RandomState(0)
# Euclidean distance should be equivalent to calling the function. X = rng.random_sample((5, 4)).astype(global_dtype, copy=False) S = pairwise_distances(X, metric="euclidean") S2 = euclidean_distances(X) assert_allclose(S, S2) assert S.dtype == S2.dtype == global_dtype
# Euclidean distance, with Y != X. Y = rng.random_sample((2, 4)).astype(global_dtype, copy=False) S = pairwise_distances(X, Y, metric="euclidean") S2 = euclidean_distances(X, Y) assert_allclose(S, S2) assert S.dtype == S2.dtype == global_dtype
# Check to ensure NaNs work with pairwise_distances. X_masked = rng.random_sample((5, 4)).astype(global_dtype, copy=False) Y_masked = rng.random_sample((2, 4)).astype(global_dtype, copy=False) X_masked[0, 0] = np.nan Y_masked[0, 0] = np.nan S_masked = pairwise_distances(X_masked, Y_masked, metric="nan_euclidean") S2_masked = nan_euclidean_distances(X_masked, Y_masked) assert_allclose(S_masked, S2_masked) assert S_masked.dtype == S2_masked.dtype == global_dtype
# Test with tuples as X and Y X_tuples = tuple([tuple([v for v in row]) for row in X]) Y_tuples = tuple([tuple([v for v in row]) for row in Y]) S2 = pairwise_distances(X_tuples, Y_tuples, metric="euclidean") assert_allclose(S, S2) assert S.dtype == S2.dtype == global_dtype
# Test haversine distance # The data should be valid latitude and longitude # haversine converts to float64 currently so we don't check dtypes. X = rng.random_sample((5, 2)).astype(global_dtype, copy=False) X[:, 0] = (X[:, 0] - 0.5) * 2 * np.pi / 2 X[:, 1] = (X[:, 1] - 0.5) * 2 * np.pi S = pairwise_distances(X, metric="haversine") S2 = haversine_distances(X) assert_allclose(S, S2)
# Test haversine distance, with Y != X Y = rng.random_sample((2, 2)).astype(global_dtype, copy=False) Y[:, 0] = (Y[:, 0] - 0.5) * 2 * np.pi / 2 Y[:, 1] = (Y[:, 1] - 0.5) * 2 * np.pi S = pairwise_distances(X, Y, metric="haversine") S2 = haversine_distances(X, Y) assert_allclose(S, S2)
# "cityblock" uses scikit-learn metric, cityblock (function) is # scipy.spatial. # The metric functions from scipy converts to float64 so we don't check the dtypes. S = pairwise_distances(X, metric="cityblock") S2 = pairwise_distances(X, metric=cityblock) assert S.shape[0] == S.shape[1] assert S.shape[0] == X.shape[0] assert_allclose(S, S2)
# The manhattan metric should be equivalent to cityblock. S = pairwise_distances(X, Y, metric="manhattan") S2 = pairwise_distances(X, Y, metric=cityblock) assert S.shape[0] == X.shape[0] assert S.shape[1] == Y.shape[0] assert_allclose(S, S2)
# Test cosine as a string metric versus cosine callable # The string "cosine" uses sklearn.metric, # while the function cosine is scipy.spatial S = pairwise_distances(X, Y, metric="cosine") S2 = pairwise_distances(X, Y, metric=cosine) assert S.shape[0] == X.shape[0] assert S.shape[1] == Y.shape[0] assert_allclose(S, S2)
# Test with sparse X and Y, # currently only supported for Euclidean, L1 and cosine. X_sparse = csr_matrix(X) Y_sparse = csr_matrix(Y)
S = pairwise_distances(X_sparse, Y_sparse, metric="euclidean") S2 = euclidean_distances(X_sparse, Y_sparse) assert_allclose(S, S2) assert S.dtype == S2.dtype == global_dtype
S = pairwise_distances(X_sparse, Y_sparse, metric="cosine") S2 = cosine_distances(X_sparse, Y_sparse) assert_allclose(S, S2) assert S.dtype == S2.dtype == global_dtype
S = pairwise_distances(X_sparse, Y_sparse.tocsc(), metric="manhattan") S2 = manhattan_distances(X_sparse.tobsr(), Y_sparse.tocoo()) assert_allclose(S, S2) if global_dtype == np.float64: assert S.dtype == S2.dtype == global_dtype else: # TODO Fix manhattan_distances to preserve dtype. # currently pairwise_distances uses manhattan_distances but converts the result # back to the input dtype with pytest.raises(AssertionError): assert S.dtype == S2.dtype == global_dtype
S2 = manhattan_distances(X, Y) assert_allclose(S, S2) if global_dtype == np.float64: assert S.dtype == S2.dtype == global_dtype else: # TODO Fix manhattan_distances to preserve dtype. # currently pairwise_distances uses manhattan_distances but converts the result # back to the input dtype with pytest.raises(AssertionError): assert S.dtype == S2.dtype == global_dtype
# Test with scipy.spatial.distance metric, with a kwd kwds = {"p": 2.0} S = pairwise_distances(X, Y, metric="minkowski", **kwds) S2 = pairwise_distances(X, Y, metric=minkowski, **kwds) assert_allclose(S, S2)
# same with Y = None kwds = {"p": 2.0} S = pairwise_distances(X, metric="minkowski", **kwds) S2 = pairwise_distances(X, metric=minkowski, **kwds) assert_allclose(S, S2)
# Test that scipy distance metrics throw an error if sparse matrix given with pytest.raises(TypeError): pairwise_distances(X_sparse, metric="minkowski") with pytest.raises(TypeError): pairwise_distances(X, Y_sparse, metric="minkowski")
# Test that a value error is raised if the metric is unknown with pytest.raises(ValueError): pairwise_distances(X, Y, metric="blah")
# TODO(1.4): Remove test when `sum_over_features` parameter is removed@pytest.mark.parametrize("sum_over_features", [True, False])def test_manhattan_distances_deprecated_sum_over_features(sum_over_features): # Check that future warning is raised when user # enters `sum_over_features` argument. X = [[1, 2], [3, 4]] Y = [[1, 2], [0, 3]] with pytest.warns( FutureWarning, match=( "`sum_over_features` is deprecated in version 1.2 and will be" " removed in version 1.4." ), ): manhattan_distances(X, Y, sum_over_features=sum_over_features)
@pytest.mark.parametrize("metric", PAIRWISE_BOOLEAN_FUNCTIONS)def test_pairwise_boolean_distance(metric): # test that we convert to boolean arrays for boolean distances rng = np.random.RandomState(0) X = rng.randn(5, 4) Y = X.copy() Y[0, 0] = 1 - Y[0, 0]
# ignore conversion to boolean in pairwise_distances with ignore_warnings(category=DataConversionWarning): for Z in [Y, None]: res = pairwise_distances(X, Z, metric=metric) res[np.isnan(res)] = 0 assert np.sum(res != 0) == 0
# non-boolean arrays are converted to boolean for boolean # distance metrics with a data conversion warning msg = "Data was converted to boolean for metric %s" % metric with pytest.warns(DataConversionWarning, match=msg): pairwise_distances(X, metric=metric)
# Check that the warning is raised if X is boolean by Y is not boolean: with pytest.warns(DataConversionWarning, match=msg): pairwise_distances(X.astype(bool), Y=Y, metric=metric)
# Check that no warning is raised if X is already boolean and Y is None: with warnings.catch_warnings(): warnings.simplefilter("error", DataConversionWarning) pairwise_distances(X.astype(bool), metric=metric)
def test_no_data_conversion_warning(): # No warnings issued if metric is not a boolean distance function rng = np.random.RandomState(0) X = rng.randn(5, 4) with warnings.catch_warnings(): warnings.simplefilter("error", DataConversionWarning) pairwise_distances(X, metric="minkowski")
@pytest.mark.parametrize("func", [pairwise_distances, pairwise_kernels])def test_pairwise_precomputed(func): # Test correct shape with pytest.raises(ValueError, match=".* shape .*"): func(np.zeros((5, 3)), metric="precomputed") # with two args with pytest.raises(ValueError, match=".* shape .*"): func(np.zeros((5, 3)), np.zeros((4, 4)), metric="precomputed") # even if shape[1] agrees (although thus second arg is spurious) with pytest.raises(ValueError, match=".* shape .*"): func(np.zeros((5, 3)), np.zeros((4, 3)), metric="precomputed")
# Test not copied (if appropriate dtype) S = np.zeros((5, 5)) S2 = func(S, metric="precomputed") assert S is S2 # with two args S = np.zeros((5, 3)) S2 = func(S, np.zeros((3, 3)), metric="precomputed") assert S is S2
# Test always returns float dtype S = func(np.array([[1]], dtype="int"), metric="precomputed") assert "f" == S.dtype.kind
# Test converts list to array-like S = func([[1.0]], metric="precomputed") assert isinstance(S, np.ndarray)
def test_pairwise_precomputed_non_negative(): # Test non-negative values with pytest.raises(ValueError, match=".* non-negative values.*"): pairwise_distances(np.full((5, 5), -1), metric="precomputed")
_minkowski_kwds = {"w": np.arange(1, 5).astype("double", copy=False), "p": 1}_wminkowski_kwds = {"w": np.arange(1, 5).astype("double", copy=False), "p": 1}
def callable_rbf_kernel(x, y, **kwds): # Callable version of pairwise.rbf_kernel. K = rbf_kernel(np.atleast_2d(x), np.atleast_2d(y), **kwds) return K
# TODO: Remove filterwarnings in 1.3 when wminkowski is removed@pytest.mark.filterwarnings("ignore:WMinkowskiDistance:FutureWarning:sklearn")@pytest.mark.parametrize( "func, metric, kwds", [ (pairwise_distances, "euclidean", {}), pytest.param( pairwise_distances, minkowski, _minkowski_kwds, ), pytest.param( pairwise_distances, "minkowski", _minkowski_kwds, ), pytest.param( pairwise_distances, wminkowski, _wminkowski_kwds, marks=pytest.mark.skipif( sp_version >= parse_version("1.6.0"), reason="wminkowski is now minkowski and it has been already tested.", ), ), pytest.param( pairwise_distances, "wminkowski", _wminkowski_kwds, marks=pytest.mark.skipif( sp_version >= parse_version("1.6.0"), reason="wminkowski is now minkowski and it has been already tested.", ), ), (pairwise_kernels, "polynomial", {"degree": 1}), (pairwise_kernels, callable_rbf_kernel, {"gamma": 0.1}), ],)@pytest.mark.parametrize("dtype", [np.float64, np.float32, int])def test_pairwise_parallel(func, metric, kwds, dtype): rng = np.random.RandomState(0) X = np.array(5 * rng.random_sample((5, 4)), dtype=dtype) Y = np.array(5 * rng.random_sample((3, 4)), dtype=dtype)
S = func(X, metric=metric, n_jobs=1, **kwds) S2 = func(X, metric=metric, n_jobs=2, **kwds) assert_allclose(S, S2)
S = func(X, Y, metric=metric, n_jobs=1, **kwds) S2 = func(X, Y, metric=metric, n_jobs=2, **kwds) assert_allclose(S, S2)
def test_pairwise_callable_nonstrict_metric(): # paired_distances should allow callable metric where metric(x, x) != 0 # Knowing that the callable is a strict metric would allow the diagonal to # be left uncalculated and set to 0. assert pairwise_distances([[1.0]], metric=lambda x, y: 5)[0, 0] == 5
# Test with all metrics that should be in PAIRWISE_KERNEL_FUNCTIONS.@pytest.mark.parametrize( "metric", ["rbf", "laplacian", "sigmoid", "polynomial", "linear", "chi2", "additive_chi2"],)def test_pairwise_kernels(metric): # Test the pairwise_kernels helper function.
rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((2, 4)) function = PAIRWISE_KERNEL_FUNCTIONS[metric] # Test with Y=None K1 = pairwise_kernels(X, metric=metric) K2 = function(X) assert_allclose(K1, K2) # Test with Y=Y K1 = pairwise_kernels(X, Y=Y, metric=metric) K2 = function(X, Y=Y) assert_allclose(K1, K2) # Test with tuples as X and Y X_tuples = tuple([tuple([v for v in row]) for row in X]) Y_tuples = tuple([tuple([v for v in row]) for row in Y]) K2 = pairwise_kernels(X_tuples, Y_tuples, metric=metric) assert_allclose(K1, K2)
# Test with sparse X and Y X_sparse = csr_matrix(X) Y_sparse = csr_matrix(Y) if metric in ["chi2", "additive_chi2"]: # these don't support sparse matrices yet with pytest.raises(ValueError): pairwise_kernels(X_sparse, Y=Y_sparse, metric=metric) return K1 = pairwise_kernels(X_sparse, Y=Y_sparse, metric=metric) assert_allclose(K1, K2)
def test_pairwise_kernels_callable(): # Test the pairwise_kernels helper function # with a callable function, with given keywords. rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((2, 4))
metric = callable_rbf_kernel kwds = {"gamma": 0.1} K1 = pairwise_kernels(X, Y=Y, metric=metric, **kwds) K2 = rbf_kernel(X, Y=Y, **kwds) assert_allclose(K1, K2)
# callable function, X=Y K1 = pairwise_kernels(X, Y=X, metric=metric, **kwds) K2 = rbf_kernel(X, Y=X, **kwds) assert_allclose(K1, K2)
def test_pairwise_kernels_filter_param(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((2, 4)) K = rbf_kernel(X, Y, gamma=0.1) params = {"gamma": 0.1, "blabla": ":)"} K2 = pairwise_kernels(X, Y, metric="rbf", filter_params=True, **params) assert_allclose(K, K2)
with pytest.raises(TypeError): pairwise_kernels(X, Y, metric="rbf", **params)
@pytest.mark.parametrize("metric, func", PAIRED_DISTANCES.items())def test_paired_distances(metric, func): # Test the pairwise_distance helper function. rng = np.random.RandomState(0) # Euclidean distance should be equivalent to calling the function. X = rng.random_sample((5, 4)) # Euclidean distance, with Y != X. Y = rng.random_sample((5, 4))
S = paired_distances(X, Y, metric=metric) S2 = func(X, Y) assert_allclose(S, S2) S3 = func(csr_matrix(X), csr_matrix(Y)) assert_allclose(S, S3) if metric in PAIRWISE_DISTANCE_FUNCTIONS: # Check the pairwise_distances implementation # gives the same value distances = PAIRWISE_DISTANCE_FUNCTIONS[metric](X, Y) distances = np.diag(distances) assert_allclose(distances, S)
def test_paired_distances_callable(global_dtype): # Test the paired_distance helper function # with the callable implementation rng = np.random.RandomState(0) # Euclidean distance should be equivalent to calling the function. X = rng.random_sample((5, 4)).astype(global_dtype, copy=False) # Euclidean distance, with Y != X. Y = rng.random_sample((5, 4)).astype(global_dtype, copy=False)
S = paired_distances(X, Y, metric="manhattan") S2 = paired_distances(X, Y, metric=lambda x, y: np.abs(x - y).sum(axis=0)) assert_allclose(S, S2)
# Test that a value error is raised when the lengths of X and Y should not # differ Y = rng.random_sample((3, 4)) with pytest.raises(ValueError): paired_distances(X, Y)
def test_pairwise_distances_argmin_min(global_dtype): # Check pairwise minimum distances computation for any metric X = np.asarray([[0], [1]], dtype=global_dtype) Y = np.asarray([[-2], [3]], dtype=global_dtype)
Xsp = dok_matrix(X) Ysp = csr_matrix(Y, dtype=global_dtype)
expected_idx = [0, 1] expected_vals = [2, 2] expected_vals_sq = [4, 4]
# euclidean metric idx, vals = pairwise_distances_argmin_min(X, Y, metric="euclidean") idx2 = pairwise_distances_argmin(X, Y, metric="euclidean") assert_allclose(idx, expected_idx) assert_allclose(idx2, expected_idx) assert_allclose(vals, expected_vals) # sparse matrix case idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric="euclidean") idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric="euclidean") assert_allclose(idxsp, expected_idx) assert_allclose(idxsp2, expected_idx) assert_allclose(valssp, expected_vals) # We don't want np.matrix here assert type(idxsp) == np.ndarray assert type(valssp) == np.ndarray
# Squared Euclidean metric idx, vals = pairwise_distances_argmin_min(X, Y, metric="sqeuclidean") idx2, vals2 = pairwise_distances_argmin_min( X, Y, metric="euclidean", metric_kwargs={"squared": True} ) idx3 = pairwise_distances_argmin(X, Y, metric="sqeuclidean") idx4 = pairwise_distances_argmin( X, Y, metric="euclidean", metric_kwargs={"squared": True} )
assert_allclose(vals, expected_vals_sq) assert_allclose(vals2, expected_vals_sq)
assert_allclose(idx, expected_idx) assert_allclose(idx2, expected_idx) assert_allclose(idx3, expected_idx) assert_allclose(idx4, expected_idx)
# Non-euclidean scikit-learn metric idx, vals = pairwise_distances_argmin_min(X, Y, metric="manhattan") idx2 = pairwise_distances_argmin(X, Y, metric="manhattan") assert_allclose(idx, expected_idx) assert_allclose(idx2, expected_idx) assert_allclose(vals, expected_vals) # sparse matrix case idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric="manhattan") idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric="manhattan") assert_allclose(idxsp, expected_idx) assert_allclose(idxsp2, expected_idx) assert_allclose(valssp, expected_vals)
# Non-euclidean Scipy distance (callable) idx, vals = pairwise_distances_argmin_min( X, Y, metric=minkowski, metric_kwargs={"p": 2} ) assert_allclose(idx, expected_idx) assert_allclose(vals, expected_vals)
# Non-euclidean Scipy distance (string) idx, vals = pairwise_distances_argmin_min( X, Y, metric="minkowski", metric_kwargs={"p": 2} ) assert_allclose(idx, expected_idx) assert_allclose(vals, expected_vals)
# Compare with naive implementation rng = np.random.RandomState(0) X = rng.randn(97, 149) Y = rng.randn(111, 149)
dist = pairwise_distances(X, Y, metric="manhattan") dist_orig_ind = dist.argmin(axis=0) dist_orig_val = dist[dist_orig_ind, range(len(dist_orig_ind))]
dist_chunked_ind, dist_chunked_val = pairwise_distances_argmin_min( X, Y, axis=0, metric="manhattan" ) assert_allclose(dist_orig_ind, dist_chunked_ind, rtol=1e-7) assert_allclose(dist_orig_val, dist_chunked_val, rtol=1e-7)
# Changing the axis and permuting datasets must give the same results argmin_0, dist_0 = pairwise_distances_argmin_min(X, Y, axis=0) argmin_1, dist_1 = pairwise_distances_argmin_min(Y, X, axis=1)
assert_allclose(dist_0, dist_1) assert_array_equal(argmin_0, argmin_1)
argmin_0, dist_0 = pairwise_distances_argmin_min(X, X, axis=0) argmin_1, dist_1 = pairwise_distances_argmin_min(X, X, axis=1)
assert_allclose(dist_0, dist_1) assert_array_equal(argmin_0, argmin_1)
# Changing the axis and permuting datasets must give the same results argmin_0 = pairwise_distances_argmin(X, Y, axis=0) argmin_1 = pairwise_distances_argmin(Y, X, axis=1)
assert_array_equal(argmin_0, argmin_1)
argmin_0 = pairwise_distances_argmin(X, X, axis=0) argmin_1 = pairwise_distances_argmin(X, X, axis=1)
assert_array_equal(argmin_0, argmin_1)
# F-contiguous arrays must be supported and must return identical results. argmin_C_contiguous = pairwise_distances_argmin(X, Y) argmin_F_contiguous = pairwise_distances_argmin( np.asfortranarray(X), np.asfortranarray(Y) )
assert_array_equal(argmin_C_contiguous, argmin_F_contiguous)
def _reduce_func(dist, start): return dist[:, :100]
def test_pairwise_distances_chunked_reduce(global_dtype): rng = np.random.RandomState(0) X = rng.random_sample((400, 4)).astype(global_dtype, copy=False) # Reduced Euclidean distance S = pairwise_distances(X)[:, :100] S_chunks = pairwise_distances_chunked( X, None, reduce_func=_reduce_func, working_memory=2**-16 ) assert isinstance(S_chunks, GeneratorType) S_chunks = list(S_chunks) assert len(S_chunks) > 1 assert S_chunks[0].dtype == X.dtype
# atol is for diagonal where S is explicitly zeroed on the diagonal assert_allclose(np.vstack(S_chunks), S, atol=1e-7)
def test_pairwise_distances_chunked_reduce_none(global_dtype): # check that the reduce func is allowed to return None rng = np.random.RandomState(0) X = rng.random_sample((10, 4)).astype(global_dtype, copy=False) S_chunks = pairwise_distances_chunked( X, None, reduce_func=lambda dist, start: None, working_memory=2**-16 ) assert isinstance(S_chunks, GeneratorType) S_chunks = list(S_chunks) assert len(S_chunks) > 1 assert all(chunk is None for chunk in S_chunks)
@pytest.mark.parametrize( "good_reduce", [ lambda D, start: list(D), lambda D, start: np.array(D), lambda D, start: csr_matrix(D), lambda D, start: (list(D), list(D)), lambda D, start: (dok_matrix(D), np.array(D), list(D)), ],)def test_pairwise_distances_chunked_reduce_valid(good_reduce): X = np.arange(10).reshape(-1, 1) S_chunks = pairwise_distances_chunked( X, None, reduce_func=good_reduce, working_memory=64 ) next(S_chunks)
@pytest.mark.parametrize( ("bad_reduce", "err_type", "message"), [ ( lambda D, s: np.concatenate([D, D[-1:]]), ValueError, r"length 11\..* input: 10\.", ), ( lambda D, s: (D, np.concatenate([D, D[-1:]])), ValueError, r"length \(10, 11\)\..* input: 10\.", ), (lambda D, s: (D[:9], D), ValueError, r"length \(9, 10\)\..* input: 10\."), ( lambda D, s: 7, TypeError, r"returned 7\. Expected sequence\(s\) of length 10\.", ), ( lambda D, s: (7, 8), TypeError, r"returned \(7, 8\)\. Expected sequence\(s\) of length 10\.", ), ( lambda D, s: (np.arange(10), 9), TypeError, r", 9\)\. Expected sequence\(s\) of length 10\.", ), ],)def test_pairwise_distances_chunked_reduce_invalid( global_dtype, bad_reduce, err_type, message): X = np.arange(10).reshape(-1, 1).astype(global_dtype, copy=False) S_chunks = pairwise_distances_chunked( X, None, reduce_func=bad_reduce, working_memory=64 ) with pytest.raises(err_type, match=message): next(S_chunks)
def check_pairwise_distances_chunked(X, Y, working_memory, metric="euclidean"): gen = pairwise_distances_chunked(X, Y, working_memory=working_memory, metric=metric) assert isinstance(gen, GeneratorType) blockwise_distances = list(gen) Y = X if Y is None else Y min_block_mib = len(Y) * 8 * 2**-20
for block in blockwise_distances: memory_used = block.nbytes assert memory_used <= max(working_memory, min_block_mib) * 2**20
blockwise_distances = np.vstack(blockwise_distances) S = pairwise_distances(X, Y, metric=metric) assert_allclose(blockwise_distances, S, atol=1e-7)
@pytest.mark.parametrize("metric", ("euclidean", "l2", "sqeuclidean"))def test_pairwise_distances_chunked_diagonal(metric, global_dtype): rng = np.random.RandomState(0) X = rng.normal(size=(1000, 10), scale=1e10).astype(global_dtype, copy=False) chunks = list(pairwise_distances_chunked(X, working_memory=1, metric=metric)) assert len(chunks) > 1 assert_allclose(np.diag(np.vstack(chunks)), 0, rtol=1e-10)
@pytest.mark.parametrize("metric", ("euclidean", "l2", "sqeuclidean"))def test_parallel_pairwise_distances_diagonal(metric, global_dtype): rng = np.random.RandomState(0) X = rng.normal(size=(1000, 10), scale=1e10).astype(global_dtype, copy=False) distances = pairwise_distances(X, metric=metric, n_jobs=2) assert_allclose(np.diag(distances), 0, atol=1e-10)
@ignore_warningsdef test_pairwise_distances_chunked(global_dtype): # Test the pairwise_distance helper function. rng = np.random.RandomState(0) # Euclidean distance should be equivalent to calling the function. X = rng.random_sample((200, 4)).astype(global_dtype, copy=False) check_pairwise_distances_chunked(X, None, working_memory=1, metric="euclidean") # Test small amounts of memory for power in range(-16, 0): check_pairwise_distances_chunked( X, None, working_memory=2**power, metric="euclidean" ) # X as list check_pairwise_distances_chunked( X.tolist(), None, working_memory=1, metric="euclidean" ) # Euclidean distance, with Y != X. Y = rng.random_sample((100, 4)).astype(global_dtype, copy=False) check_pairwise_distances_chunked(X, Y, working_memory=1, metric="euclidean") check_pairwise_distances_chunked( X.tolist(), Y.tolist(), working_memory=1, metric="euclidean" ) # absurdly large working_memory check_pairwise_distances_chunked(X, Y, working_memory=10000, metric="euclidean") # "cityblock" uses scikit-learn metric, cityblock (function) is # scipy.spatial. check_pairwise_distances_chunked(X, Y, working_memory=1, metric="cityblock") # Test that a value error is raised if the metric is unknown with pytest.raises(ValueError): next(pairwise_distances_chunked(X, Y, metric="blah"))
# Test precomputed returns all at once D = pairwise_distances(X) gen = pairwise_distances_chunked(D, working_memory=2**-16, metric="precomputed") assert isinstance(gen, GeneratorType) assert next(gen) is D with pytest.raises(StopIteration): next(gen)
@pytest.mark.parametrize( "x_array_constr", [np.array, csr_matrix], ids=["dense", "sparse"])@pytest.mark.parametrize( "y_array_constr", [np.array, csr_matrix], ids=["dense", "sparse"])def test_euclidean_distances_known_result(x_array_constr, y_array_constr): # Check the pairwise Euclidean distances computation on known result X = x_array_constr([[0]]) Y = y_array_constr([[1], [2]]) D = euclidean_distances(X, Y) assert_allclose(D, [[1.0, 2.0]])
@pytest.mark.parametrize( "y_array_constr", [np.array, csr_matrix], ids=["dense", "sparse"])def test_euclidean_distances_with_norms(global_dtype, y_array_constr): # check that we still get the right answers with {X,Y}_norm_squared # and that we get a wrong answer with wrong {X,Y}_norm_squared rng = np.random.RandomState(0) X = rng.random_sample((10, 10)).astype(global_dtype, copy=False) Y = rng.random_sample((20, 10)).astype(global_dtype, copy=False)
# norms will only be used if their dtype is float64 X_norm_sq = (X.astype(np.float64) ** 2).sum(axis=1).reshape(1, -1) Y_norm_sq = (Y.astype(np.float64) ** 2).sum(axis=1).reshape(1, -1)
Y = y_array_constr(Y)
D1 = euclidean_distances(X, Y) D2 = euclidean_distances(X, Y, X_norm_squared=X_norm_sq) D3 = euclidean_distances(X, Y, Y_norm_squared=Y_norm_sq) D4 = euclidean_distances(X, Y, X_norm_squared=X_norm_sq, Y_norm_squared=Y_norm_sq) assert_allclose(D2, D1) assert_allclose(D3, D1) assert_allclose(D4, D1)
# check we get the wrong answer with wrong {X,Y}_norm_squared wrong_D = euclidean_distances( X, Y, X_norm_squared=np.zeros_like(X_norm_sq), Y_norm_squared=np.zeros_like(Y_norm_sq), ) with pytest.raises(AssertionError): assert_allclose(wrong_D, D1)
def test_euclidean_distances_norm_shapes(): # Check all accepted shapes for the norms or appropriate error messages. rng = np.random.RandomState(0) X = rng.random_sample((10, 10)) Y = rng.random_sample((20, 10))
X_norm_squared = (X**2).sum(axis=1) Y_norm_squared = (Y**2).sum(axis=1)
D1 = euclidean_distances( X, Y, X_norm_squared=X_norm_squared, Y_norm_squared=Y_norm_squared ) D2 = euclidean_distances( X, Y, X_norm_squared=X_norm_squared.reshape(-1, 1), Y_norm_squared=Y_norm_squared.reshape(-1, 1), ) D3 = euclidean_distances( X, Y, X_norm_squared=X_norm_squared.reshape(1, -1), Y_norm_squared=Y_norm_squared.reshape(1, -1), )
assert_allclose(D2, D1) assert_allclose(D3, D1)
with pytest.raises(ValueError, match="Incompatible dimensions for X"): euclidean_distances(X, Y, X_norm_squared=X_norm_squared[:5]) with pytest.raises(ValueError, match="Incompatible dimensions for Y"): euclidean_distances(X, Y, Y_norm_squared=Y_norm_squared[:5])
@pytest.mark.parametrize( "x_array_constr", [np.array, csr_matrix], ids=["dense", "sparse"])@pytest.mark.parametrize( "y_array_constr", [np.array, csr_matrix], ids=["dense", "sparse"])def test_euclidean_distances(global_dtype, x_array_constr, y_array_constr): # check that euclidean distances gives same result as scipy cdist # when X and Y != X are provided rng = np.random.RandomState(0) X = rng.random_sample((100, 10)).astype(global_dtype, copy=False) X[X < 0.8] = 0 Y = rng.random_sample((10, 10)).astype(global_dtype, copy=False) Y[Y < 0.8] = 0
expected = cdist(X, Y)
X = x_array_constr(X) Y = y_array_constr(Y) distances = euclidean_distances(X, Y)
# the default rtol=1e-7 is too close to the float32 precision # and fails due to rounding errors. assert_allclose(distances, expected, rtol=1e-6) assert distances.dtype == global_dtype
@pytest.mark.parametrize( "x_array_constr", [np.array, csr_matrix], ids=["dense", "sparse"])def test_euclidean_distances_sym(global_dtype, x_array_constr): # check that euclidean distances gives same result as scipy pdist # when only X is provided rng = np.random.RandomState(0) X = rng.random_sample((100, 10)).astype(global_dtype, copy=False) X[X < 0.8] = 0
expected = squareform(pdist(X))
X = x_array_constr(X) distances = euclidean_distances(X)
# the default rtol=1e-7 is too close to the float32 precision # and fails due to rounding errors. assert_allclose(distances, expected, rtol=1e-6) assert distances.dtype == global_dtype
@pytest.mark.parametrize("batch_size", [None, 5, 7, 101])@pytest.mark.parametrize( "x_array_constr", [np.array, csr_matrix], ids=["dense", "sparse"])@pytest.mark.parametrize( "y_array_constr", [np.array, csr_matrix], ids=["dense", "sparse"])def test_euclidean_distances_upcast(batch_size, x_array_constr, y_array_constr): # check batches handling when Y != X (#13910) rng = np.random.RandomState(0) X = rng.random_sample((100, 10)).astype(np.float32) X[X < 0.8] = 0 Y = rng.random_sample((10, 10)).astype(np.float32) Y[Y < 0.8] = 0
expected = cdist(X, Y)
X = x_array_constr(X) Y = y_array_constr(Y) distances = _euclidean_distances_upcast(X, Y=Y, batch_size=batch_size) distances = np.sqrt(np.maximum(distances, 0))
# the default rtol=1e-7 is too close to the float32 precision # and fails due to rounding errors. assert_allclose(distances, expected, rtol=1e-6)
@pytest.mark.parametrize("batch_size", [None, 5, 7, 101])@pytest.mark.parametrize( "x_array_constr", [np.array, csr_matrix], ids=["dense", "sparse"])def test_euclidean_distances_upcast_sym(batch_size, x_array_constr): # check batches handling when X is Y (#13910) rng = np.random.RandomState(0) X = rng.random_sample((100, 10)).astype(np.float32) X[X < 0.8] = 0
expected = squareform(pdist(X))
X = x_array_constr(X) distances = _euclidean_distances_upcast(X, Y=X, batch_size=batch_size) distances = np.sqrt(np.maximum(distances, 0))
# the default rtol=1e-7 is too close to the float32 precision # and fails due to rounding errors. assert_allclose(distances, expected, rtol=1e-6)
@pytest.mark.parametrize( "dtype, eps, rtol", [ (np.float32, 1e-4, 1e-5), pytest.param( np.float64, 1e-8, 0.99, marks=pytest.mark.xfail(reason="failing due to lack of precision"), ), ],)@pytest.mark.parametrize("dim", [1, 1000000])def test_euclidean_distances_extreme_values(dtype, eps, rtol, dim): # check that euclidean distances is correct with float32 input thanks to # upcasting. On float64 there are still precision issues. X = np.array([[1.0] * dim], dtype=dtype) Y = np.array([[1.0 + eps] * dim], dtype=dtype)
distances = euclidean_distances(X, Y) expected = cdist(X, Y)
assert_allclose(distances, expected, rtol=1e-5)
@pytest.mark.parametrize("squared", [True, False])def test_nan_euclidean_distances_equal_to_euclidean_distance(squared): # with no nan values rng = np.random.RandomState(1337) X = rng.randn(3, 4) Y = rng.randn(4, 4)
normal_distance = euclidean_distances(X, Y=Y, squared=squared) nan_distance = nan_euclidean_distances(X, Y=Y, squared=squared) assert_allclose(normal_distance, nan_distance)
@pytest.mark.parametrize("X", [np.array([[np.inf, 0]]), np.array([[0, -np.inf]])])@pytest.mark.parametrize("Y", [np.array([[np.inf, 0]]), np.array([[0, -np.inf]]), None])def test_nan_euclidean_distances_infinite_values(X, Y):
with pytest.raises(ValueError) as excinfo: nan_euclidean_distances(X, Y=Y)
exp_msg = "Input contains infinity or a value too large for dtype('float64')." assert exp_msg == str(excinfo.value)
@pytest.mark.parametrize( "X, X_diag, missing_value", [ (np.array([[0, 1], [1, 0]]), np.sqrt(2), np.nan), (np.array([[0, 1], [1, np.nan]]), np.sqrt(2), np.nan), (np.array([[np.nan, 1], [1, np.nan]]), np.nan, np.nan), (np.array([[np.nan, 1], [np.nan, 0]]), np.sqrt(2), np.nan), (np.array([[0, np.nan], [1, np.nan]]), np.sqrt(2), np.nan), (np.array([[0, 1], [1, 0]]), np.sqrt(2), -1), (np.array([[0, 1], [1, -1]]), np.sqrt(2), -1), (np.array([[-1, 1], [1, -1]]), np.nan, -1), (np.array([[-1, 1], [-1, 0]]), np.sqrt(2), -1), (np.array([[0, -1], [1, -1]]), np.sqrt(2), -1), ],)def test_nan_euclidean_distances_2x2(X, X_diag, missing_value):
exp_dist = np.array([[0.0, X_diag], [X_diag, 0]])
dist = nan_euclidean_distances(X, missing_values=missing_value) assert_allclose(exp_dist, dist)
dist_sq = nan_euclidean_distances(X, squared=True, missing_values=missing_value) assert_allclose(exp_dist**2, dist_sq)
dist_two = nan_euclidean_distances(X, X, missing_values=missing_value) assert_allclose(exp_dist, dist_two)
dist_two_copy = nan_euclidean_distances(X, X.copy(), missing_values=missing_value) assert_allclose(exp_dist, dist_two_copy)
@pytest.mark.parametrize("missing_value", [np.nan, -1])def test_nan_euclidean_distances_complete_nan(missing_value): X = np.array([[missing_value, missing_value], [0, 1]])
exp_dist = np.array([[np.nan, np.nan], [np.nan, 0]])
dist = nan_euclidean_distances(X, missing_values=missing_value) assert_allclose(exp_dist, dist)
dist = nan_euclidean_distances(X, X.copy(), missing_values=missing_value) assert_allclose(exp_dist, dist)
@pytest.mark.parametrize("missing_value", [np.nan, -1])def test_nan_euclidean_distances_not_trival(missing_value): X = np.array( [ [1.0, missing_value, 3.0, 4.0, 2.0], [missing_value, 4.0, 6.0, 1.0, missing_value], [3.0, missing_value, missing_value, missing_value, 1.0], ] )
Y = np.array( [ [missing_value, 7.0, 7.0, missing_value, 2.0], [missing_value, missing_value, 5.0, 4.0, 7.0], [missing_value, missing_value, missing_value, 4.0, 5.0], ] )
# Check for symmetry D1 = nan_euclidean_distances(X, Y, missing_values=missing_value) D2 = nan_euclidean_distances(Y, X, missing_values=missing_value)
assert_almost_equal(D1, D2.T)
# Check with explicit formula and squared=True assert_allclose( nan_euclidean_distances( X[:1], Y[:1], squared=True, missing_values=missing_value ), [[5.0 / 2.0 * ((7 - 3) ** 2 + (2 - 2) ** 2)]], )
# Check with explicit formula and squared=False assert_allclose( nan_euclidean_distances( X[1:2], Y[1:2], squared=False, missing_values=missing_value ), [[np.sqrt(5.0 / 2.0 * ((6 - 5) ** 2 + (1 - 4) ** 2))]], )
# Check when Y = X is explicitly passed D3 = nan_euclidean_distances(X, missing_values=missing_value) D4 = nan_euclidean_distances(X, X, missing_values=missing_value) D5 = nan_euclidean_distances(X, X.copy(), missing_values=missing_value) assert_allclose(D3, D4) assert_allclose(D4, D5)
# Check copy = True against copy = False D6 = nan_euclidean_distances(X, Y, copy=True) D7 = nan_euclidean_distances(X, Y, copy=False) assert_allclose(D6, D7)
@pytest.mark.parametrize("missing_value", [np.nan, -1])def test_nan_euclidean_distances_one_feature_match_positive(missing_value): # First feature is the only feature that is non-nan and in both # samples. The result of `nan_euclidean_distances` with squared=True # should be non-negative. The non-squared version should all be close to 0. X = np.array( [ [-122.27, 648.0, missing_value, 37.85], [-122.27, missing_value, 2.34701493, missing_value], ] )
dist_squared = nan_euclidean_distances( X, missing_values=missing_value, squared=True ) assert np.all(dist_squared >= 0)
dist = nan_euclidean_distances(X, missing_values=missing_value, squared=False) assert_allclose(dist, 0.0)
def test_cosine_distances(): # Check the pairwise Cosine distances computation rng = np.random.RandomState(1337) x = np.abs(rng.rand(910)) XA = np.vstack([x, x]) D = cosine_distances(XA) assert_allclose(D, [[0.0, 0.0], [0.0, 0.0]], atol=1e-10) # check that all elements are in [0, 2] assert np.all(D >= 0.0) assert np.all(D <= 2.0) # check that diagonal elements are equal to 0 assert_allclose(D[np.diag_indices_from(D)], [0.0, 0.0])
XB = np.vstack([x, -x]) D2 = cosine_distances(XB) # check that all elements are in [0, 2] assert np.all(D2 >= 0.0) assert np.all(D2 <= 2.0) # check that diagonal elements are equal to 0 and non diagonal to 2 assert_allclose(D2, [[0.0, 2.0], [2.0, 0.0]])
# check large random matrix X = np.abs(rng.rand(1000, 5000)) D = cosine_distances(X) # check that diagonal elements are equal to 0 assert_allclose(D[np.diag_indices_from(D)], [0.0] * D.shape[0]) assert np.all(D >= 0.0) assert np.all(D <= 2.0)
def test_haversine_distances(): # Check haversine distance with distances computation def slow_haversine_distances(x, y): diff_lat = y[0] - x[0] diff_lon = y[1] - x[1] a = np.sin(diff_lat / 2) ** 2 + ( np.cos(x[0]) * np.cos(y[0]) * np.sin(diff_lon / 2) ** 2 ) c = 2 * np.arcsin(np.sqrt(a)) return c
rng = np.random.RandomState(0) X = rng.random_sample((5, 2)) Y = rng.random_sample((10, 2)) D1 = np.array([[slow_haversine_distances(x, y) for y in Y] for x in X]) D2 = haversine_distances(X, Y) assert_allclose(D1, D2) # Test haversine distance does not accept X where n_feature != 2 X = rng.random_sample((10, 3)) err_msg = "Haversine distance only valid in 2 dimensions" with pytest.raises(ValueError, match=err_msg): haversine_distances(X)
# Paired distances
def test_paired_euclidean_distances(): # Check the paired Euclidean distances computation X = [[0], [0]] Y = [[1], [2]] D = paired_euclidean_distances(X, Y) assert_allclose(D, [1.0, 2.0])
def test_paired_manhattan_distances(): # Check the paired manhattan distances computation X = [[0], [0]] Y = [[1], [2]] D = paired_manhattan_distances(X, Y) assert_allclose(D, [1.0, 2.0])
def test_chi_square_kernel(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((10, 4)) K_add = additive_chi2_kernel(X, Y) gamma = 0.1 K = chi2_kernel(X, Y, gamma=gamma) assert K.dtype == float for i, x in enumerate(X): for j, y in enumerate(Y): chi2 = -np.sum((x - y) ** 2 / (x + y)) chi2_exp = np.exp(gamma * chi2) assert_almost_equal(K_add[i, j], chi2) assert_almost_equal(K[i, j], chi2_exp)
# check diagonal is ones for data with itself K = chi2_kernel(Y) assert_array_equal(np.diag(K), 1) # check off-diagonal is < 1 but > 0: assert np.all(K > 0) assert np.all(K - np.diag(np.diag(K)) < 1) # check that float32 is preserved X = rng.random_sample((5, 4)).astype(np.float32) Y = rng.random_sample((10, 4)).astype(np.float32) K = chi2_kernel(X, Y) assert K.dtype == np.float32
# check integer type gets converted, # check that zeros are handled X = rng.random_sample((10, 4)).astype(np.int32) K = chi2_kernel(X, X) assert np.isfinite(K).all() assert K.dtype == float
# check that kernel of similar things is greater than dissimilar ones X = [[0.3, 0.7], [1.0, 0]] Y = [[0, 1], [0.9, 0.1]] K = chi2_kernel(X, Y) assert K[0, 0] > K[0, 1] assert K[1, 1] > K[1, 0]
# test negative input with pytest.raises(ValueError): chi2_kernel([[0, -1]]) with pytest.raises(ValueError): chi2_kernel([[0, -1]], [[-1, -1]]) with pytest.raises(ValueError): chi2_kernel([[0, 1]], [[-1, -1]])
# different n_features in X and Y with pytest.raises(ValueError): chi2_kernel([[0, 1]], [[0.2, 0.2, 0.6]])
# sparse matrices with pytest.raises(ValueError): chi2_kernel(csr_matrix(X), csr_matrix(Y)) with pytest.raises(ValueError): additive_chi2_kernel(csr_matrix(X), csr_matrix(Y))
@pytest.mark.parametrize( "kernel", ( linear_kernel, polynomial_kernel, rbf_kernel, laplacian_kernel, sigmoid_kernel, cosine_similarity, ),)def test_kernel_symmetry(kernel): # Valid kernels should be symmetric rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) K = kernel(X, X) assert_allclose(K, K.T, 15)
@pytest.mark.parametrize( "kernel", ( linear_kernel, polynomial_kernel, rbf_kernel, laplacian_kernel, sigmoid_kernel, cosine_similarity, ),)def test_kernel_sparse(kernel): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) X_sparse = csr_matrix(X) K = kernel(X, X) K2 = kernel(X_sparse, X_sparse) assert_allclose(K, K2)
def test_linear_kernel(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) K = linear_kernel(X, X) # the diagonal elements of a linear kernel are their squared norm assert_allclose(K.flat[::6], [linalg.norm(x) ** 2 for x in X])
def test_rbf_kernel(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) K = rbf_kernel(X, X) # the diagonal elements of a rbf kernel are 1 assert_allclose(K.flat[::6], np.ones(5))
def test_laplacian_kernel(): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) K = laplacian_kernel(X, X) # the diagonal elements of a laplacian kernel are 1 assert_allclose(np.diag(K), np.ones(5))
# off-diagonal elements are < 1 but > 0: assert np.all(K > 0) assert np.all(K - np.diag(np.diag(K)) < 1)
@pytest.mark.parametrize( "metric, pairwise_func", [("linear", linear_kernel), ("cosine", cosine_similarity)])def test_pairwise_similarity_sparse_output(metric, pairwise_func): rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((3, 4)) Xcsr = csr_matrix(X) Ycsr = csr_matrix(Y)
# should be sparse K1 = pairwise_func(Xcsr, Ycsr, dense_output=False) assert issparse(K1)
# should be dense, and equal to K1 K2 = pairwise_func(X, Y, dense_output=True) assert not issparse(K2) assert_allclose(K1.toarray(), K2)
# show the kernel output equal to the sparse.toarray() K3 = pairwise_kernels(X, Y=Y, metric=metric) assert_allclose(K1.toarray(), K3)
def test_cosine_similarity(): # Test the cosine_similarity.
rng = np.random.RandomState(0) X = rng.random_sample((5, 4)) Y = rng.random_sample((3, 4)) Xcsr = csr_matrix(X) Ycsr = csr_matrix(Y)
for X_, Y_ in ((X, None), (X, Y), (Xcsr, None), (Xcsr, Ycsr)): # Test that the cosine is kernel is equal to a linear kernel when data # has been previously normalized by L2-norm. K1 = pairwise_kernels(X_, Y=Y_, metric="cosine") X_ = normalize(X_) if Y_ is not None: Y_ = normalize(Y_) K2 = pairwise_kernels(X_, Y=Y_, metric="linear") assert_allclose(K1, K2)
def test_check_dense_matrices(): # Ensure that pairwise array check works for dense matrices. # Check that if XB is None, XB is returned as reference to XA XA = np.resize(np.arange(40), (5, 8)) XA_checked, XB_checked = check_pairwise_arrays(XA, None) assert XA_checked is XB_checked assert_array_equal(XA, XA_checked)
def test_check_XB_returned(): # Ensure that if XA and XB are given correctly, they return as equal. # Check that if XB is not None, it is returned equal. # Note that the second dimension of XB is the same as XA. XA = np.resize(np.arange(40), (5, 8)) XB = np.resize(np.arange(32), (4, 8)) XA_checked, XB_checked = check_pairwise_arrays(XA, XB) assert_array_equal(XA, XA_checked) assert_array_equal(XB, XB_checked)
XB = np.resize(np.arange(40), (5, 8)) XA_checked, XB_checked = check_paired_arrays(XA, XB) assert_array_equal(XA, XA_checked) assert_array_equal(XB, XB_checked)
def test_check_different_dimensions(): # Ensure an error is raised if the dimensions are different. XA = np.resize(np.arange(45), (5, 9)) XB = np.resize(np.arange(32), (4, 8)) with pytest.raises(ValueError): check_pairwise_arrays(XA, XB)
XB = np.resize(np.arange(4 * 9), (4, 9)) with pytest.raises(ValueError): check_paired_arrays(XA, XB)
def test_check_invalid_dimensions(): # Ensure an error is raised on 1D input arrays. # The modified tests are not 1D. In the old test, the array was internally # converted to 2D anyways XA = np.arange(45).reshape(9, 5) XB = np.arange(32).reshape(4, 8) with pytest.raises(ValueError): check_pairwise_arrays(XA, XB) XA = np.arange(45).reshape(9, 5) XB = np.arange(32).reshape(4, 8) with pytest.raises(ValueError): check_pairwise_arrays(XA, XB)
def test_check_sparse_arrays(): # Ensures that checks return valid sparse matrices. rng = np.random.RandomState(0) XA = rng.random_sample((5, 4)) XA_sparse = csr_matrix(XA) XB = rng.random_sample((5, 4)) XB_sparse = csr_matrix(XB) XA_checked, XB_checked = check_pairwise_arrays(XA_sparse, XB_sparse) # compare their difference because testing csr matrices for # equality with '==' does not work as expected. assert issparse(XA_checked) assert abs(XA_sparse - XA_checked).sum() == 0 assert issparse(XB_checked) assert abs(XB_sparse - XB_checked).sum() == 0
XA_checked, XA_2_checked = check_pairwise_arrays(XA_sparse, XA_sparse) assert issparse(XA_checked) assert abs(XA_sparse - XA_checked).sum() == 0 assert issparse(XA_2_checked) assert abs(XA_2_checked - XA_checked).sum() == 0
def tuplify(X): # Turns a numpy matrix (any n-dimensional array) into tuples. s = X.shape if len(s) > 1: # Tuplify each sub-array in the input. return tuple(tuplify(row) for row in X) else: # Single dimension input, just return tuple of contents. return tuple(r for r in X)
def test_check_tuple_input(): # Ensures that checks return valid tuples. rng = np.random.RandomState(0) XA = rng.random_sample((5, 4)) XA_tuples = tuplify(XA) XB = rng.random_sample((5, 4)) XB_tuples = tuplify(XB) XA_checked, XB_checked = check_pairwise_arrays(XA_tuples, XB_tuples) assert_array_equal(XA_tuples, XA_checked) assert_array_equal(XB_tuples, XB_checked)
def test_check_preserve_type(): # Ensures that type float32 is preserved. XA = np.resize(np.arange(40), (5, 8)).astype(np.float32) XB = np.resize(np.arange(40), (5, 8)).astype(np.float32)
XA_checked, XB_checked = check_pairwise_arrays(XA, None) assert XA_checked.dtype == np.float32
# both float32 XA_checked, XB_checked = check_pairwise_arrays(XA, XB) assert XA_checked.dtype == np.float32 assert XB_checked.dtype == np.float32
# mismatched A XA_checked, XB_checked = check_pairwise_arrays(XA.astype(float), XB) assert XA_checked.dtype == float assert XB_checked.dtype == float
# mismatched B XA_checked, XB_checked = check_pairwise_arrays(XA, XB.astype(float)) assert XA_checked.dtype == float assert XB_checked.dtype == float
@pytest.mark.parametrize("n_jobs", [1, 2])@pytest.mark.parametrize("metric", ["seuclidean", "mahalanobis"])@pytest.mark.parametrize( "dist_function", [pairwise_distances, pairwise_distances_chunked])def test_pairwise_distances_data_derived_params(n_jobs, metric, dist_function): # check that pairwise_distances give the same result in sequential and # parallel, when metric has data-derived parameters. with config_context(working_memory=0.1): # to have more than 1 chunk rng = np.random.RandomState(0) X = rng.random_sample((100, 10))
expected_dist = squareform(pdist(X, metric=metric)) dist = np.vstack(tuple(dist_function(X, metric=metric, n_jobs=n_jobs)))
assert_allclose(dist, expected_dist)
@pytest.mark.parametrize("metric", ["seuclidean", "mahalanobis"])def test_pairwise_distances_data_derived_params_error(metric): # check that pairwise_distances raises an error when Y is passed but # metric has data-derived params that are not provided by the user. rng = np.random.RandomState(0) X = rng.random_sample((100, 10)) Y = rng.random_sample((100, 10))
with pytest.raises( ValueError, match=rf"The '(V|VI)' parameter is required for the " rf"{metric} metric", ): pairwise_distances(X, Y, metric=metric)
@pytest.mark.parametrize( "metric", [ "braycurtis", "canberra", "chebyshev", "correlation", "hamming", "mahalanobis", "minkowski", "seuclidean", "sqeuclidean", "cityblock", "cosine", "euclidean", ],)@pytest.mark.parametrize("y_is_x", [True, False], ids=["Y is X", "Y is not X"])def test_numeric_pairwise_distances_datatypes(metric, global_dtype, y_is_x): # Check that pairwise distances gives the same result as pdist and cdist # regardless of input datatype when using any scipy metric for comparing # numeric vectors # # This test is necessary because pairwise_distances used to throw an # error when using metric='seuclidean' and the input data was not # of type np.float64 (#15730)
rng = np.random.RandomState(0)
X = rng.random_sample((5, 4)).astype(global_dtype, copy=False)
params = {} if y_is_x: Y = X expected_dist = squareform(pdist(X, metric=metric)) else: Y = rng.random_sample((5, 4)).astype(global_dtype, copy=False) expected_dist = cdist(X, Y, metric=metric) # precompute parameters for seuclidean & mahalanobis when x is not y if metric == "seuclidean": params = {"V": np.var(np.vstack([X, Y]), axis=0, ddof=1, dtype=np.float64)} elif metric == "mahalanobis": params = {"VI": np.linalg.inv(np.cov(np.vstack([X, Y]).T)).T}
dist = pairwise_distances(X, Y, metric=metric, **params)
assert_allclose(dist, expected_dist)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117import reimport pytestimport numpy as npimport warningsfrom scipy.sparse import csr_matrixfrom scipy import stats
from sklearn import datasetsfrom sklearn import svm
from sklearn.utils.extmath import softmaxfrom sklearn.datasets import make_multilabel_classificationfrom sklearn.random_projection import _sparse_random_matrixfrom sklearn.utils.validation import check_array, check_consistent_lengthfrom sklearn.utils.validation import check_random_state
from sklearn.utils._testing import assert_allclosefrom sklearn.utils._testing import assert_almost_equalfrom sklearn.utils._testing import assert_array_equalfrom sklearn.utils._testing import assert_array_almost_equal
from sklearn.metrics import accuracy_scorefrom sklearn.metrics import aucfrom sklearn.metrics import average_precision_scorefrom sklearn.metrics import coverage_errorfrom sklearn.metrics import det_curvefrom sklearn.metrics import label_ranking_average_precision_scorefrom sklearn.metrics import precision_recall_curvefrom sklearn.metrics import label_ranking_lossfrom sklearn.metrics import roc_auc_scorefrom sklearn.metrics import roc_curvefrom sklearn.metrics._ranking import _ndcg_sample_scores, _dcg_sample_scoresfrom sklearn.metrics import ndcg_score, dcg_scorefrom sklearn.metrics import top_k_accuracy_score
from sklearn.exceptions import UndefinedMetricWarningfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.preprocessing import label_binarize
################################################################################ Utilities for testing
CURVE_FUNCS = [ det_curve, precision_recall_curve, roc_curve,]
def make_prediction(dataset=None, binary=False): """Make some classification predictions on a toy dataset using a SVC
If binary is True restrict to a binary classification problem instead of a multiclass classification problem """
if dataset is None: # import some data to play with dataset = datasets.load_iris()
X = dataset.data y = dataset.target
if binary: # restrict to a binary classification task X, y = X[y < 2], y[y < 2]
n_samples, n_features = X.shape p = np.arange(n_samples)
rng = check_random_state(37) rng.shuffle(p) X, y = X[p], y[p] half = int(n_samples / 2)
# add noisy features to make the problem harder and avoid perfect results rng = np.random.RandomState(0) X = np.c_[X, rng.randn(n_samples, 200 * n_features)]
# run classifier, get class probabilities and label predictions clf = svm.SVC(kernel="linear", probability=True, random_state=0) y_score = clf.fit(X[:half], y[:half]).predict_proba(X[half:])
if binary: # only interested in probabilities of the positive case # XXX: do we really want a special API for the binary case? y_score = y_score[:, 1]
y_pred = clf.predict(X[half:]) y_true = y[half:] return y_true, y_pred, y_score
################################################################################ Tests
def _auc(y_true, y_score): """Alternative implementation to check for correctness of `roc_auc_score`.""" pos_label = np.unique(y_true)[1]
# Count the number of times positive samples are correctly ranked above # negative samples. pos = y_score[y_true == pos_label] neg = y_score[y_true != pos_label] diff_matrix = pos.reshape(1, -1) - neg.reshape(-1, 1) n_correct = np.sum(diff_matrix > 0)
return n_correct / float(len(pos) * len(neg))
def _average_precision(y_true, y_score): """Alternative implementation to check for correctness of `average_precision_score`.
Note that this implementation fails on some edge cases. For example, for constant predictions e.g. [0.5, 0.5, 0.5], y_true = [1, 0, 0] returns an average precision of 0.33... but y_true = [0, 0, 1] returns 1.0. """ pos_label = np.unique(y_true)[1] n_pos = np.sum(y_true == pos_label) order = np.argsort(y_score)[::-1] y_score = y_score[order] y_true = y_true[order]
score = 0 for i in range(len(y_score)): if y_true[i] == pos_label: # Compute precision up to document i # i.e, percentage of relevant documents up to document i. prec = 0 for j in range(0, i + 1): if y_true[j] == pos_label: prec += 1.0 prec /= i + 1.0 score += prec
return score / n_pos
def _average_precision_slow(y_true, y_score): """A second alternative implementation of average precision that closely follows the Wikipedia article's definition (see References). This should give identical results as `average_precision_score` for all inputs.
References ---------- .. [1] `Wikipedia entry for the Average precision <https://en.wikipedia.org/wiki/Average_precision>`_ """ precision, recall, threshold = precision_recall_curve(y_true, y_score) precision = list(reversed(precision)) recall = list(reversed(recall)) average_precision = 0 for i in range(1, len(precision)): average_precision += precision[i] * (recall[i] - recall[i - 1]) return average_precision
def _partial_roc_auc_score(y_true, y_predict, max_fpr): """Alternative implementation to check for correctness of `roc_auc_score` with `max_fpr` set. """
def _partial_roc(y_true, y_predict, max_fpr): fpr, tpr, _ = roc_curve(y_true, y_predict) new_fpr = fpr[fpr <= max_fpr] new_fpr = np.append(new_fpr, max_fpr) new_tpr = tpr[fpr <= max_fpr] idx_out = np.argmax(fpr > max_fpr) idx_in = idx_out - 1 x_interp = [fpr[idx_in], fpr[idx_out]] y_interp = [tpr[idx_in], tpr[idx_out]] new_tpr = np.append(new_tpr, np.interp(max_fpr, x_interp, y_interp)) return (new_fpr, new_tpr)
new_fpr, new_tpr = _partial_roc(y_true, y_predict, max_fpr) partial_auc = auc(new_fpr, new_tpr)
# Formula (5) from McClish 1989 fpr1 = 0 fpr2 = max_fpr min_area = 0.5 * (fpr2 - fpr1) * (fpr2 + fpr1) max_area = fpr2 - fpr1 return 0.5 * (1 + (partial_auc - min_area) / (max_area - min_area))
@pytest.mark.parametrize("drop", [True, False])def test_roc_curve(drop): # Test Area under Receiver Operating Characteristic (ROC) curve y_true, _, y_score = make_prediction(binary=True) expected_auc = _auc(y_true, y_score)
fpr, tpr, thresholds = roc_curve(y_true, y_score, drop_intermediate=drop) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, expected_auc, decimal=2) assert_almost_equal(roc_auc, roc_auc_score(y_true, y_score)) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape
def test_roc_curve_end_points(): # Make sure that roc_curve returns a curve start at 0 and ending and # 1 even in corner cases rng = np.random.RandomState(0) y_true = np.array([0] * 50 + [1] * 50) y_pred = rng.randint(3, size=100) fpr, tpr, thr = roc_curve(y_true, y_pred, drop_intermediate=True) assert fpr[0] == 0 assert fpr[-1] == 1 assert fpr.shape == tpr.shape assert fpr.shape == thr.shape
def test_roc_returns_consistency(): # Test whether the returned threshold matches up with tpr # make small toy dataset y_true, _, y_score = make_prediction(binary=True) fpr, tpr, thresholds = roc_curve(y_true, y_score)
# use the given thresholds to determine the tpr tpr_correct = [] for t in thresholds: tp = np.sum((y_score >= t) & y_true) p = np.sum(y_true) tpr_correct.append(1.0 * tp / p)
# compare tpr and tpr_correct to see if the thresholds' order was correct assert_array_almost_equal(tpr, tpr_correct, decimal=2) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape
def test_roc_curve_multi(): # roc_curve not applicable for multi-class problems y_true, _, y_score = make_prediction(binary=False)
with pytest.raises(ValueError): roc_curve(y_true, y_score)
def test_roc_curve_confidence(): # roc_curve for confidence scores y_true, _, y_score = make_prediction(binary=True)
fpr, tpr, thresholds = roc_curve(y_true, y_score - 0.5) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, 0.90, decimal=2) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape
def test_roc_curve_hard(): # roc_curve for hard decisions y_true, pred, y_score = make_prediction(binary=True)
# always predict one trivial_pred = np.ones(y_true.shape) fpr, tpr, thresholds = roc_curve(y_true, trivial_pred) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, 0.50, decimal=2) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape
# always predict zero trivial_pred = np.zeros(y_true.shape) fpr, tpr, thresholds = roc_curve(y_true, trivial_pred) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, 0.50, decimal=2) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape
# hard decisions fpr, tpr, thresholds = roc_curve(y_true, pred) roc_auc = auc(fpr, tpr) assert_array_almost_equal(roc_auc, 0.78, decimal=2) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape
def test_roc_curve_one_label(): y_true = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] y_pred = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] # assert there are warnings expected_message = ( "No negative samples in y_true, false positive value should be meaningless" ) with pytest.warns(UndefinedMetricWarning, match=expected_message): fpr, tpr, thresholds = roc_curve(y_true, y_pred)
# all true labels, all fpr should be nan assert_array_equal(fpr, np.full(len(thresholds), np.nan)) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape
# assert there are warnings expected_message = ( "No positive samples in y_true, true positive value should be meaningless" ) with pytest.warns(UndefinedMetricWarning, match=expected_message): fpr, tpr, thresholds = roc_curve([1 - x for x in y_true], y_pred) # all negative labels, all tpr should be nan assert_array_equal(tpr, np.full(len(thresholds), np.nan)) assert fpr.shape == tpr.shape assert fpr.shape == thresholds.shape
def test_roc_curve_toydata(): # Binary classification y_true = [0, 1] y_score = [0, 1] tpr, fpr, _ = roc_curve(y_true, y_score) roc_auc = roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [0, 0, 1]) assert_array_almost_equal(fpr, [0, 1, 1]) assert_almost_equal(roc_auc, 1.0)
y_true = [0, 1] y_score = [1, 0] tpr, fpr, _ = roc_curve(y_true, y_score) roc_auc = roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [0, 1, 1]) assert_array_almost_equal(fpr, [0, 0, 1]) assert_almost_equal(roc_auc, 0.0)
y_true = [1, 0] y_score = [1, 1] tpr, fpr, _ = roc_curve(y_true, y_score) roc_auc = roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [0, 1]) assert_array_almost_equal(fpr, [0, 1]) assert_almost_equal(roc_auc, 0.5)
y_true = [1, 0] y_score = [1, 0] tpr, fpr, _ = roc_curve(y_true, y_score) roc_auc = roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [0, 0, 1]) assert_array_almost_equal(fpr, [0, 1, 1]) assert_almost_equal(roc_auc, 1.0)
y_true = [1, 0] y_score = [0.5, 0.5] tpr, fpr, _ = roc_curve(y_true, y_score) roc_auc = roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [0, 1]) assert_array_almost_equal(fpr, [0, 1]) assert_almost_equal(roc_auc, 0.5)
y_true = [0, 0] y_score = [0.25, 0.75] # assert UndefinedMetricWarning because of no positive sample in y_true expected_message = ( "No positive samples in y_true, true positive value should be meaningless" ) with pytest.warns(UndefinedMetricWarning, match=expected_message): tpr, fpr, _ = roc_curve(y_true, y_score)
with pytest.raises(ValueError): roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [0.0, 0.5, 1.0]) assert_array_almost_equal(fpr, [np.nan, np.nan, np.nan])
y_true = [1, 1] y_score = [0.25, 0.75] # assert UndefinedMetricWarning because of no negative sample in y_true expected_message = ( "No negative samples in y_true, false positive value should be meaningless" ) with pytest.warns(UndefinedMetricWarning, match=expected_message): tpr, fpr, _ = roc_curve(y_true, y_score)
with pytest.raises(ValueError): roc_auc_score(y_true, y_score) assert_array_almost_equal(tpr, [np.nan, np.nan, np.nan]) assert_array_almost_equal(fpr, [0.0, 0.5, 1.0])
# Multi-label classification task y_true = np.array([[0, 1], [0, 1]]) y_score = np.array([[0, 1], [0, 1]]) with pytest.raises(ValueError): roc_auc_score(y_true, y_score, average="macro") with pytest.raises(ValueError): roc_auc_score(y_true, y_score, average="weighted") assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 1.0) assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 1.0)
y_true = np.array([[0, 1], [0, 1]]) y_score = np.array([[0, 1], [1, 0]]) with pytest.raises(ValueError): roc_auc_score(y_true, y_score, average="macro") with pytest.raises(ValueError): roc_auc_score(y_true, y_score, average="weighted") assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 0.5) assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 0.5)
y_true = np.array([[1, 0], [0, 1]]) y_score = np.array([[0, 1], [1, 0]]) assert_almost_equal(roc_auc_score(y_true, y_score, average="macro"), 0) assert_almost_equal(roc_auc_score(y_true, y_score, average="weighted"), 0) assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 0) assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 0)
y_true = np.array([[1, 0], [0, 1]]) y_score = np.array([[0.5, 0.5], [0.5, 0.5]]) assert_almost_equal(roc_auc_score(y_true, y_score, average="macro"), 0.5) assert_almost_equal(roc_auc_score(y_true, y_score, average="weighted"), 0.5) assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 0.5) assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 0.5)
def test_roc_curve_drop_intermediate(): # Test that drop_intermediate drops the correct thresholds y_true = [0, 0, 0, 0, 1, 1] y_score = [0.0, 0.2, 0.5, 0.6, 0.7, 1.0] tpr, fpr, thresholds = roc_curve(y_true, y_score, drop_intermediate=True) assert_array_almost_equal(thresholds, [2.0, 1.0, 0.7, 0.0])
# Test dropping thresholds with repeating scores y_true = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] y_score = [0.0, 0.1, 0.6, 0.6, 0.7, 0.8, 0.9, 0.6, 0.7, 0.8, 0.9, 0.9, 1.0] tpr, fpr, thresholds = roc_curve(y_true, y_score, drop_intermediate=True) assert_array_almost_equal(thresholds, [2.0, 1.0, 0.9, 0.7, 0.6, 0.0])
def test_roc_curve_fpr_tpr_increasing(): # Ensure that fpr and tpr returned by roc_curve are increasing. # Construct an edge case with float y_score and sample_weight # when some adjacent values of fpr and tpr are actually the same. y_true = [0, 0, 1, 1, 1] y_score = [0.1, 0.7, 0.3, 0.4, 0.5] sample_weight = np.repeat(0.2, 5) fpr, tpr, _ = roc_curve(y_true, y_score, sample_weight=sample_weight) assert (np.diff(fpr) < 0).sum() == 0 assert (np.diff(tpr) < 0).sum() == 0
def test_auc(): # Test Area Under Curve (AUC) computation x = [0, 1] y = [0, 1] assert_array_almost_equal(auc(x, y), 0.5) x = [1, 0] y = [0, 1] assert_array_almost_equal(auc(x, y), 0.5) x = [1, 0, 0] y = [0, 1, 1] assert_array_almost_equal(auc(x, y), 0.5) x = [0, 1] y = [1, 1] assert_array_almost_equal(auc(x, y), 1) x = [0, 0.5, 1] y = [0, 0.5, 1] assert_array_almost_equal(auc(x, y), 0.5)
def test_auc_errors(): # Incompatible shapes with pytest.raises(ValueError): auc([0.0, 0.5, 1.0], [0.1, 0.2])
# Too few x values with pytest.raises(ValueError): auc([0.0], [0.1])
# x is not in order x = [2, 1, 3, 4] y = [5, 6, 7, 8] error_message = "x is neither increasing nor decreasing : {}".format(np.array(x)) with pytest.raises(ValueError, match=re.escape(error_message)): auc(x, y)
@pytest.mark.parametrize( "y_true, labels", [ (np.array([0, 1, 0, 2]), [0, 1, 2]), (np.array([0, 1, 0, 2]), None), (["a", "b", "a", "c"], ["a", "b", "c"]), (["a", "b", "a", "c"], None), ],)def test_multiclass_ovo_roc_auc_toydata(y_true, labels): # Tests the one-vs-one multiclass ROC AUC algorithm # on a small example, representative of an expected use case. y_scores = np.array( [[0.1, 0.8, 0.1], [0.3, 0.4, 0.3], [0.35, 0.5, 0.15], [0, 0.2, 0.8]] )
# Used to compute the expected output. # Consider labels 0 and 1: # positive label is 0, negative label is 1 score_01 = roc_auc_score([1, 0, 1], [0.1, 0.3, 0.35]) # positive label is 1, negative label is 0 score_10 = roc_auc_score([0, 1, 0], [0.8, 0.4, 0.5]) average_score_01 = (score_01 + score_10) / 2
# Consider labels 0 and 2: score_02 = roc_auc_score([1, 1, 0], [0.1, 0.35, 0]) score_20 = roc_auc_score([0, 0, 1], [0.1, 0.15, 0.8]) average_score_02 = (score_02 + score_20) / 2
# Consider labels 1 and 2: score_12 = roc_auc_score([1, 0], [0.4, 0.2]) score_21 = roc_auc_score([0, 1], [0.3, 0.8]) average_score_12 = (score_12 + score_21) / 2
# Unweighted, one-vs-one multiclass ROC AUC algorithm ovo_unweighted_score = (average_score_01 + average_score_02 + average_score_12) / 3 assert_almost_equal( roc_auc_score(y_true, y_scores, labels=labels, multi_class="ovo"), ovo_unweighted_score, )
# Weighted, one-vs-one multiclass ROC AUC algorithm # Each term is weighted by the prevalence for the positive label. pair_scores = [average_score_01, average_score_02, average_score_12] prevalence = [0.75, 0.75, 0.50] ovo_weighted_score = np.average(pair_scores, weights=prevalence) assert_almost_equal( roc_auc_score( y_true, y_scores, labels=labels, multi_class="ovo", average="weighted" ), ovo_weighted_score, )
# Check that average=None raises NotImplemented error error_message = "average=None is not implemented for multi_class='ovo'." with pytest.raises(NotImplementedError, match=error_message): roc_auc_score(y_true, y_scores, labels=labels, multi_class="ovo", average=None)
@pytest.mark.parametrize( "y_true, labels", [ (np.array([0, 2, 0, 2]), [0, 1, 2]), (np.array(["a", "d", "a", "d"]), ["a", "b", "d"]), ],)def test_multiclass_ovo_roc_auc_toydata_binary(y_true, labels): # Tests the one-vs-one multiclass ROC AUC algorithm for binary y_true # # on a small example, representative of an expected use case. y_scores = np.array( [[0.2, 0.0, 0.8], [0.6, 0.0, 0.4], [0.55, 0.0, 0.45], [0.4, 0.0, 0.6]] )
# Used to compute the expected output. # Consider labels 0 and 1: # positive label is 0, negative label is 1 score_01 = roc_auc_score([1, 0, 1, 0], [0.2, 0.6, 0.55, 0.4]) # positive label is 1, negative label is 0 score_10 = roc_auc_score([0, 1, 0, 1], [0.8, 0.4, 0.45, 0.6]) ovo_score = (score_01 + score_10) / 2
assert_almost_equal( roc_auc_score(y_true, y_scores, labels=labels, multi_class="ovo"), ovo_score )
# Weighted, one-vs-one multiclass ROC AUC algorithm assert_almost_equal( roc_auc_score( y_true, y_scores, labels=labels, multi_class="ovo", average="weighted" ), ovo_score, )
@pytest.mark.parametrize( "y_true, labels", [ (np.array([0, 1, 2, 2]), None), (["a", "b", "c", "c"], None), ([0, 1, 2, 2], [0, 1, 2]), (["a", "b", "c", "c"], ["a", "b", "c"]), ],)def test_multiclass_ovr_roc_auc_toydata(y_true, labels): # Tests the unweighted, one-vs-rest multiclass ROC AUC algorithm # on a small example, representative of an expected use case. y_scores = np.array( [[1.0, 0.0, 0.0], [0.1, 0.5, 0.4], [0.1, 0.1, 0.8], [0.3, 0.3, 0.4]] ) # Compute the expected result by individually computing the 'one-vs-rest' # ROC AUC scores for classes 0, 1, and 2. out_0 = roc_auc_score([1, 0, 0, 0], y_scores[:, 0]) out_1 = roc_auc_score([0, 1, 0, 0], y_scores[:, 1]) out_2 = roc_auc_score([0, 0, 1, 1], y_scores[:, 2]) assert_almost_equal( roc_auc_score(y_true, y_scores, multi_class="ovr", labels=labels, average=None), [out_0, out_1, out_2], )
# Compute unweighted results (default behaviour is average="macro") result_unweighted = (out_0 + out_1 + out_2) / 3.0 assert_almost_equal( roc_auc_score(y_true, y_scores, multi_class="ovr", labels=labels), result_unweighted, )
# Tests the weighted, one-vs-rest multiclass ROC AUC algorithm # on the same input (Provost & Domingos, 2000) result_weighted = out_0 * 0.25 + out_1 * 0.25 + out_2 * 0.5 assert_almost_equal( roc_auc_score( y_true, y_scores, multi_class="ovr", labels=labels, average="weighted" ), result_weighted, )
@pytest.mark.parametrize( "multi_class, average", [ ("ovr", "macro"), ("ovr", "micro"), ("ovo", "macro"), ],)def test_perfect_imperfect_chance_multiclass_roc_auc(multi_class, average): y_true = np.array([3, 1, 2, 0])
# Perfect classifier (from a ranking point of view) has roc_auc_score = 1.0 y_perfect = [ [0.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.75, 0.05, 0.05, 0.15], ] assert_almost_equal( roc_auc_score(y_true, y_perfect, multi_class=multi_class, average=average), 1.0, )
# Imperfect classifier has roc_auc_score < 1.0 y_imperfect = [ [0.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] assert ( roc_auc_score(y_true, y_imperfect, multi_class=multi_class, average=average) < 1.0 )
# Chance level classifier has roc_auc_score = 5.0 y_chance = 0.25 * np.ones((4, 4)) assert roc_auc_score( y_true, y_chance, multi_class=multi_class, average=average ) == pytest.approx(0.5)
def test_micro_averaged_ovr_roc_auc(global_random_seed): seed = global_random_seed # Let's generate a set of random predictions and matching true labels such # that the predictions are not perfect. To make the problem more interesting, # we use an imbalanced class distribution (by using different parameters # in the Dirichlet prior (conjugate prior of the multinomial distribution). y_pred = stats.dirichlet.rvs([2.0, 1.0, 0.5], size=1000, random_state=seed) y_true = np.asarray( [ stats.multinomial.rvs(n=1, p=y_pred_i, random_state=seed).argmax() for y_pred_i in y_pred ] ) y_onehot = label_binarize(y_true, classes=[0, 1, 2]) fpr, tpr, _ = roc_curve(y_onehot.ravel(), y_pred.ravel()) roc_auc_by_hand = auc(fpr, tpr) roc_auc_auto = roc_auc_score(y_true, y_pred, multi_class="ovr", average="micro") assert roc_auc_by_hand == pytest.approx(roc_auc_auto)
@pytest.mark.parametrize( "msg, y_true, labels", [ ("Parameter 'labels' must be unique", np.array([0, 1, 2, 2]), [0, 2, 0]), ( "Parameter 'labels' must be unique", np.array(["a", "b", "c", "c"]), ["a", "a", "b"], ), ( "Number of classes in y_true not equal to the number of columns " "in 'y_score'", np.array([0, 2, 0, 2]), None, ), ( "Parameter 'labels' must be ordered", np.array(["a", "b", "c", "c"]), ["a", "c", "b"], ), ( "Number of given labels, 2, not equal to the number of columns in " "'y_score', 3", np.array([0, 1, 2, 2]), [0, 1], ), ( "Number of given labels, 2, not equal to the number of columns in " "'y_score', 3", np.array(["a", "b", "c", "c"]), ["a", "b"], ), ( "Number of given labels, 4, not equal to the number of columns in " "'y_score', 3", np.array([0, 1, 2, 2]), [0, 1, 2, 3], ), ( "Number of given labels, 4, not equal to the number of columns in " "'y_score', 3", np.array(["a", "b", "c", "c"]), ["a", "b", "c", "d"], ), ( "'y_true' contains labels not in parameter 'labels'", np.array(["a", "b", "c", "e"]), ["a", "b", "c"], ), ( "'y_true' contains labels not in parameter 'labels'", np.array(["a", "b", "c", "d"]), ["a", "b", "c"], ), ( "'y_true' contains labels not in parameter 'labels'", np.array([0, 1, 2, 3]), [0, 1, 2], ), ],)@pytest.mark.parametrize("multi_class", ["ovo", "ovr"])def test_roc_auc_score_multiclass_labels_error(msg, y_true, labels, multi_class): y_scores = np.array( [[0.1, 0.8, 0.1], [0.3, 0.4, 0.3], [0.35, 0.5, 0.15], [0, 0.2, 0.8]] )
with pytest.raises(ValueError, match=msg): roc_auc_score(y_true, y_scores, labels=labels, multi_class=multi_class)
@pytest.mark.parametrize( "msg, kwargs", [ ( ( r"average must be one of \('macro', 'weighted', None\) for " r"multiclass problems" ), {"average": "samples", "multi_class": "ovo"}, ), ( ( r"average must be one of \('micro', 'macro', 'weighted', None\) for " r"multiclass problems" ), {"average": "samples", "multi_class": "ovr"}, ), ( ( r"sample_weight is not supported for multiclass one-vs-one " r"ROC AUC, 'sample_weight' must be None in this case" ), {"multi_class": "ovo", "sample_weight": []}, ), ( ( r"Partial AUC computation not available in multiclass setting, " r"'max_fpr' must be set to `None`, received `max_fpr=0.5` " r"instead" ), {"multi_class": "ovo", "max_fpr": 0.5}, ), ( ( r"multi_class='ovp' is not supported for multiclass ROC AUC, " r"multi_class must be in \('ovo', 'ovr'\)" ), {"multi_class": "ovp"}, ), (r"multi_class must be in \('ovo', 'ovr'\)", {}), ],)def test_roc_auc_score_multiclass_error(msg, kwargs): # Test that roc_auc_score function returns an error when trying # to compute multiclass AUC for parameters where an output # is not defined. rng = check_random_state(404) y_score = rng.rand(20, 3) y_prob = softmax(y_score) y_true = rng.randint(0, 3, size=20) with pytest.raises(ValueError, match=msg): roc_auc_score(y_true, y_prob, **kwargs)
def test_auc_score_non_binary_class(): # Test that roc_auc_score function returns an error when trying # to compute AUC for non-binary class values. rng = check_random_state(404) y_pred = rng.rand(10) # y_true contains only one class value y_true = np.zeros(10, dtype="int") err_msg = "ROC AUC score is not defined" with pytest.raises(ValueError, match=err_msg): roc_auc_score(y_true, y_pred) y_true = np.ones(10, dtype="int") with pytest.raises(ValueError, match=err_msg): roc_auc_score(y_true, y_pred) y_true = np.full(10, -1, dtype="int") with pytest.raises(ValueError, match=err_msg): roc_auc_score(y_true, y_pred)
with warnings.catch_warnings(record=True): rng = check_random_state(404) y_pred = rng.rand(10) # y_true contains only one class value y_true = np.zeros(10, dtype="int") with pytest.raises(ValueError, match=err_msg): roc_auc_score(y_true, y_pred) y_true = np.ones(10, dtype="int") with pytest.raises(ValueError, match=err_msg): roc_auc_score(y_true, y_pred) y_true = np.full(10, -1, dtype="int") with pytest.raises(ValueError, match=err_msg): roc_auc_score(y_true, y_pred)
@pytest.mark.parametrize("curve_func", CURVE_FUNCS)def test_binary_clf_curve_multiclass_error(curve_func): rng = check_random_state(404) y_true = rng.randint(0, 3, size=10) y_pred = rng.rand(10) msg = "multiclass format is not supported" with pytest.raises(ValueError, match=msg): curve_func(y_true, y_pred)
@pytest.mark.parametrize("curve_func", CURVE_FUNCS)def test_binary_clf_curve_implicit_pos_label(curve_func): # Check that using string class labels raises an informative # error for any supported string dtype: msg = ( "y_true takes value in {'a', 'b'} and pos_label is " "not specified: either make y_true take " "value in {0, 1} or {-1, 1} or pass pos_label " "explicitly." ) with pytest.raises(ValueError, match=msg): curve_func(np.array(["a", "b"], dtype="<U1"), [0.0, 1.0])
with pytest.raises(ValueError, match=msg): curve_func(np.array(["a", "b"], dtype=object), [0.0, 1.0])
# The error message is slightly different for bytes-encoded # class labels, but otherwise the behavior is the same: msg = ( "y_true takes value in {b'a', b'b'} and pos_label is " "not specified: either make y_true take " "value in {0, 1} or {-1, 1} or pass pos_label " "explicitly." ) with pytest.raises(ValueError, match=msg): curve_func(np.array([b"a", b"b"], dtype="<S1"), [0.0, 1.0])
# Check that it is possible to use floating point class labels # that are interpreted similarly to integer class labels: y_pred = [0.0, 1.0, 0.2, 0.42] int_curve = curve_func([0, 1, 1, 0], y_pred) float_curve = curve_func([0.0, 1.0, 1.0, 0.0], y_pred) for int_curve_part, float_curve_part in zip(int_curve, float_curve): np.testing.assert_allclose(int_curve_part, float_curve_part)
@pytest.mark.parametrize("curve_func", CURVE_FUNCS)def test_binary_clf_curve_zero_sample_weight(curve_func): y_true = [0, 0, 1, 1, 1] y_score = [0.1, 0.2, 0.3, 0.4, 0.5] sample_weight = [1, 1, 1, 0.5, 0]
result_1 = curve_func(y_true, y_score, sample_weight=sample_weight) result_2 = curve_func(y_true[:-1], y_score[:-1], sample_weight=sample_weight[:-1])
for arr_1, arr_2 in zip(result_1, result_2): assert_allclose(arr_1, arr_2)
def test_precision_recall_curve(): y_true, _, y_score = make_prediction(binary=True) _test_precision_recall_curve(y_true, y_score)
# Make sure the first point of the Precision-Recall on the right is: # (p=1.0, r=class balance) on a non-balanced dataset [1:] p, r, t = precision_recall_curve(y_true[1:], y_score[1:]) assert r[0] == 1.0 assert p[0] == y_true[1:].mean()
# Use {-1, 1} for labels; make sure original labels aren't modified y_true[np.where(y_true == 0)] = -1 y_true_copy = y_true.copy() _test_precision_recall_curve(y_true, y_score) assert_array_equal(y_true_copy, y_true)
labels = [1, 0, 0, 1] predict_probas = [1, 2, 3, 4] p, r, t = precision_recall_curve(labels, predict_probas) assert_array_almost_equal(p, np.array([0.5, 0.33333333, 0.5, 1.0, 1.0])) assert_array_almost_equal(r, np.array([1.0, 0.5, 0.5, 0.5, 0.0])) assert_array_almost_equal(t, np.array([1, 2, 3, 4])) assert p.size == r.size assert p.size == t.size + 1
def _test_precision_recall_curve(y_true, y_score): # Test Precision-Recall and area under PR curve p, r, thresholds = precision_recall_curve(y_true, y_score) precision_recall_auc = _average_precision_slow(y_true, y_score) assert_array_almost_equal(precision_recall_auc, 0.859, 3) assert_array_almost_equal( precision_recall_auc, average_precision_score(y_true, y_score) ) # `_average_precision` is not very precise in case of 0.5 ties: be tolerant assert_almost_equal( _average_precision(y_true, y_score), precision_recall_auc, decimal=2 ) assert p.size == r.size assert p.size == thresholds.size + 1 # Smoke test in the case of proba having only one value p, r, thresholds = precision_recall_curve(y_true, np.zeros_like(y_score)) assert p.size == r.size assert p.size == thresholds.size + 1
def test_precision_recall_curve_toydata(): with np.errstate(all="raise"): # Binary classification y_true = [0, 1] y_score = [0, 1] p, r, _ = precision_recall_curve(y_true, y_score) auc_prc = average_precision_score(y_true, y_score) assert_array_almost_equal(p, [0.5, 1, 1]) assert_array_almost_equal(r, [1, 1, 0]) assert_almost_equal(auc_prc, 1.0)
y_true = [0, 1] y_score = [1, 0] p, r, _ = precision_recall_curve(y_true, y_score) auc_prc = average_precision_score(y_true, y_score) assert_array_almost_equal(p, [0.5, 0.0, 1.0]) assert_array_almost_equal(r, [1.0, 0.0, 0.0]) # Here we are doing a terrible prediction: we are always getting # it wrong, hence the average_precision_score is the accuracy at # chance: 50% assert_almost_equal(auc_prc, 0.5)
y_true = [1, 0] y_score = [1, 1] p, r, _ = precision_recall_curve(y_true, y_score) auc_prc = average_precision_score(y_true, y_score) assert_array_almost_equal(p, [0.5, 1]) assert_array_almost_equal(r, [1.0, 0]) assert_almost_equal(auc_prc, 0.5)
y_true = [1, 0] y_score = [1, 0] p, r, _ = precision_recall_curve(y_true, y_score) auc_prc = average_precision_score(y_true, y_score) assert_array_almost_equal(p, [0.5, 1, 1]) assert_array_almost_equal(r, [1, 1, 0]) assert_almost_equal(auc_prc, 1.0)
y_true = [1, 0] y_score = [0.5, 0.5] p, r, _ = precision_recall_curve(y_true, y_score) auc_prc = average_precision_score(y_true, y_score) assert_array_almost_equal(p, [0.5, 1]) assert_array_almost_equal(r, [1, 0.0]) assert_almost_equal(auc_prc, 0.5)
y_true = [0, 0] y_score = [0.25, 0.75] with pytest.warns(UserWarning, match="No positive class found in y_true"): p, r, _ = precision_recall_curve(y_true, y_score) with pytest.warns(UserWarning, match="No positive class found in y_true"): auc_prc = average_precision_score(y_true, y_score) assert_allclose(p, [0, 0, 1]) assert_allclose(r, [1, 1, 0]) assert_allclose(auc_prc, 0)
y_true = [1, 1] y_score = [0.25, 0.75] p, r, _ = precision_recall_curve(y_true, y_score) assert_almost_equal(average_precision_score(y_true, y_score), 1.0) assert_array_almost_equal(p, [1.0, 1.0, 1.0]) assert_array_almost_equal(r, [1, 0.5, 0.0])
# Multi-label classification task y_true = np.array([[0, 1], [0, 1]]) y_score = np.array([[0, 1], [0, 1]]) with pytest.warns(UserWarning, match="No positive class found in y_true"): assert_allclose( average_precision_score(y_true, y_score, average="macro"), 0.5 ) with pytest.warns(UserWarning, match="No positive class found in y_true"): assert_allclose( average_precision_score(y_true, y_score, average="weighted"), 1.0 ) assert_allclose( average_precision_score(y_true, y_score, average="samples"), 1.0 ) assert_allclose(average_precision_score(y_true, y_score, average="micro"), 1.0)
y_true = np.array([[0, 1], [0, 1]]) y_score = np.array([[0, 1], [1, 0]]) with pytest.warns(UserWarning, match="No positive class found in y_true"): assert_allclose( average_precision_score(y_true, y_score, average="macro"), 0.5 ) with pytest.warns(UserWarning, match="No positive class found in y_true"): assert_allclose( average_precision_score(y_true, y_score, average="weighted"), 1.0 ) assert_allclose( average_precision_score(y_true, y_score, average="samples"), 0.75 ) assert_allclose(average_precision_score(y_true, y_score, average="micro"), 0.5)
y_true = np.array([[1, 0], [0, 1]]) y_score = np.array([[0, 1], [1, 0]]) assert_almost_equal( average_precision_score(y_true, y_score, average="macro"), 0.5 ) assert_almost_equal( average_precision_score(y_true, y_score, average="weighted"), 0.5 ) assert_almost_equal( average_precision_score(y_true, y_score, average="samples"), 0.5 ) assert_almost_equal( average_precision_score(y_true, y_score, average="micro"), 0.5 )
y_true = np.array([[0, 0], [0, 0]]) y_score = np.array([[0, 1], [0, 1]]) with pytest.warns(UserWarning, match="No positive class found in y_true"): assert_allclose( average_precision_score(y_true, y_score, average="macro"), 0.0 ) assert_allclose( average_precision_score(y_true, y_score, average="weighted"), 0.0 ) with pytest.warns(UserWarning, match="No positive class found in y_true"): assert_allclose( average_precision_score(y_true, y_score, average="samples"), 0.0 ) with pytest.warns(UserWarning, match="No positive class found in y_true"): assert_allclose( average_precision_score(y_true, y_score, average="micro"), 0.0 )
y_true = np.array([[1, 1], [1, 1]]) y_score = np.array([[0, 1], [0, 1]]) assert_allclose(average_precision_score(y_true, y_score, average="macro"), 1.0) assert_allclose( average_precision_score(y_true, y_score, average="weighted"), 1.0 ) assert_allclose( average_precision_score(y_true, y_score, average="samples"), 1.0 ) assert_allclose(average_precision_score(y_true, y_score, average="micro"), 1.0)
y_true = np.array([[1, 0], [0, 1]]) y_score = np.array([[0.5, 0.5], [0.5, 0.5]]) assert_almost_equal( average_precision_score(y_true, y_score, average="macro"), 0.5 ) assert_almost_equal( average_precision_score(y_true, y_score, average="weighted"), 0.5 ) assert_almost_equal( average_precision_score(y_true, y_score, average="samples"), 0.5 ) assert_almost_equal( average_precision_score(y_true, y_score, average="micro"), 0.5 )
with np.errstate(all="ignore"): # if one class is never present weighted should not be NaN y_true = np.array([[0, 0], [0, 1]]) y_score = np.array([[0, 0], [0, 1]]) with pytest.warns(UserWarning, match="No positive class found in y_true"): assert_allclose( average_precision_score(y_true, y_score, average="weighted"), 1 )
def test_average_precision_constant_values(): # Check the average_precision_score of a constant predictor is # the TPR
# Generate a dataset with 25% of positives y_true = np.zeros(100, dtype=int) y_true[::4] = 1 # And a constant score y_score = np.ones(100) # The precision is then the fraction of positive whatever the recall # is, as there is only one threshold: assert average_precision_score(y_true, y_score) == 0.25
def test_average_precision_score_pos_label_errors(): # Raise an error when pos_label is not in binary y_true y_true = np.array([0, 1]) y_pred = np.array([0, 1]) err_msg = r"pos_label=2 is not a valid label. It should be one of \[0, 1\]" with pytest.raises(ValueError, match=err_msg): average_precision_score(y_true, y_pred, pos_label=2) # Raise an error for multilabel-indicator y_true with # pos_label other than 1 y_true = np.array([[1, 0], [0, 1], [0, 1], [1, 0]]) y_pred = np.array([[0.9, 0.1], [0.1, 0.9], [0.8, 0.2], [0.2, 0.8]]) err_msg = ( "Parameter pos_label is fixed to 1 for multilabel-indicator y_true. " "Do not set pos_label or set pos_label to 1." ) with pytest.raises(ValueError, match=err_msg): average_precision_score(y_true, y_pred, pos_label=0)
def test_score_scale_invariance(): # Test that average_precision_score and roc_auc_score are invariant by # the scaling or shifting of probabilities # This test was expanded (added scaled_down) in response to github # issue #3864 (and others), where overly aggressive rounding was causing # problems for users with very small y_score values y_true, _, y_score = make_prediction(binary=True)
roc_auc = roc_auc_score(y_true, y_score) roc_auc_scaled_up = roc_auc_score(y_true, 100 * y_score) roc_auc_scaled_down = roc_auc_score(y_true, 1e-6 * y_score) roc_auc_shifted = roc_auc_score(y_true, y_score - 10) assert roc_auc == roc_auc_scaled_up assert roc_auc == roc_auc_scaled_down assert roc_auc == roc_auc_shifted
pr_auc = average_precision_score(y_true, y_score) pr_auc_scaled_up = average_precision_score(y_true, 100 * y_score) pr_auc_scaled_down = average_precision_score(y_true, 1e-6 * y_score) pr_auc_shifted = average_precision_score(y_true, y_score - 10) assert pr_auc == pr_auc_scaled_up assert pr_auc == pr_auc_scaled_down assert pr_auc == pr_auc_shifted
@pytest.mark.parametrize( "y_true,y_score,expected_fpr,expected_fnr", [ ([0, 0, 1], [0, 0.5, 1], [0], [0]), ([0, 0, 1], [0, 0.25, 0.5], [0], [0]), ([0, 0, 1], [0.5, 0.75, 1], [0], [0]), ([0, 0, 1], [0.25, 0.5, 0.75], [0], [0]), ([0, 1, 0], [0, 0.5, 1], [0.5], [0]), ([0, 1, 0], [0, 0.25, 0.5], [0.5], [0]), ([0, 1, 0], [0.5, 0.75, 1], [0.5], [0]), ([0, 1, 0], [0.25, 0.5, 0.75], [0.5], [0]), ([0, 1, 1], [0, 0.5, 1], [0.0], [0]), ([0, 1, 1], [0, 0.25, 0.5], [0], [0]), ([0, 1, 1], [0.5, 0.75, 1], [0], [0]), ([0, 1, 1], [0.25, 0.5, 0.75], [0], [0]), ([1, 0, 0], [0, 0.5, 1], [1, 1, 0.5], [0, 1, 1]), ([1, 0, 0], [0, 0.25, 0.5], [1, 1, 0.5], [0, 1, 1]), ([1, 0, 0], [0.5, 0.75, 1], [1, 1, 0.5], [0, 1, 1]), ([1, 0, 0], [0.25, 0.5, 0.75], [1, 1, 0.5], [0, 1, 1]), ([1, 0, 1], [0, 0.5, 1], [1, 1, 0], [0, 0.5, 0.5]), ([1, 0, 1], [0, 0.25, 0.5], [1, 1, 0], [0, 0.5, 0.5]), ([1, 0, 1], [0.5, 0.75, 1], [1, 1, 0], [0, 0.5, 0.5]), ([1, 0, 1], [0.25, 0.5, 0.75], [1, 1, 0], [0, 0.5, 0.5]), ],)def test_det_curve_toydata(y_true, y_score, expected_fpr, expected_fnr): # Check on a batch of small examples. fpr, fnr, _ = det_curve(y_true, y_score)
assert_allclose(fpr, expected_fpr) assert_allclose(fnr, expected_fnr)
@pytest.mark.parametrize( "y_true,y_score,expected_fpr,expected_fnr", [ ([1, 0], [0.5, 0.5], [1], [0]), ([0, 1], [0.5, 0.5], [1], [0]), ([0, 0, 1], [0.25, 0.5, 0.5], [0.5], [0]), ([0, 1, 0], [0.25, 0.5, 0.5], [0.5], [0]), ([0, 1, 1], [0.25, 0.5, 0.5], [0], [0]), ([1, 0, 0], [0.25, 0.5, 0.5], [1], [0]), ([1, 0, 1], [0.25, 0.5, 0.5], [1], [0]), ([1, 1, 0], [0.25, 0.5, 0.5], [1], [0]), ],)def test_det_curve_tie_handling(y_true, y_score, expected_fpr, expected_fnr): fpr, fnr, _ = det_curve(y_true, y_score)
assert_allclose(fpr, expected_fpr) assert_allclose(fnr, expected_fnr)
def test_det_curve_sanity_check(): # Exactly duplicated inputs yield the same result. assert_allclose( det_curve([0, 0, 1], [0, 0.5, 1]), det_curve([0, 0, 0, 0, 1, 1], [0, 0, 0.5, 0.5, 1, 1]), )
@pytest.mark.parametrize("y_score", [(0), (0.25), (0.5), (0.75), (1)])def test_det_curve_constant_scores(y_score): fpr, fnr, threshold = det_curve( y_true=[0, 1, 0, 1, 0, 1], y_score=np.full(6, y_score) )
assert_allclose(fpr, [1]) assert_allclose(fnr, [0]) assert_allclose(threshold, [y_score])
@pytest.mark.parametrize( "y_true", [ ([0, 0, 0, 0, 0, 1]), ([0, 0, 0, 0, 1, 1]), ([0, 0, 0, 1, 1, 1]), ([0, 0, 1, 1, 1, 1]), ([0, 1, 1, 1, 1, 1]), ],)def test_det_curve_perfect_scores(y_true): fpr, fnr, _ = det_curve(y_true=y_true, y_score=y_true)
assert_allclose(fpr, [0]) assert_allclose(fnr, [0])
@pytest.mark.parametrize( "y_true, y_pred, err_msg", [ ([0, 1], [0, 0.5, 1], "inconsistent numbers of samples"), ([0, 1, 1], [0, 0.5], "inconsistent numbers of samples"), ([0, 0, 0], [0, 0.5, 1], "Only one class present in y_true"), ([1, 1, 1], [0, 0.5, 1], "Only one class present in y_true"), ( ["cancer", "cancer", "not cancer"], [0.2, 0.3, 0.8], "pos_label is not specified", ), ],)def test_det_curve_bad_input(y_true, y_pred, err_msg): # input variables with inconsistent numbers of samples with pytest.raises(ValueError, match=err_msg): det_curve(y_true, y_pred)
def test_det_curve_pos_label(): y_true = ["cancer"] * 3 + ["not cancer"] * 7 y_pred_pos_not_cancer = np.array([0.1, 0.4, 0.6, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.9]) y_pred_pos_cancer = 1 - y_pred_pos_not_cancer
fpr_pos_cancer, fnr_pos_cancer, th_pos_cancer = det_curve( y_true, y_pred_pos_cancer, pos_label="cancer", ) fpr_pos_not_cancer, fnr_pos_not_cancer, th_pos_not_cancer = det_curve( y_true, y_pred_pos_not_cancer, pos_label="not cancer", )
# check that the first threshold will change depending which label we # consider positive assert th_pos_cancer[0] == pytest.approx(0.4) assert th_pos_not_cancer[0] == pytest.approx(0.2)
# check for the symmetry of the fpr and fnr assert_allclose(fpr_pos_cancer, fnr_pos_not_cancer[::-1]) assert_allclose(fnr_pos_cancer, fpr_pos_not_cancer[::-1])
def check_lrap_toy(lrap_score): # Check on several small example that it works assert_almost_equal(lrap_score([[0, 1]], [[0.25, 0.75]]), 1) assert_almost_equal(lrap_score([[0, 1]], [[0.75, 0.25]]), 1 / 2) assert_almost_equal(lrap_score([[1, 1]], [[0.75, 0.25]]), 1)
assert_almost_equal(lrap_score([[0, 0, 1]], [[0.25, 0.5, 0.75]]), 1) assert_almost_equal(lrap_score([[0, 1, 0]], [[0.25, 0.5, 0.75]]), 1 / 2) assert_almost_equal(lrap_score([[0, 1, 1]], [[0.25, 0.5, 0.75]]), 1) assert_almost_equal(lrap_score([[1, 0, 0]], [[0.25, 0.5, 0.75]]), 1 / 3) assert_almost_equal( lrap_score([[1, 0, 1]], [[0.25, 0.5, 0.75]]), (2 / 3 + 1 / 1) / 2 ) assert_almost_equal( lrap_score([[1, 1, 0]], [[0.25, 0.5, 0.75]]), (2 / 3 + 1 / 2) / 2 )
assert_almost_equal(lrap_score([[0, 0, 1]], [[0.75, 0.5, 0.25]]), 1 / 3) assert_almost_equal(lrap_score([[0, 1, 0]], [[0.75, 0.5, 0.25]]), 1 / 2) assert_almost_equal( lrap_score([[0, 1, 1]], [[0.75, 0.5, 0.25]]), (1 / 2 + 2 / 3) / 2 ) assert_almost_equal(lrap_score([[1, 0, 0]], [[0.75, 0.5, 0.25]]), 1) assert_almost_equal(lrap_score([[1, 0, 1]], [[0.75, 0.5, 0.25]]), (1 + 2 / 3) / 2) assert_almost_equal(lrap_score([[1, 1, 0]], [[0.75, 0.5, 0.25]]), 1) assert_almost_equal(lrap_score([[1, 1, 1]], [[0.75, 0.5, 0.25]]), 1)
assert_almost_equal(lrap_score([[0, 0, 1]], [[0.5, 0.75, 0.25]]), 1 / 3) assert_almost_equal(lrap_score([[0, 1, 0]], [[0.5, 0.75, 0.25]]), 1) assert_almost_equal(lrap_score([[0, 1, 1]], [[0.5, 0.75, 0.25]]), (1 + 2 / 3) / 2) assert_almost_equal(lrap_score([[1, 0, 0]], [[0.5, 0.75, 0.25]]), 1 / 2) assert_almost_equal( lrap_score([[1, 0, 1]], [[0.5, 0.75, 0.25]]), (1 / 2 + 2 / 3) / 2 ) assert_almost_equal(lrap_score([[1, 1, 0]], [[0.5, 0.75, 0.25]]), 1) assert_almost_equal(lrap_score([[1, 1, 1]], [[0.5, 0.75, 0.25]]), 1)
# Tie handling assert_almost_equal(lrap_score([[1, 0]], [[0.5, 0.5]]), 0.5) assert_almost_equal(lrap_score([[0, 1]], [[0.5, 0.5]]), 0.5) assert_almost_equal(lrap_score([[1, 1]], [[0.5, 0.5]]), 1)
assert_almost_equal(lrap_score([[0, 0, 1]], [[0.25, 0.5, 0.5]]), 0.5) assert_almost_equal(lrap_score([[0, 1, 0]], [[0.25, 0.5, 0.5]]), 0.5) assert_almost_equal(lrap_score([[0, 1, 1]], [[0.25, 0.5, 0.5]]), 1) assert_almost_equal(lrap_score([[1, 0, 0]], [[0.25, 0.5, 0.5]]), 1 / 3) assert_almost_equal( lrap_score([[1, 0, 1]], [[0.25, 0.5, 0.5]]), (2 / 3 + 1 / 2) / 2 ) assert_almost_equal( lrap_score([[1, 1, 0]], [[0.25, 0.5, 0.5]]), (2 / 3 + 1 / 2) / 2 ) assert_almost_equal(lrap_score([[1, 1, 1]], [[0.25, 0.5, 0.5]]), 1)
assert_almost_equal(lrap_score([[1, 1, 0]], [[0.5, 0.5, 0.5]]), 2 / 3)
assert_almost_equal(lrap_score([[1, 1, 1, 0]], [[0.5, 0.5, 0.5, 0.5]]), 3 / 4)
def check_zero_or_all_relevant_labels(lrap_score): random_state = check_random_state(0)
for n_labels in range(2, 5): y_score = random_state.uniform(size=(1, n_labels)) y_score_ties = np.zeros_like(y_score)
# No relevant labels y_true = np.zeros((1, n_labels)) assert lrap_score(y_true, y_score) == 1.0 assert lrap_score(y_true, y_score_ties) == 1.0
# Only relevant labels y_true = np.ones((1, n_labels)) assert lrap_score(y_true, y_score) == 1.0 assert lrap_score(y_true, y_score_ties) == 1.0
# Degenerate case: only one label assert_almost_equal( lrap_score([[1], [0], [1], [0]], [[0.5], [0.5], [0.5], [0.5]]), 1.0 )
def check_lrap_error_raised(lrap_score): # Raise value error if not appropriate format with pytest.raises(ValueError): lrap_score([0, 1, 0], [0.25, 0.3, 0.2]) with pytest.raises(ValueError): lrap_score([0, 1, 2], [[0.25, 0.75, 0.0], [0.7, 0.3, 0.0], [0.8, 0.2, 0.0]]) with pytest.raises(ValueError): lrap_score( [(0), (1), (2)], [[0.25, 0.75, 0.0], [0.7, 0.3, 0.0], [0.8, 0.2, 0.0]] )
# Check that y_true.shape != y_score.shape raise the proper exception with pytest.raises(ValueError): lrap_score([[0, 1], [0, 1]], [0, 1]) with pytest.raises(ValueError): lrap_score([[0, 1], [0, 1]], [[0, 1]]) with pytest.raises(ValueError): lrap_score([[0, 1], [0, 1]], [[0], [1]]) with pytest.raises(ValueError): lrap_score([[0, 1]], [[0, 1], [0, 1]]) with pytest.raises(ValueError): lrap_score([[0], [1]], [[0, 1], [0, 1]]) with pytest.raises(ValueError): lrap_score([[0, 1], [0, 1]], [[0], [1]])
def check_lrap_only_ties(lrap_score): # Check tie handling in score # Basic check with only ties and increasing label space for n_labels in range(2, 10): y_score = np.ones((1, n_labels))
# Check for growing number of consecutive relevant for n_relevant in range(1, n_labels): # Check for a bunch of positions for pos in range(n_labels - n_relevant): y_true = np.zeros((1, n_labels)) y_true[0, pos : pos + n_relevant] = 1 assert_almost_equal(lrap_score(y_true, y_score), n_relevant / n_labels)
def check_lrap_without_tie_and_increasing_score(lrap_score): # Check that Label ranking average precision works for various # Basic check with increasing label space size and decreasing score for n_labels in range(2, 10): y_score = n_labels - (np.arange(n_labels).reshape((1, n_labels)) + 1)
# First and last y_true = np.zeros((1, n_labels)) y_true[0, 0] = 1 y_true[0, -1] = 1 assert_almost_equal(lrap_score(y_true, y_score), (2 / n_labels + 1) / 2)
# Check for growing number of consecutive relevant label for n_relevant in range(1, n_labels): # Check for a bunch of position for pos in range(n_labels - n_relevant): y_true = np.zeros((1, n_labels)) y_true[0, pos : pos + n_relevant] = 1 assert_almost_equal( lrap_score(y_true, y_score), sum( (r + 1) / ((pos + r + 1) * n_relevant) for r in range(n_relevant) ), )
def _my_lrap(y_true, y_score): """Simple implementation of label ranking average precision""" check_consistent_length(y_true, y_score) y_true = check_array(y_true) y_score = check_array(y_score) n_samples, n_labels = y_true.shape score = np.empty((n_samples,)) for i in range(n_samples): # The best rank correspond to 1. Rank higher than 1 are worse. # The best inverse ranking correspond to n_labels. unique_rank, inv_rank = np.unique(y_score[i], return_inverse=True) n_ranks = unique_rank.size rank = n_ranks - inv_rank
# Rank need to be corrected to take into account ties # ex: rank 1 ex aequo means that both label are rank 2. corr_rank = np.bincount(rank, minlength=n_ranks + 1).cumsum() rank = corr_rank[rank]
relevant = y_true[i].nonzero()[0] if relevant.size == 0 or relevant.size == n_labels: score[i] = 1 continue
score[i] = 0.0 for label in relevant: # Let's count the number of relevant label with better rank # (smaller rank). n_ranked_above = sum(rank[r] <= rank[label] for r in relevant)
# Weight by the rank of the actual label score[i] += n_ranked_above / rank[label]
score[i] /= relevant.size
return score.mean()
def check_alternative_lrap_implementation( lrap_score, n_classes=5, n_samples=20, random_state=0): _, y_true = make_multilabel_classification( n_features=1, allow_unlabeled=False, random_state=random_state, n_classes=n_classes, n_samples=n_samples, )
# Score with ties y_score = _sparse_random_matrix( n_components=y_true.shape[0], n_features=y_true.shape[1], random_state=random_state, )
if hasattr(y_score, "toarray"): y_score = y_score.toarray() score_lrap = label_ranking_average_precision_score(y_true, y_score) score_my_lrap = _my_lrap(y_true, y_score) assert_almost_equal(score_lrap, score_my_lrap)
# Uniform score random_state = check_random_state(random_state) y_score = random_state.uniform(size=(n_samples, n_classes)) score_lrap = label_ranking_average_precision_score(y_true, y_score) score_my_lrap = _my_lrap(y_true, y_score) assert_almost_equal(score_lrap, score_my_lrap)
@pytest.mark.parametrize( "check", ( check_lrap_toy, check_lrap_without_tie_and_increasing_score, check_lrap_only_ties, check_zero_or_all_relevant_labels, ),)@pytest.mark.parametrize("func", (label_ranking_average_precision_score, _my_lrap))def test_label_ranking_avp(check, func): check(func)
def test_lrap_error_raised(): check_lrap_error_raised(label_ranking_average_precision_score)
@pytest.mark.parametrize("n_samples", (1, 2, 8, 20))@pytest.mark.parametrize("n_classes", (2, 5, 10))@pytest.mark.parametrize("random_state", range(1))def test_alternative_lrap_implementation(n_samples, n_classes, random_state):
check_alternative_lrap_implementation( label_ranking_average_precision_score, n_classes, n_samples, random_state )
def test_lrap_sample_weighting_zero_labels(): # Degenerate sample labeling (e.g., zero labels for a sample) is a valid # special case for lrap (the sample is considered to achieve perfect # precision), but this case is not tested in test_common. # For these test samples, the APs are 0.5, 0.75, and 1.0 (default for zero # labels). y_true = np.array([[1, 0, 0, 0], [1, 0, 0, 1], [0, 0, 0, 0]], dtype=bool) y_score = np.array( [[0.3, 0.4, 0.2, 0.1], [0.1, 0.2, 0.3, 0.4], [0.4, 0.3, 0.2, 0.1]] ) samplewise_lraps = np.array([0.5, 0.75, 1.0]) sample_weight = np.array([1.0, 1.0, 0.0])
assert_almost_equal( label_ranking_average_precision_score( y_true, y_score, sample_weight=sample_weight ), np.sum(sample_weight * samplewise_lraps) / np.sum(sample_weight), )
def test_coverage_error(): # Toy case assert_almost_equal(coverage_error([[0, 1]], [[0.25, 0.75]]), 1) assert_almost_equal(coverage_error([[0, 1]], [[0.75, 0.25]]), 2) assert_almost_equal(coverage_error([[1, 1]], [[0.75, 0.25]]), 2) assert_almost_equal(coverage_error([[0, 0]], [[0.75, 0.25]]), 0)
assert_almost_equal(coverage_error([[0, 0, 0]], [[0.25, 0.5, 0.75]]), 0) assert_almost_equal(coverage_error([[0, 0, 1]], [[0.25, 0.5, 0.75]]), 1) assert_almost_equal(coverage_error([[0, 1, 0]], [[0.25, 0.5, 0.75]]), 2) assert_almost_equal(coverage_error([[0, 1, 1]], [[0.25, 0.5, 0.75]]), 2) assert_almost_equal(coverage_error([[1, 0, 0]], [[0.25, 0.5, 0.75]]), 3) assert_almost_equal(coverage_error([[1, 0, 1]], [[0.25, 0.5, 0.75]]), 3) assert_almost_equal(coverage_error([[1, 1, 0]], [[0.25, 0.5, 0.75]]), 3) assert_almost_equal(coverage_error([[1, 1, 1]], [[0.25, 0.5, 0.75]]), 3)
assert_almost_equal(coverage_error([[0, 0, 0]], [[0.75, 0.5, 0.25]]), 0) assert_almost_equal(coverage_error([[0, 0, 1]], [[0.75, 0.5, 0.25]]), 3) assert_almost_equal(coverage_error([[0, 1, 0]], [[0.75, 0.5, 0.25]]), 2) assert_almost_equal(coverage_error([[0, 1, 1]], [[0.75, 0.5, 0.25]]), 3) assert_almost_equal(coverage_error([[1, 0, 0]], [[0.75, 0.5, 0.25]]), 1) assert_almost_equal(coverage_error([[1, 0, 1]], [[0.75, 0.5, 0.25]]), 3) assert_almost_equal(coverage_error([[1, 1, 0]], [[0.75, 0.5, 0.25]]), 2) assert_almost_equal(coverage_error([[1, 1, 1]], [[0.75, 0.5, 0.25]]), 3)
assert_almost_equal(coverage_error([[0, 0, 0]], [[0.5, 0.75, 0.25]]), 0) assert_almost_equal(coverage_error([[0, 0, 1]], [[0.5, 0.75, 0.25]]), 3) assert_almost_equal(coverage_error([[0, 1, 0]], [[0.5, 0.75, 0.25]]), 1) assert_almost_equal(coverage_error([[0, 1, 1]], [[0.5, 0.75, 0.25]]), 3) assert_almost_equal(coverage_error([[1, 0, 0]], [[0.5, 0.75, 0.25]]), 2) assert_almost_equal(coverage_error([[1, 0, 1]], [[0.5, 0.75, 0.25]]), 3) assert_almost_equal(coverage_error([[1, 1, 0]], [[0.5, 0.75, 0.25]]), 2) assert_almost_equal(coverage_error([[1, 1, 1]], [[0.5, 0.75, 0.25]]), 3)
# Non trivial case assert_almost_equal( coverage_error([[0, 1, 0], [1, 1, 0]], [[0.1, 10.0, -3], [0, 1, 3]]), (1 + 3) / 2.0, )
assert_almost_equal( coverage_error( [[0, 1, 0], [1, 1, 0], [0, 1, 1]], [[0.1, 10, -3], [0, 1, 3], [0, 2, 0]] ), (1 + 3 + 3) / 3.0, )
assert_almost_equal( coverage_error( [[0, 1, 0], [1, 1, 0], [0, 1, 1]], [[0.1, 10, -3], [3, 1, 3], [0, 2, 0]] ), (1 + 3 + 3) / 3.0, )
def test_coverage_tie_handling(): assert_almost_equal(coverage_error([[0, 0]], [[0.5, 0.5]]), 0) assert_almost_equal(coverage_error([[1, 0]], [[0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[0, 1]], [[0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[1, 1]], [[0.5, 0.5]]), 2)
assert_almost_equal(coverage_error([[0, 0, 0]], [[0.25, 0.5, 0.5]]), 0) assert_almost_equal(coverage_error([[0, 0, 1]], [[0.25, 0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[0, 1, 0]], [[0.25, 0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[0, 1, 1]], [[0.25, 0.5, 0.5]]), 2) assert_almost_equal(coverage_error([[1, 0, 0]], [[0.25, 0.5, 0.5]]), 3) assert_almost_equal(coverage_error([[1, 0, 1]], [[0.25, 0.5, 0.5]]), 3) assert_almost_equal(coverage_error([[1, 1, 0]], [[0.25, 0.5, 0.5]]), 3) assert_almost_equal(coverage_error([[1, 1, 1]], [[0.25, 0.5, 0.5]]), 3)
@pytest.mark.parametrize( "y_true, y_score", [ ([1, 0, 1], [0.25, 0.5, 0.5]), ([1, 0, 1], [[0.25, 0.5, 0.5]]), ([[1, 0, 1]], [0.25, 0.5, 0.5]), ],)def test_coverage_1d_error_message(y_true, y_score): # Non-regression test for: # https://github.com/scikit-learn/scikit-learn/issues/23368 with pytest.raises(ValueError, match=r"Expected 2D array, got 1D array instead"): coverage_error(y_true, y_score)
def test_label_ranking_loss(): assert_almost_equal(label_ranking_loss([[0, 1]], [[0.25, 0.75]]), 0) assert_almost_equal(label_ranking_loss([[0, 1]], [[0.75, 0.25]]), 1)
assert_almost_equal(label_ranking_loss([[0, 0, 1]], [[0.25, 0.5, 0.75]]), 0) assert_almost_equal(label_ranking_loss([[0, 1, 0]], [[0.25, 0.5, 0.75]]), 1 / 2) assert_almost_equal(label_ranking_loss([[0, 1, 1]], [[0.25, 0.5, 0.75]]), 0) assert_almost_equal(label_ranking_loss([[1, 0, 0]], [[0.25, 0.5, 0.75]]), 2 / 2) assert_almost_equal(label_ranking_loss([[1, 0, 1]], [[0.25, 0.5, 0.75]]), 1 / 2) assert_almost_equal(label_ranking_loss([[1, 1, 0]], [[0.25, 0.5, 0.75]]), 2 / 2)
# Undefined metrics - the ranking doesn't matter assert_almost_equal(label_ranking_loss([[0, 0]], [[0.75, 0.25]]), 0) assert_almost_equal(label_ranking_loss([[1, 1]], [[0.75, 0.25]]), 0) assert_almost_equal(label_ranking_loss([[0, 0]], [[0.5, 0.5]]), 0) assert_almost_equal(label_ranking_loss([[1, 1]], [[0.5, 0.5]]), 0)
assert_almost_equal(label_ranking_loss([[0, 0, 0]], [[0.5, 0.75, 0.25]]), 0) assert_almost_equal(label_ranking_loss([[1, 1, 1]], [[0.5, 0.75, 0.25]]), 0) assert_almost_equal(label_ranking_loss([[0, 0, 0]], [[0.25, 0.5, 0.5]]), 0) assert_almost_equal(label_ranking_loss([[1, 1, 1]], [[0.25, 0.5, 0.5]]), 0)
# Non trivial case assert_almost_equal( label_ranking_loss([[0, 1, 0], [1, 1, 0]], [[0.1, 10.0, -3], [0, 1, 3]]), (0 + 2 / 2) / 2.0, )
assert_almost_equal( label_ranking_loss( [[0, 1, 0], [1, 1, 0], [0, 1, 1]], [[0.1, 10, -3], [0, 1, 3], [0, 2, 0]] ), (0 + 2 / 2 + 1 / 2) / 3.0, )
assert_almost_equal( label_ranking_loss( [[0, 1, 0], [1, 1, 0], [0, 1, 1]], [[0.1, 10, -3], [3, 1, 3], [0, 2, 0]] ), (0 + 2 / 2 + 1 / 2) / 3.0, )
# Sparse csr matrices assert_almost_equal( label_ranking_loss( csr_matrix(np.array([[0, 1, 0], [1, 1, 0]])), [[0.1, 10, -3], [3, 1, 3]] ), (0 + 2 / 2) / 2.0, )
def test_ranking_appropriate_input_shape(): # Check that y_true.shape != y_score.shape raise the proper exception with pytest.raises(ValueError): label_ranking_loss([[0, 1], [0, 1]], [0, 1]) with pytest.raises(ValueError): label_ranking_loss([[0, 1], [0, 1]], [[0, 1]]) with pytest.raises(ValueError): label_ranking_loss([[0, 1], [0, 1]], [[0], [1]]) with pytest.raises(ValueError): label_ranking_loss([[0, 1]], [[0, 1], [0, 1]]) with pytest.raises(ValueError): label_ranking_loss([[0], [1]], [[0, 1], [0, 1]]) with pytest.raises(ValueError): label_ranking_loss([[0, 1], [0, 1]], [[0], [1]])
def test_ranking_loss_ties_handling(): # Tie handling assert_almost_equal(label_ranking_loss([[1, 0]], [[0.5, 0.5]]), 1) assert_almost_equal(label_ranking_loss([[0, 1]], [[0.5, 0.5]]), 1) assert_almost_equal(label_ranking_loss([[0, 0, 1]], [[0.25, 0.5, 0.5]]), 1 / 2) assert_almost_equal(label_ranking_loss([[0, 1, 0]], [[0.25, 0.5, 0.5]]), 1 / 2) assert_almost_equal(label_ranking_loss([[0, 1, 1]], [[0.25, 0.5, 0.5]]), 0) assert_almost_equal(label_ranking_loss([[1, 0, 0]], [[0.25, 0.5, 0.5]]), 1) assert_almost_equal(label_ranking_loss([[1, 0, 1]], [[0.25, 0.5, 0.5]]), 1) assert_almost_equal(label_ranking_loss([[1, 1, 0]], [[0.25, 0.5, 0.5]]), 1)
def test_dcg_score(): _, y_true = make_multilabel_classification(random_state=0, n_classes=10) y_score = -y_true + 1 _test_dcg_score_for(y_true, y_score) y_true, y_score = np.random.RandomState(0).random_sample((2, 100, 10)) _test_dcg_score_for(y_true, y_score)
def _test_dcg_score_for(y_true, y_score): discount = np.log2(np.arange(y_true.shape[1]) + 2) ideal = _dcg_sample_scores(y_true, y_true) score = _dcg_sample_scores(y_true, y_score) assert (score <= ideal).all() assert (_dcg_sample_scores(y_true, y_true, k=5) <= ideal).all() assert ideal.shape == (y_true.shape[0],) assert score.shape == (y_true.shape[0],) assert ideal == pytest.approx((np.sort(y_true)[:, ::-1] / discount).sum(axis=1))
def test_dcg_ties(): y_true = np.asarray([np.arange(5)]) y_score = np.zeros(y_true.shape) dcg = _dcg_sample_scores(y_true, y_score) dcg_ignore_ties = _dcg_sample_scores(y_true, y_score, ignore_ties=True) discounts = 1 / np.log2(np.arange(2, 7)) assert dcg == pytest.approx([discounts.sum() * y_true.mean()]) assert dcg_ignore_ties == pytest.approx([(discounts * y_true[:, ::-1]).sum()]) y_score[0, 3:] = 1 dcg = _dcg_sample_scores(y_true, y_score) dcg_ignore_ties = _dcg_sample_scores(y_true, y_score, ignore_ties=True) assert dcg_ignore_ties == pytest.approx([(discounts * y_true[:, ::-1]).sum()]) assert dcg == pytest.approx( [ discounts[:2].sum() * y_true[0, 3:].mean() + discounts[2:].sum() * y_true[0, :3].mean() ] )
def test_ndcg_ignore_ties_with_k(): a = np.arange(12).reshape((2, 6)) assert ndcg_score(a, a, k=3, ignore_ties=True) == pytest.approx( ndcg_score(a, a, k=3, ignore_ties=True) )
# TODO(1.4): Replace warning w/ ValueErrordef test_ndcg_negative_ndarray_warn(): y_true = np.array([[-0.89, -0.53, -0.47, 0.39, 0.56]]) y_score = np.array([[0.07, 0.31, 0.75, 0.33, 0.27]]) expected_message = ( "ndcg_score should not be used on negative y_true values. ndcg_score will raise" " a ValueError on negative y_true values starting from version 1.4." ) with pytest.warns(FutureWarning, match=expected_message): assert ndcg_score(y_true, y_score) == pytest.approx(396.0329)
def test_ndcg_invariant(): y_true = np.arange(70).reshape(7, 10) y_score = y_true + np.random.RandomState(0).uniform(-0.2, 0.2, size=y_true.shape) ndcg = ndcg_score(y_true, y_score) ndcg_no_ties = ndcg_score(y_true, y_score, ignore_ties=True) assert ndcg == pytest.approx(ndcg_no_ties) assert ndcg == pytest.approx(1.0) y_score += 1000 assert ndcg_score(y_true, y_score) == pytest.approx(1.0)
@pytest.mark.parametrize("ignore_ties", [True, False])def test_ndcg_toy_examples(ignore_ties): y_true = 3 * np.eye(7)[:5] y_score = np.tile(np.arange(6, -1, -1), (5, 1)) y_score_noisy = y_score + np.random.RandomState(0).uniform( -0.2, 0.2, size=y_score.shape ) assert _dcg_sample_scores( y_true, y_score, ignore_ties=ignore_ties ) == pytest.approx(3 / np.log2(np.arange(2, 7))) assert _dcg_sample_scores( y_true, y_score_noisy, ignore_ties=ignore_ties ) == pytest.approx(3 / np.log2(np.arange(2, 7))) assert _ndcg_sample_scores( y_true, y_score, ignore_ties=ignore_ties ) == pytest.approx(1 / np.log2(np.arange(2, 7))) assert _dcg_sample_scores( y_true, y_score, log_base=10, ignore_ties=ignore_ties ) == pytest.approx(3 / np.log10(np.arange(2, 7))) assert ndcg_score(y_true, y_score, ignore_ties=ignore_ties) == pytest.approx( (1 / np.log2(np.arange(2, 7))).mean() ) assert dcg_score(y_true, y_score, ignore_ties=ignore_ties) == pytest.approx( (3 / np.log2(np.arange(2, 7))).mean() ) y_true = 3 * np.ones((5, 7)) expected_dcg_score = (3 / np.log2(np.arange(2, 9))).sum() assert _dcg_sample_scores( y_true, y_score, ignore_ties=ignore_ties ) == pytest.approx(expected_dcg_score * np.ones(5)) assert _ndcg_sample_scores( y_true, y_score, ignore_ties=ignore_ties ) == pytest.approx(np.ones(5)) assert dcg_score(y_true, y_score, ignore_ties=ignore_ties) == pytest.approx( expected_dcg_score ) assert ndcg_score(y_true, y_score, ignore_ties=ignore_ties) == pytest.approx(1.0)
def test_ndcg_score(): _, y_true = make_multilabel_classification(random_state=0, n_classes=10) y_score = -y_true + 1 _test_ndcg_score_for(y_true, y_score) y_true, y_score = np.random.RandomState(0).random_sample((2, 100, 10)) _test_ndcg_score_for(y_true, y_score)
def _test_ndcg_score_for(y_true, y_score): ideal = _ndcg_sample_scores(y_true, y_true) score = _ndcg_sample_scores(y_true, y_score) assert (score <= ideal).all() all_zero = (y_true == 0).all(axis=1) assert ideal[~all_zero] == pytest.approx(np.ones((~all_zero).sum())) assert ideal[all_zero] == pytest.approx(np.zeros(all_zero.sum())) assert score[~all_zero] == pytest.approx( _dcg_sample_scores(y_true, y_score)[~all_zero] / _dcg_sample_scores(y_true, y_true)[~all_zero] ) assert score[all_zero] == pytest.approx(np.zeros(all_zero.sum())) assert ideal.shape == (y_true.shape[0],) assert score.shape == (y_true.shape[0],)
def test_partial_roc_auc_score(): # Check `roc_auc_score` for max_fpr != `None` y_true = np.array([0, 0, 1, 1]) assert roc_auc_score(y_true, y_true, max_fpr=1) == 1 assert roc_auc_score(y_true, y_true, max_fpr=0.001) == 1 with pytest.raises(ValueError): assert roc_auc_score(y_true, y_true, max_fpr=-0.1) with pytest.raises(ValueError): assert roc_auc_score(y_true, y_true, max_fpr=1.1) with pytest.raises(ValueError): assert roc_auc_score(y_true, y_true, max_fpr=0)
y_scores = np.array([0.1, 0, 0.1, 0.01]) roc_auc_with_max_fpr_one = roc_auc_score(y_true, y_scores, max_fpr=1) unconstrained_roc_auc = roc_auc_score(y_true, y_scores) assert roc_auc_with_max_fpr_one == unconstrained_roc_auc assert roc_auc_score(y_true, y_scores, max_fpr=0.3) == 0.5
y_true, y_pred, _ = make_prediction(binary=True) for max_fpr in np.linspace(1e-4, 1, 5): assert_almost_equal( roc_auc_score(y_true, y_pred, max_fpr=max_fpr), _partial_roc_auc_score(y_true, y_pred, max_fpr), )
@pytest.mark.parametrize( "y_true, k, true_score", [ ([0, 1, 2, 3], 1, 0.25), ([0, 1, 2, 3], 2, 0.5), ([0, 1, 2, 3], 3, 0.75), ],)def test_top_k_accuracy_score(y_true, k, true_score): y_score = np.array( [ [0.4, 0.3, 0.2, 0.1], [0.1, 0.3, 0.4, 0.2], [0.4, 0.1, 0.2, 0.3], [0.3, 0.2, 0.4, 0.1], ] ) score = top_k_accuracy_score(y_true, y_score, k=k) assert score == pytest.approx(true_score)
@pytest.mark.parametrize( "y_score, k, true_score", [ (np.array([-1, -1, 1, 1]), 1, 1), (np.array([-1, 1, -1, 1]), 1, 0.5), (np.array([-1, 1, -1, 1]), 2, 1), (np.array([0.2, 0.2, 0.7, 0.7]), 1, 1), (np.array([0.2, 0.7, 0.2, 0.7]), 1, 0.5), (np.array([0.2, 0.7, 0.2, 0.7]), 2, 1), ],)def test_top_k_accuracy_score_binary(y_score, k, true_score): y_true = [0, 0, 1, 1]
threshold = 0.5 if y_score.min() >= 0 and y_score.max() <= 1 else 0 y_pred = (y_score > threshold).astype(np.int64) if k == 1 else y_true
score = top_k_accuracy_score(y_true, y_score, k=k) score_acc = accuracy_score(y_true, y_pred)
assert score == score_acc == pytest.approx(true_score)
@pytest.mark.parametrize( "y_true, true_score, labels", [ (np.array([0, 1, 1, 2]), 0.75, [0, 1, 2, 3]), (np.array([0, 1, 1, 1]), 0.5, [0, 1, 2, 3]), (np.array([1, 1, 1, 1]), 0.5, [0, 1, 2, 3]), (np.array(["a", "e", "e", "a"]), 0.75, ["a", "b", "d", "e"]), ],)@pytest.mark.parametrize("labels_as_ndarray", [True, False])def test_top_k_accuracy_score_multiclass_with_labels( y_true, true_score, labels, labels_as_ndarray): """Test when labels and y_score are multiclass.""" if labels_as_ndarray: labels = np.asarray(labels) y_score = np.array( [ [0.4, 0.3, 0.2, 0.1], [0.1, 0.3, 0.4, 0.2], [0.4, 0.1, 0.2, 0.3], [0.3, 0.2, 0.4, 0.1], ] )
score = top_k_accuracy_score(y_true, y_score, k=2, labels=labels) assert score == pytest.approx(true_score)
def test_top_k_accuracy_score_increasing(): # Make sure increasing k leads to a higher score X, y = datasets.make_classification( n_classes=10, n_samples=1000, n_informative=10, random_state=0 )
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = LogisticRegression(random_state=0) clf.fit(X_train, y_train)
for X, y in zip((X_train, X_test), (y_train, y_test)): scores = [ top_k_accuracy_score(y, clf.predict_proba(X), k=k) for k in range(2, 10) ]
assert np.all(np.diff(scores) > 0)
@pytest.mark.parametrize( "y_true, k, true_score", [ ([0, 1, 2, 3], 1, 0.25), ([0, 1, 2, 3], 2, 0.5), ([0, 1, 2, 3], 3, 1), ],)def test_top_k_accuracy_score_ties(y_true, k, true_score): # Make sure highest indices labels are chosen first in case of ties y_score = np.array( [ [5, 5, 7, 0], [1, 5, 5, 5], [0, 0, 3, 3], [1, 1, 1, 1], ] ) assert top_k_accuracy_score(y_true, y_score, k=k) == pytest.approx(true_score)
@pytest.mark.parametrize( "y_true, k", [ ([0, 1, 2, 3], 4), ([0, 1, 2, 3], 5), ],)def test_top_k_accuracy_score_warning(y_true, k): y_score = np.array( [ [0.4, 0.3, 0.2, 0.1], [0.1, 0.4, 0.3, 0.2], [0.2, 0.1, 0.4, 0.3], [0.3, 0.2, 0.1, 0.4], ] ) expected_message = ( r"'k' \(\d+\) greater than or equal to 'n_classes' \(\d+\) will result in a " "perfect score and is therefore meaningless." ) with pytest.warns(UndefinedMetricWarning, match=expected_message): score = top_k_accuracy_score(y_true, y_score, k=k) assert score == 1
@pytest.mark.parametrize( "y_true, y_score, labels, msg", [ ( [0, 0.57, 1, 2], [ [0.2, 0.1, 0.7], [0.4, 0.3, 0.3], [0.3, 0.4, 0.3], [0.4, 0.5, 0.1], ], None, "y type must be 'binary' or 'multiclass', got 'continuous'", ), ( [0, 1, 2, 3], [ [0.2, 0.1, 0.7], [0.4, 0.3, 0.3], [0.3, 0.4, 0.3], [0.4, 0.5, 0.1], ], None, r"Number of classes in 'y_true' \(4\) not equal to the number of " r"classes in 'y_score' \(3\).", ), ( ["c", "c", "a", "b"], [ [0.2, 0.1, 0.7], [0.4, 0.3, 0.3], [0.3, 0.4, 0.3], [0.4, 0.5, 0.1], ], ["a", "b", "c", "c"], "Parameter 'labels' must be unique.", ), ( ["c", "c", "a", "b"], [ [0.2, 0.1, 0.7], [0.4, 0.3, 0.3], [0.3, 0.4, 0.3], [0.4, 0.5, 0.1], ], ["a", "c", "b"], "Parameter 'labels' must be ordered.", ), ( [0, 0, 1, 2], [ [0.2, 0.1, 0.7], [0.4, 0.3, 0.3], [0.3, 0.4, 0.3], [0.4, 0.5, 0.1], ], [0, 1, 2, 3], r"Number of given labels \(4\) not equal to the number of classes in " r"'y_score' \(3\).", ), ( [0, 0, 1, 2], [ [0.2, 0.1, 0.7], [0.4, 0.3, 0.3], [0.3, 0.4, 0.3], [0.4, 0.5, 0.1], ], [0, 1, 3], "'y_true' contains labels not in parameter 'labels'.", ), ( [0, 1], [[0.5, 0.2, 0.2], [0.3, 0.4, 0.2]], None, "`y_true` is binary while y_score is 2d with 3 classes. If" " `y_true` does not contain all the labels, `labels` must be provided", ), ],)def test_top_k_accuracy_score_error(y_true, y_score, labels, msg): with pytest.raises(ValueError, match=msg): top_k_accuracy_score(y_true, y_score, k=2, labels=labels)
def test_label_ranking_avg_precision_score_should_allow_csr_matrix_for_y_true_input(): # Test that label_ranking_avg_precision_score accept sparse y_true. # Non-regression test for #22575 y_true = csr_matrix([[1, 0, 0], [0, 0, 1]]) y_score = np.array([[0.5, 0.9, 0.6], [0, 0, 1]]) result = label_ranking_average_precision_score(y_true, y_score) assert result == pytest.approx(2 / 3)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200from copy import deepcopyimport pickleimport tempfileimport shutilimport osimport numbersfrom unittest.mock import Mockfrom functools import partial
import numpy as npimport pytestimport joblib
from numpy.testing import assert_allclosefrom sklearn.utils._testing import assert_almost_equalfrom sklearn.utils._testing import assert_array_equalfrom sklearn.utils._testing import ignore_warnings
from sklearn.base import BaseEstimatorfrom sklearn.metrics import ( accuracy_score, balanced_accuracy_score, average_precision_score, brier_score_loss, f1_score, fbeta_score, jaccard_score, log_loss, precision_score, r2_score, recall_score, roc_auc_score, top_k_accuracy_score, matthews_corrcoef,)from sklearn.metrics import cluster as cluster_modulefrom sklearn.metrics import check_scoringfrom sklearn.metrics._scorer import ( _PredictScorer, _passthrough_scorer, _MultimetricScorer, _check_multimetric_scoring,)from sklearn.metrics import make_scorer, get_scorer, SCORERS, get_scorer_namesfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import LinearSVCfrom sklearn.pipeline import make_pipelinefrom sklearn.cluster import KMeansfrom sklearn.linear_model import Ridge, LogisticRegression, Perceptronfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressorfrom sklearn.datasets import make_blobsfrom sklearn.datasets import make_classification, make_regressionfrom sklearn.datasets import make_multilabel_classificationfrom sklearn.datasets import load_diabetesfrom sklearn.model_selection import train_test_split, cross_val_scorefrom sklearn.model_selection import GridSearchCVfrom sklearn.multiclass import OneVsRestClassifier
REGRESSION_SCORERS = [ "explained_variance", "r2", "neg_mean_absolute_error", "neg_mean_squared_error", "neg_mean_absolute_percentage_error", "neg_mean_squared_log_error", "neg_median_absolute_error", "neg_root_mean_squared_error", "mean_absolute_error", "mean_absolute_percentage_error", "mean_squared_error", "median_absolute_error", "max_error", "neg_mean_poisson_deviance", "neg_mean_gamma_deviance",]
CLF_SCORERS = [ "accuracy", "balanced_accuracy", "top_k_accuracy", "f1", "f1_weighted", "f1_macro", "f1_micro", "roc_auc", "average_precision", "precision", "precision_weighted", "precision_macro", "precision_micro", "recall", "recall_weighted", "recall_macro", "recall_micro", "neg_log_loss", "neg_brier_score", "jaccard", "jaccard_weighted", "jaccard_macro", "jaccard_micro", "roc_auc_ovr", "roc_auc_ovo", "roc_auc_ovr_weighted", "roc_auc_ovo_weighted", "matthews_corrcoef", "positive_likelihood_ratio", "neg_negative_likelihood_ratio",]
# All supervised cluster scorers (They behave like classification metric)CLUSTER_SCORERS = [ "adjusted_rand_score", "rand_score", "homogeneity_score", "completeness_score", "v_measure_score", "mutual_info_score", "adjusted_mutual_info_score", "normalized_mutual_info_score", "fowlkes_mallows_score",]
MULTILABEL_ONLY_SCORERS = [ "precision_samples", "recall_samples", "f1_samples", "jaccard_samples",]
REQUIRE_POSITIVE_Y_SCORERS = ["neg_mean_poisson_deviance", "neg_mean_gamma_deviance"]
def _require_positive_y(y): """Make targets strictly positive""" offset = abs(y.min()) + 1 y = y + offset return y
def _make_estimators(X_train, y_train, y_ml_train): # Make estimators that make sense to test various scoring methods sensible_regr = DecisionTreeRegressor(random_state=0) # some of the regressions scorers require strictly positive input. sensible_regr.fit(X_train, _require_positive_y(y_train)) sensible_clf = DecisionTreeClassifier(random_state=0) sensible_clf.fit(X_train, y_train) sensible_ml_clf = DecisionTreeClassifier(random_state=0) sensible_ml_clf.fit(X_train, y_ml_train) return dict( [(name, sensible_regr) for name in REGRESSION_SCORERS] + [(name, sensible_clf) for name in CLF_SCORERS] + [(name, sensible_clf) for name in CLUSTER_SCORERS] + [(name, sensible_ml_clf) for name in MULTILABEL_ONLY_SCORERS] )
X_mm, y_mm, y_ml_mm = None, None, NoneESTIMATORS = NoneTEMP_FOLDER = None
def setup_module(): # Create some memory mapped data global X_mm, y_mm, y_ml_mm, TEMP_FOLDER, ESTIMATORS TEMP_FOLDER = tempfile.mkdtemp(prefix="sklearn_test_score_objects_") X, y = make_classification(n_samples=30, n_features=5, random_state=0) _, y_ml = make_multilabel_classification(n_samples=X.shape[0], random_state=0) filename = os.path.join(TEMP_FOLDER, "test_data.pkl") joblib.dump((X, y, y_ml), filename) X_mm, y_mm, y_ml_mm = joblib.load(filename, mmap_mode="r") ESTIMATORS = _make_estimators(X_mm, y_mm, y_ml_mm)
def teardown_module(): global X_mm, y_mm, y_ml_mm, TEMP_FOLDER, ESTIMATORS # GC closes the mmap file descriptors X_mm, y_mm, y_ml_mm, ESTIMATORS = None, None, None, None shutil.rmtree(TEMP_FOLDER)
class EstimatorWithoutFit: """Dummy estimator to test scoring validators"""
pass
class EstimatorWithFit(BaseEstimator): """Dummy estimator to test scoring validators"""
def fit(self, X, y): return self
class EstimatorWithFitAndScore: """Dummy estimator to test scoring validators"""
def fit(self, X, y): return self
def score(self, X, y): return 1.0
class EstimatorWithFitAndPredict: """Dummy estimator to test scoring validators"""
def fit(self, X, y): self.y = y return self
def predict(self, X): return self.y
class DummyScorer: """Dummy scorer that always returns 1."""
def __call__(self, est, X, y): return 1
def test_all_scorers_repr(): # Test that all scorers have a working repr for name in get_scorer_names(): repr(get_scorer(name))
def check_scoring_validator_for_single_metric_usecases(scoring_validator): # Test all branches of single metric usecases estimator = EstimatorWithoutFit() pattern = ( r"estimator should be an estimator implementing 'fit' method," r" .* was passed" ) with pytest.raises(TypeError, match=pattern): scoring_validator(estimator)
estimator = EstimatorWithFitAndScore() estimator.fit([[1]], [1]) scorer = scoring_validator(estimator) assert scorer is _passthrough_scorer assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0)
estimator = EstimatorWithFitAndPredict() estimator.fit([[1]], [1]) pattern = ( r"If no scoring is specified, the estimator passed should have" r" a 'score' method\. The estimator .* does not\." ) with pytest.raises(TypeError, match=pattern): scoring_validator(estimator)
scorer = scoring_validator(estimator, scoring="accuracy") assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0)
estimator = EstimatorWithFit() scorer = scoring_validator(estimator, scoring="accuracy") assert isinstance(scorer, _PredictScorer)
# Test the allow_none parameter for check_scoring alone if scoring_validator is check_scoring: estimator = EstimatorWithFit() scorer = scoring_validator(estimator, allow_none=True) assert scorer is None
@pytest.mark.parametrize( "scoring", ( ("accuracy",), ["precision"], {"acc": "accuracy", "precision": "precision"}, ("accuracy", "precision"), ["precision", "accuracy"], { "accuracy": make_scorer(accuracy_score), "precision": make_scorer(precision_score), }, ), ids=[ "single_tuple", "single_list", "dict_str", "multi_tuple", "multi_list", "dict_callable", ],)def test_check_scoring_and_check_multimetric_scoring(scoring): check_scoring_validator_for_single_metric_usecases(check_scoring) # To make sure the check_scoring is correctly applied to the constituent # scorers
estimator = LinearSVC(random_state=0) estimator.fit([[1], [2], [3]], [1, 1, 0])
scorers = _check_multimetric_scoring(estimator, scoring) assert isinstance(scorers, dict) assert sorted(scorers.keys()) == sorted(list(scoring)) assert all( [isinstance(scorer, _PredictScorer) for scorer in list(scorers.values())] )
if "acc" in scoring: assert_almost_equal( scorers["acc"](estimator, [[1], [2], [3]], [1, 0, 0]), 2.0 / 3.0 ) if "accuracy" in scoring: assert_almost_equal( scorers["accuracy"](estimator, [[1], [2], [3]], [1, 0, 0]), 2.0 / 3.0 ) if "precision" in scoring: assert_almost_equal( scorers["precision"](estimator, [[1], [2], [3]], [1, 0, 0]), 0.5 )
@pytest.mark.parametrize( "scoring, msg", [ ( (make_scorer(precision_score), make_scorer(accuracy_score)), "One or more of the elements were callables", ), ([5], "Non-string types were found"), ((make_scorer(precision_score),), "One or more of the elements were callables"), ((), "Empty list was given"), (("f1", "f1"), "Duplicate elements were found"), ({4: "accuracy"}, "Non-string types were found in the keys"), ({}, "An empty dict was passed"), ], ids=[ "tuple of callables", "list of int", "tuple of one callable", "empty tuple", "non-unique str", "non-string key dict", "empty dict", ],)def test_check_scoring_and_check_multimetric_scoring_errors(scoring, msg): # Make sure it raises errors when scoring parameter is not valid. # More weird corner cases are tested at test_validation.py estimator = EstimatorWithFitAndPredict() estimator.fit([[1]], [1])
with pytest.raises(ValueError, match=msg): _check_multimetric_scoring(estimator, scoring=scoring)
def test_check_scoring_gridsearchcv(): # test that check_scoring works on GridSearchCV and pipeline. # slightly redundant non-regression test.
grid = GridSearchCV(LinearSVC(), param_grid={"C": [0.1, 1]}, cv=3) scorer = check_scoring(grid, scoring="f1") assert isinstance(scorer, _PredictScorer)
pipe = make_pipeline(LinearSVC()) scorer = check_scoring(pipe, scoring="f1") assert isinstance(scorer, _PredictScorer)
# check that cross_val_score definitely calls the scorer # and doesn't make any assumptions about the estimator apart from having a # fit. scores = cross_val_score( EstimatorWithFit(), [[1], [2], [3]], [1, 0, 1], scoring=DummyScorer(), cv=3 ) assert_array_equal(scores, 1)
def test_make_scorer(): # Sanity check on the make_scorer factory function. f = lambda *args: 0 with pytest.raises(ValueError): make_scorer(f, needs_threshold=True, needs_proba=True)
@pytest.mark.parametrize( "scorer_name, metric", [ ("f1", f1_score), ("f1_weighted", partial(f1_score, average="weighted")), ("f1_macro", partial(f1_score, average="macro")), ("f1_micro", partial(f1_score, average="micro")), ("precision", precision_score), ("precision_weighted", partial(precision_score, average="weighted")), ("precision_macro", partial(precision_score, average="macro")), ("precision_micro", partial(precision_score, average="micro")), ("recall", recall_score), ("recall_weighted", partial(recall_score, average="weighted")), ("recall_macro", partial(recall_score, average="macro")), ("recall_micro", partial(recall_score, average="micro")), ("jaccard", jaccard_score), ("jaccard_weighted", partial(jaccard_score, average="weighted")), ("jaccard_macro", partial(jaccard_score, average="macro")), ("jaccard_micro", partial(jaccard_score, average="micro")), ("top_k_accuracy", top_k_accuracy_score), ("matthews_corrcoef", matthews_corrcoef), ],)def test_classification_binary_scores(scorer_name, metric): # check consistency between score and scorer for scores supporting # binary classification. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LinearSVC(random_state=0) clf.fit(X_train, y_train)
score = get_scorer(scorer_name)(clf, X_test, y_test) expected_score = metric(y_test, clf.predict(X_test)) assert_almost_equal(score, expected_score)
@pytest.mark.parametrize( "scorer_name, metric", [ ("accuracy", accuracy_score), ("balanced_accuracy", balanced_accuracy_score), ("f1_weighted", partial(f1_score, average="weighted")), ("f1_macro", partial(f1_score, average="macro")), ("f1_micro", partial(f1_score, average="micro")), ("precision_weighted", partial(precision_score, average="weighted")), ("precision_macro", partial(precision_score, average="macro")), ("precision_micro", partial(precision_score, average="micro")), ("recall_weighted", partial(recall_score, average="weighted")), ("recall_macro", partial(recall_score, average="macro")), ("recall_micro", partial(recall_score, average="micro")), ("jaccard_weighted", partial(jaccard_score, average="weighted")), ("jaccard_macro", partial(jaccard_score, average="macro")), ("jaccard_micro", partial(jaccard_score, average="micro")), ],)def test_classification_multiclass_scores(scorer_name, metric): # check consistency between score and scorer for scores supporting # multiclass classification. X, y = make_classification( n_classes=3, n_informative=3, n_samples=30, random_state=0 )
# use `stratify` = y to ensure train and test sets capture all classes X_train, X_test, y_train, y_test = train_test_split( X, y, random_state=0, stratify=y )
clf = DecisionTreeClassifier(random_state=0) clf.fit(X_train, y_train) score = get_scorer(scorer_name)(clf, X_test, y_test) expected_score = metric(y_test, clf.predict(X_test)) assert score == pytest.approx(expected_score)
def test_custom_scorer_pickling(): # test that custom scorer can be pickled X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LinearSVC(random_state=0) clf.fit(X_train, y_train)
scorer = make_scorer(fbeta_score, beta=2) score1 = scorer(clf, X_test, y_test) unpickled_scorer = pickle.loads(pickle.dumps(scorer)) score2 = unpickled_scorer(clf, X_test, y_test) assert score1 == pytest.approx(score2)
# smoke test the repr: repr(fbeta_score)
def test_regression_scorers(): # Test regression scorers. diabetes = load_diabetes() X, y = diabetes.data, diabetes.target X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = Ridge() clf.fit(X_train, y_train) score1 = get_scorer("r2")(clf, X_test, y_test) score2 = r2_score(y_test, clf.predict(X_test)) assert_almost_equal(score1, score2)
def test_thresholded_scorers(): # Test scorers that take thresholds. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LogisticRegression(random_state=0) clf.fit(X_train, y_train) score1 = get_scorer("roc_auc")(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.decision_function(X_test)) score3 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) assert_almost_equal(score1, score2) assert_almost_equal(score1, score3)
logscore = get_scorer("neg_log_loss")(clf, X_test, y_test) logloss = log_loss(y_test, clf.predict_proba(X_test)) assert_almost_equal(-logscore, logloss)
# same for an estimator without decision_function clf = DecisionTreeClassifier() clf.fit(X_train, y_train) score1 = get_scorer("roc_auc")(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) assert_almost_equal(score1, score2)
# test with a regressor (no decision_function) reg = DecisionTreeRegressor() reg.fit(X_train, y_train) score1 = get_scorer("roc_auc")(reg, X_test, y_test) score2 = roc_auc_score(y_test, reg.predict(X_test)) assert_almost_equal(score1, score2)
# Test that an exception is raised on more than two classes X, y = make_blobs(random_state=0, centers=3) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf.fit(X_train, y_train) with pytest.raises(ValueError, match="multiclass format is not supported"): get_scorer("roc_auc")(clf, X_test, y_test)
# test error is raised with a single class present in model # (predict_proba shape is not suitable for binary auc) X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = DecisionTreeClassifier() clf.fit(X_train, np.zeros_like(y_train)) with pytest.raises(ValueError, match="need classifier with two classes"): get_scorer("roc_auc")(clf, X_test, y_test)
# for proba scorers with pytest.raises(ValueError, match="need classifier with two classes"): get_scorer("neg_log_loss")(clf, X_test, y_test)
def test_thresholded_scorers_multilabel_indicator_data(): # Test that the scorer work with multilabel-indicator format # for multilabel and multi-output multi-class classifier X, y = make_multilabel_classification(allow_unlabeled=False, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
# Multi-output multi-class predict_proba clf = DecisionTreeClassifier() clf.fit(X_train, y_train) y_proba = clf.predict_proba(X_test) score1 = get_scorer("roc_auc")(clf, X_test, y_test) score2 = roc_auc_score(y_test, np.vstack([p[:, -1] for p in y_proba]).T) assert_almost_equal(score1, score2)
# Multi-output multi-class decision_function # TODO Is there any yet? clf = DecisionTreeClassifier() clf.fit(X_train, y_train) clf._predict_proba = clf.predict_proba clf.predict_proba = None clf.decision_function = lambda X: [p[:, 1] for p in clf._predict_proba(X)]
y_proba = clf.decision_function(X_test) score1 = get_scorer("roc_auc")(clf, X_test, y_test) score2 = roc_auc_score(y_test, np.vstack([p for p in y_proba]).T) assert_almost_equal(score1, score2)
# Multilabel predict_proba clf = OneVsRestClassifier(DecisionTreeClassifier()) clf.fit(X_train, y_train) score1 = get_scorer("roc_auc")(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.predict_proba(X_test)) assert_almost_equal(score1, score2)
# Multilabel decision function clf = OneVsRestClassifier(LinearSVC(random_state=0)) clf.fit(X_train, y_train) score1 = get_scorer("roc_auc")(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.decision_function(X_test)) assert_almost_equal(score1, score2)
def test_supervised_cluster_scorers(): # Test clustering scorers against gold standard labeling. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) km = KMeans(n_clusters=3, n_init="auto") km.fit(X_train) for name in CLUSTER_SCORERS: score1 = get_scorer(name)(km, X_test, y_test) score2 = getattr(cluster_module, name)(y_test, km.predict(X_test)) assert_almost_equal(score1, score2)
@ignore_warningsdef test_raises_on_score_list(): # Test that when a list of scores is returned, we raise proper errors. X, y = make_blobs(random_state=0) f1_scorer_no_average = make_scorer(f1_score, average=None) clf = DecisionTreeClassifier() with pytest.raises(ValueError): cross_val_score(clf, X, y, scoring=f1_scorer_no_average) grid_search = GridSearchCV( clf, scoring=f1_scorer_no_average, param_grid={"max_depth": [1, 2]} ) with pytest.raises(ValueError): grid_search.fit(X, y)
@ignore_warningsdef test_classification_scorer_sample_weight(): # Test that classification scorers support sample_weight or raise sensible # errors
# Unlike the metrics invariance test, in the scorer case it's harder # to ensure that, on the classifier output, weighted and unweighted # scores really should be unequal. X, y = make_classification(random_state=0) _, y_ml = make_multilabel_classification(n_samples=X.shape[0], random_state=0) split = train_test_split(X, y, y_ml, random_state=0) X_train, X_test, y_train, y_test, y_ml_train, y_ml_test = split
sample_weight = np.ones_like(y_test) sample_weight[:10] = 0
# get sensible estimators for each metric estimator = _make_estimators(X_train, y_train, y_ml_train)
for name in get_scorer_names(): scorer = get_scorer(name) if name in REGRESSION_SCORERS: # skip the regression scores continue if name == "top_k_accuracy": # in the binary case k > 1 will always lead to a perfect score scorer._kwargs = {"k": 1} if name in MULTILABEL_ONLY_SCORERS: target = y_ml_test else: target = y_test try: weighted = scorer( estimator[name], X_test, target, sample_weight=sample_weight ) ignored = scorer(estimator[name], X_test[10:], target[10:]) unweighted = scorer(estimator[name], X_test, target) assert weighted != unweighted, ( f"scorer {name} behaves identically when called with " f"sample weights: {weighted} vs {unweighted}" ) assert_almost_equal( weighted, ignored, err_msg=( f"scorer {name} behaves differently " "when ignoring samples and setting " f"sample_weight to 0: {weighted} vs {ignored}" ), )
except TypeError as e: assert "sample_weight" in str(e), ( f"scorer {name} raises unhelpful exception when called " f"with sample weights: {str(e)}" )
@ignore_warningsdef test_regression_scorer_sample_weight(): # Test that regression scorers support sample_weight or raise sensible # errors
# Odd number of test samples req for neg_median_absolute_error X, y = make_regression(n_samples=101, n_features=20, random_state=0) y = _require_positive_y(y) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
sample_weight = np.ones_like(y_test) # Odd number req for neg_median_absolute_error sample_weight[:11] = 0
reg = DecisionTreeRegressor(random_state=0) reg.fit(X_train, y_train)
for name in get_scorer_names(): scorer = get_scorer(name) if name not in REGRESSION_SCORERS: # skip classification scorers continue try: weighted = scorer(reg, X_test, y_test, sample_weight=sample_weight) ignored = scorer(reg, X_test[11:], y_test[11:]) unweighted = scorer(reg, X_test, y_test) assert weighted != unweighted, ( f"scorer {name} behaves identically when called with " f"sample weights: {weighted} vs {unweighted}" ) assert_almost_equal( weighted, ignored, err_msg=( f"scorer {name} behaves differently " "when ignoring samples and setting " f"sample_weight to 0: {weighted} vs {ignored}" ), )
except TypeError as e: assert "sample_weight" in str(e), ( f"scorer {name} raises unhelpful exception when called " f"with sample weights: {str(e)}" )
@pytest.mark.parametrize("name", get_scorer_names())def test_scorer_memmap_input(name): # Non-regression test for #6147: some score functions would # return singleton memmap when computed on memmap data instead of scalar # float values.
if name in REQUIRE_POSITIVE_Y_SCORERS: y_mm_1 = _require_positive_y(y_mm) y_ml_mm_1 = _require_positive_y(y_ml_mm) else: y_mm_1, y_ml_mm_1 = y_mm, y_ml_mm
# UndefinedMetricWarning for P / R scores with ignore_warnings(): scorer, estimator = get_scorer(name), ESTIMATORS[name] if name in MULTILABEL_ONLY_SCORERS: score = scorer(estimator, X_mm, y_ml_mm_1) else: score = scorer(estimator, X_mm, y_mm_1) assert isinstance(score, numbers.Number), name
def test_scoring_is_not_metric(): with pytest.raises(ValueError, match="make_scorer"): check_scoring(LogisticRegression(), scoring=f1_score) with pytest.raises(ValueError, match="make_scorer"): check_scoring(LogisticRegression(), scoring=roc_auc_score) with pytest.raises(ValueError, match="make_scorer"): check_scoring(Ridge(), scoring=r2_score) with pytest.raises(ValueError, match="make_scorer"): check_scoring(KMeans(), scoring=cluster_module.adjusted_rand_score) with pytest.raises(ValueError, match="make_scorer"): check_scoring(KMeans(), scoring=cluster_module.rand_score)
@pytest.mark.parametrize( "scorers,expected_predict_count," "expected_predict_proba_count,expected_decision_func_count", [ ( { "a1": "accuracy", "a2": "accuracy", "ll1": "neg_log_loss", "ll2": "neg_log_loss", "ra1": "roc_auc", "ra2": "roc_auc", }, 1, 1, 1, ), (["roc_auc", "accuracy"], 1, 0, 1), (["neg_log_loss", "accuracy"], 1, 1, 0), ],)def test_multimetric_scorer_calls_method_once( scorers, expected_predict_count, expected_predict_proba_count, expected_decision_func_count,): X, y = np.array([[1], [1], [0], [0], [0]]), np.array([0, 1, 1, 1, 0])
mock_est = Mock() fit_func = Mock(return_value=mock_est) predict_func = Mock(return_value=y)
pos_proba = np.random.rand(X.shape[0]) proba = np.c_[1 - pos_proba, pos_proba] predict_proba_func = Mock(return_value=proba) decision_function_func = Mock(return_value=pos_proba)
mock_est.fit = fit_func mock_est.predict = predict_func mock_est.predict_proba = predict_proba_func mock_est.decision_function = decision_function_func # add the classes that would be found during fit mock_est.classes_ = np.array([0, 1])
scorer_dict = _check_multimetric_scoring(LogisticRegression(), scorers) multi_scorer = _MultimetricScorer(scorers=scorer_dict) results = multi_scorer(mock_est, X, y)
assert set(scorers) == set(results) # compare dict keys
assert predict_func.call_count == expected_predict_count assert predict_proba_func.call_count == expected_predict_proba_count assert decision_function_func.call_count == expected_decision_func_count
def test_multimetric_scorer_calls_method_once_classifier_no_decision(): predict_proba_call_cnt = 0
class MockKNeighborsClassifier(KNeighborsClassifier): def predict_proba(self, X): nonlocal predict_proba_call_cnt predict_proba_call_cnt += 1 return super().predict_proba(X)
X, y = np.array([[1], [1], [0], [0], [0]]), np.array([0, 1, 1, 1, 0])
# no decision function clf = MockKNeighborsClassifier(n_neighbors=1) clf.fit(X, y)
scorers = ["roc_auc", "neg_log_loss"] scorer_dict = _check_multimetric_scoring(clf, scorers) scorer = _MultimetricScorer(scorers=scorer_dict) scorer(clf, X, y)
assert predict_proba_call_cnt == 1
def test_multimetric_scorer_calls_method_once_regressor_threshold(): predict_called_cnt = 0
class MockDecisionTreeRegressor(DecisionTreeRegressor): def predict(self, X): nonlocal predict_called_cnt predict_called_cnt += 1 return super().predict(X)
X, y = np.array([[1], [1], [0], [0], [0]]), np.array([0, 1, 1, 1, 0])
# no decision function clf = MockDecisionTreeRegressor() clf.fit(X, y)
scorers = {"neg_mse": "neg_mean_squared_error", "r2": "roc_auc"} scorer_dict = _check_multimetric_scoring(clf, scorers) scorer = _MultimetricScorer(scorers=scorer_dict) scorer(clf, X, y)
assert predict_called_cnt == 1
def test_multimetric_scorer_sanity_check(): # scoring dictionary returned is the same as calling each scorer separately scorers = { "a1": "accuracy", "a2": "accuracy", "ll1": "neg_log_loss", "ll2": "neg_log_loss", "ra1": "roc_auc", "ra2": "roc_auc", }
X, y = make_classification(random_state=0)
clf = DecisionTreeClassifier() clf.fit(X, y)
scorer_dict = _check_multimetric_scoring(clf, scorers) multi_scorer = _MultimetricScorer(scorers=scorer_dict)
result = multi_scorer(clf, X, y)
separate_scores = { name: get_scorer(name)(clf, X, y) for name in ["accuracy", "neg_log_loss", "roc_auc"] }
for key, value in result.items(): score_name = scorers[key] assert_allclose(value, separate_scores[score_name])
@pytest.mark.parametrize("raise_exc", [True, False])def test_multimetric_scorer_exception_handling(raise_exc): """Check that the calling of the `_MultimetricScorer` returns exception messages in the result dict for the failing scorers in case of `raise_exc` is `False` and if `raise_exc` is `True`, then the proper exception is raised. """ scorers = { "failing_1": "neg_mean_squared_log_error", "non_failing": "neg_median_absolute_error", "failing_2": "neg_mean_squared_log_error", }
X, y = make_classification( n_samples=50, n_features=2, n_redundant=0, random_state=0 ) y *= -1 # neg_mean_squared_log_error fails if y contains negative values
clf = DecisionTreeClassifier().fit(X, y)
scorer_dict = _check_multimetric_scoring(clf, scorers) multi_scorer = _MultimetricScorer(scorers=scorer_dict, raise_exc=raise_exc)
error_msg = ( "Mean Squared Logarithmic Error cannot be used when targets contain" " negative values." )
if raise_exc: with pytest.raises(ValueError, match=error_msg): multi_scorer(clf, X, y) else: result = multi_scorer(clf, X, y)
exception_message_1 = result["failing_1"] score = result["non_failing"] exception_message_2 = result["failing_2"]
assert isinstance(exception_message_1, str) and error_msg in exception_message_1 assert isinstance(score, float) assert isinstance(exception_message_2, str) and error_msg in exception_message_2
@pytest.mark.parametrize( "scorer_name, metric", [ ("roc_auc_ovr", partial(roc_auc_score, multi_class="ovr")), ("roc_auc_ovo", partial(roc_auc_score, multi_class="ovo")), ( "roc_auc_ovr_weighted", partial(roc_auc_score, multi_class="ovr", average="weighted"), ), ( "roc_auc_ovo_weighted", partial(roc_auc_score, multi_class="ovo", average="weighted"), ), ],)def test_multiclass_roc_proba_scorer(scorer_name, metric): scorer = get_scorer(scorer_name) X, y = make_classification( n_classes=3, n_informative=3, n_samples=20, random_state=0 ) lr = LogisticRegression(multi_class="multinomial").fit(X, y) y_proba = lr.predict_proba(X) expected_score = metric(y, y_proba)
assert scorer(lr, X, y) == pytest.approx(expected_score)
def test_multiclass_roc_proba_scorer_label(): scorer = make_scorer( roc_auc_score, multi_class="ovo", labels=[0, 1, 2], needs_proba=True ) X, y = make_classification( n_classes=3, n_informative=3, n_samples=20, random_state=0 ) lr = LogisticRegression(multi_class="multinomial").fit(X, y) y_proba = lr.predict_proba(X)
y_binary = y == 0 expected_score = roc_auc_score( y_binary, y_proba, multi_class="ovo", labels=[0, 1, 2] )
assert scorer(lr, X, y_binary) == pytest.approx(expected_score)
@pytest.mark.parametrize( "scorer_name", ["roc_auc_ovr", "roc_auc_ovo", "roc_auc_ovr_weighted", "roc_auc_ovo_weighted"],)def test_multiclass_roc_no_proba_scorer_errors(scorer_name): # Perceptron has no predict_proba scorer = get_scorer(scorer_name) X, y = make_classification( n_classes=3, n_informative=3, n_samples=20, random_state=0 ) lr = Perceptron().fit(X, y) msg = "'Perceptron' object has no attribute 'predict_proba'" with pytest.raises(AttributeError, match=msg): scorer(lr, X, y)
@pytest.fixturedef string_labeled_classification_problem(): """Train a classifier on binary problem with string target.
The classifier is trained on a binary classification problem where the minority class of interest has a string label that is intentionally not the greatest class label using the lexicographic order. In this case, "cancer" is the positive label, and `classifier.classes_` is `["cancer", "not cancer"]`.
In addition, the dataset is imbalanced to better identify problems when using non-symmetric performance metrics such as f1-score, average precision and so on.
Returns ------- classifier : estimator object Trained classifier on the binary problem. X_test : ndarray of shape (n_samples, n_features) Data to be used as testing set in tests. y_test : ndarray of shape (n_samples,), dtype=object Binary target where labels are strings. y_pred : ndarray of shape (n_samples,), dtype=object Prediction of `classifier` when predicting for `X_test`. y_pred_proba : ndarray of shape (n_samples, 2), dtype=np.float64 Probabilities of `classifier` when predicting for `X_test`. y_pred_decision : ndarray of shape (n_samples,), dtype=np.float64 Decision function values of `classifier` when predicting on `X_test`. """ from sklearn.datasets import load_breast_cancer from sklearn.utils import shuffle
X, y = load_breast_cancer(return_X_y=True) # create an highly imbalanced classification task idx_positive = np.flatnonzero(y == 1) idx_negative = np.flatnonzero(y == 0) idx_selected = np.hstack([idx_negative, idx_positive[:25]]) X, y = X[idx_selected], y[idx_selected] X, y = shuffle(X, y, random_state=42) # only use 2 features to make the problem even harder X = X[:, :2] y = np.array(["cancer" if c == 1 else "not cancer" for c in y], dtype=object) X_train, X_test, y_train, y_test = train_test_split( X, y, stratify=y, random_state=0, ) classifier = LogisticRegression().fit(X_train, y_train) y_pred = classifier.predict(X_test) y_pred_proba = classifier.predict_proba(X_test) y_pred_decision = classifier.decision_function(X_test)
return classifier, X_test, y_test, y_pred, y_pred_proba, y_pred_decision
def test_average_precision_pos_label(string_labeled_classification_problem): # check that _ThresholdScorer will lead to the right score when passing # `pos_label`. Currently, only `average_precision_score` is defined to # be such a scorer. ( clf, X_test, y_test, _, y_pred_proba, y_pred_decision, ) = string_labeled_classification_problem
pos_label = "cancer" # we need to select the positive column or reverse the decision values y_pred_proba = y_pred_proba[:, 0] y_pred_decision = y_pred_decision * -1 assert clf.classes_[0] == pos_label
# check that when calling the scoring function, probability estimates and # decision values lead to the same results ap_proba = average_precision_score(y_test, y_pred_proba, pos_label=pos_label) ap_decision_function = average_precision_score( y_test, y_pred_decision, pos_label=pos_label ) assert ap_proba == pytest.approx(ap_decision_function)
# create a scorer which would require to pass a `pos_label` # check that it fails if `pos_label` is not provided average_precision_scorer = make_scorer( average_precision_score, needs_threshold=True, ) err_msg = "pos_label=1 is not a valid label. It should be one of " with pytest.raises(ValueError, match=err_msg): average_precision_scorer(clf, X_test, y_test)
# otherwise, the scorer should give the same results than calling the # scoring function average_precision_scorer = make_scorer( average_precision_score, needs_threshold=True, pos_label=pos_label ) ap_scorer = average_precision_scorer(clf, X_test, y_test)
assert ap_scorer == pytest.approx(ap_proba)
# The above scorer call is using `clf.decision_function`. We will force # it to use `clf.predict_proba`. clf_without_predict_proba = deepcopy(clf)
def _predict_proba(self, X): raise NotImplementedError
clf_without_predict_proba.predict_proba = partial( _predict_proba, clf_without_predict_proba ) # sanity check with pytest.raises(NotImplementedError): clf_without_predict_proba.predict_proba(X_test)
ap_scorer = average_precision_scorer(clf_without_predict_proba, X_test, y_test) assert ap_scorer == pytest.approx(ap_proba)
def test_brier_score_loss_pos_label(string_labeled_classification_problem): # check that _ProbaScorer leads to the right score when `pos_label` is # provided. Currently only the `brier_score_loss` is defined to be such # a scorer. clf, X_test, y_test, _, y_pred_proba, _ = string_labeled_classification_problem
pos_label = "cancer" assert clf.classes_[0] == pos_label
# brier score loss is symmetric brier_pos_cancer = brier_score_loss(y_test, y_pred_proba[:, 0], pos_label="cancer") brier_pos_not_cancer = brier_score_loss( y_test, y_pred_proba[:, 1], pos_label="not cancer" ) assert brier_pos_cancer == pytest.approx(brier_pos_not_cancer)
brier_scorer = make_scorer( brier_score_loss, needs_proba=True, pos_label=pos_label, ) assert brier_scorer(clf, X_test, y_test) == pytest.approx(brier_pos_cancer)
@pytest.mark.parametrize( "score_func", [f1_score, precision_score, recall_score, jaccard_score])def test_non_symmetric_metric_pos_label( score_func, string_labeled_classification_problem): # check that _PredictScorer leads to the right score when `pos_label` is # provided. We check for all possible metric supported. # Note: At some point we may end up having "scorer tags". clf, X_test, y_test, y_pred, _, _ = string_labeled_classification_problem
pos_label = "cancer" assert clf.classes_[0] == pos_label
score_pos_cancer = score_func(y_test, y_pred, pos_label="cancer") score_pos_not_cancer = score_func(y_test, y_pred, pos_label="not cancer")
assert score_pos_cancer != pytest.approx(score_pos_not_cancer)
scorer = make_scorer(score_func, pos_label=pos_label) assert scorer(clf, X_test, y_test) == pytest.approx(score_pos_cancer)
@pytest.mark.parametrize( "scorer", [ make_scorer(average_precision_score, needs_threshold=True, pos_label="xxx"), make_scorer(brier_score_loss, needs_proba=True, pos_label="xxx"), make_scorer(f1_score, pos_label="xxx"), ], ids=["ThresholdScorer", "ProbaScorer", "PredictScorer"],)def test_scorer_select_proba_error(scorer): # check that we raise the proper error when passing an unknown # pos_label X, y = make_classification( n_classes=2, n_informative=3, n_samples=20, random_state=0 ) lr = LogisticRegression().fit(X, y) assert scorer._kwargs["pos_label"] not in np.unique(y).tolist()
err_msg = "is not a valid label" with pytest.raises(ValueError, match=err_msg): scorer(lr, X, y)
def test_get_scorer_return_copy(): # test that get_scorer returns a copy assert get_scorer("roc_auc") is not get_scorer("roc_auc")
# TODO(1.3) Removedef test_SCORERS_deprecated(): with pytest.warns(FutureWarning, match="is deprecated and will be removed in v1.3"): SCORERS["roc_auc"]
def test_scorer_no_op_multiclass_select_proba(): # check that calling a ProbaScorer on a multiclass problem do not raise # even if `y_true` would be binary during the scoring. # `_select_proba_binary` should not be called in this case. X, y = make_classification( n_classes=3, n_informative=3, n_samples=20, random_state=0 ) lr = LogisticRegression().fit(X, y)
mask_last_class = y == lr.classes_[-1] X_test, y_test = X[~mask_last_class], y[~mask_last_class] assert_array_equal(np.unique(y_test), lr.classes_[:-1])
scorer = make_scorer( roc_auc_score, needs_proba=True, multi_class="ovo", labels=lr.classes_, ) scorer(lr, X_test, y_test)123456789101112131415161718192021222324252627282930#pragma once
// @generated by torchgen/gen.py from Function.h
#include <ATen/Context.h>#include <ATen/DeviceGuard.h>#include <ATen/TensorUtils.h>#include <ATen/TracerMode.h>#include <ATen/core/Generator.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <optional>
#include <ATen/ops/_cast_Half_ops.h>
namespace at {
// aten::_cast_Half(Tensor self, bool non_blocking=False) -> Tensorinline at::Tensor _cast_Half(const at::Tensor & self, bool non_blocking=false) { return at::_ops::_cast_Half::call(self, non_blocking);}
}123456789101112131415161718192021222324252627282930313233343536373839#pragma once
// @generated by torchgen/gen.py from Operator.h
#include <tuple>#include <vector>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {namespace _ops {
struct TORCH_API _copy_from { using schema = at::Tensor (const at::Tensor &, const at::Tensor &, bool); using ptr_schema = schema*; // See Note [static constexpr char* members for windows NVCC] STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_copy_from") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_copy_from(Tensor self, Tensor dst, bool non_blocking=False) -> Tensor") static at::Tensor call(const at::Tensor & self, const at::Tensor & dst, bool non_blocking); static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & dst, bool non_blocking);};
struct TORCH_API _copy_from_out { using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, bool, at::Tensor &); using ptr_schema = schema*; // See Note [static constexpr char* members for windows NVCC] STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_copy_from") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_copy_from.out(Tensor self, Tensor dst, bool non_blocking=False, *, Tensor(a!) out) -> Tensor(a!)") static at::Tensor & call(const at::Tensor & self, const at::Tensor & dst, bool non_blocking, at::Tensor & out); static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & dst, bool non_blocking, at::Tensor & out);};
}} // namespace at::_ops12345678910111213141516171819202122232425262728#pragma once
// @generated by torchgen/gen.py from Operator.h
#include <tuple>#include <vector>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {namespace _ops {
struct TORCH_API _embedding_bag_backward { using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Tensor &, c10::SymInt, bool, int64_t, bool, const ::std::optional<at::Tensor> &, int64_t); using ptr_schema = schema*; // See Note [static constexpr char* members for windows NVCC] STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_embedding_bag_backward") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_embedding_bag_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, SymInt num_weights, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor") static at::Tensor call(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional<at::Tensor> & per_sample_weights, int64_t padding_idx); static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional<at::Tensor> & per_sample_weights, int64_t padding_idx);};
}} // namespace at::_ops123456789101112131415161718192021222324#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace cpu {
TORCH_API at::Tensor _embedding_bag_dense_backward(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, int64_t num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional<at::Tensor> & per_sample_weights, int64_t padding_idx=-1);TORCH_API at::Tensor _embedding_bag_dense_backward_symint(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional<at::Tensor> & per_sample_weights, int64_t padding_idx=-1);
} // namespace cpu} // namespace at123456789101112131415161718192021222324#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace compositeimplicitautograd {
TORCH_API at::Tensor _embedding_bag_sparse_backward(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, const at::Tensor & bag_size, int64_t num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional<at::Tensor> & per_sample_weights, int64_t padding_idx=-1);TORCH_API at::Tensor _embedding_bag_sparse_backward_symint(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, const at::Tensor & bag_size, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, const ::std::optional<at::Tensor> & per_sample_weights, int64_t padding_idx=-1);
} // namespace compositeimplicitautograd} // namespace at1234567891011121314151617181920212223242526272829303132333435363738394041424344#pragma once
// @generated by torchgen/gen.py from Function.h
#include <ATen/Context.h>#include <ATen/DeviceGuard.h>#include <ATen/TensorUtils.h>#include <ATen/TracerMode.h>#include <ATen/core/Generator.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <optional>
#include <ATen/ops/_foreach_atan_ops.h>
namespace at {
// aten::_foreach_atan(Tensor[] self) -> Tensor[]inline ::std::vector<at::Tensor> _foreach_atan(at::TensorList self) { return at::_ops::_foreach_atan::call(self);}
// aten::_foreach_atan_(Tensor(a!)[] self) -> ()inline void _foreach_atan_(at::TensorList self) { return at::_ops::_foreach_atan_::call(self);}
// aten::_foreach_atan.out(Tensor[] self, *, Tensor(a!)[] out) -> ()inline void _foreach_atan_out(at::TensorList out, at::TensorList self) { return at::_ops::_foreach_atan_out::call(self, out);}// aten::_foreach_atan.out(Tensor[] self, *, Tensor(a!)[] out) -> ()inline void _foreach_atan_outf(at::TensorList self, at::TensorList out) { return at::_ops::_foreach_atan_out::call(self, out);}
}123456789101112131415161718192021222324#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace cuda {
TORCH_API ::std::vector<at::Tensor> _foreach_sigmoid(at::TensorList self);TORCH_API void _foreach_sigmoid_(at::TensorList self);
} // namespace cuda} // namespace at1234567891011121314151617181920212223#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace cuda {
TORCH_API int64_t _fused_sdp_choice(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const ::std::optional<at::Tensor> & attn_mask={}, double dropout_p=0.0, bool is_causal=false, ::std::optional<double> scale=::std::nullopt, bool enable_gqa=false);
} // namespace cuda} // namespace at123456789101112131415161718192021#pragma once
// @generated by torchgen/gen.py from NativeFunction.h
#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <optional>#include <c10/core/QScheme.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <tuple>#include <vector>
namespace at {namespace native {TORCH_API at::Tensor _gather_sparse_backward(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & grad);} // namespace native} // namespace at123456789101112131415161718192021222324252627#pragma once
// @generated by torchgen/gen.py from NativeMetaFunction.h
#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <optional>#include <c10/core/QScheme.h>#include <ATen/core/Reduction.h>#include <ATen/TensorIterator.h>#include <ATen/TensorMeta.h>#include <tuple>#include <vector>
namespace at {namespace meta {
struct TORCH_API structured__linalg_eigh : public at::impl::MetaBase { void meta(const at::Tensor & A, c10::string_view UPLO, bool compute_v);};
} // namespace native} // namespace at123456789101112131415161718192021#pragma once
// @generated by torchgen/gen.py from NativeFunction.h
#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <optional>#include <c10/core/QScheme.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <tuple>#include <vector>
namespace at {namespace native {TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _lu_with_info(const at::Tensor & self, bool pivot=true, bool check_errors=true);} // namespace native} // namespace at123456789101112131415161718192021222324252627282930#pragma once
// @generated by torchgen/gen.py from Function.h
#include <ATen/Context.h>#include <ATen/DeviceGuard.h>#include <ATen/TensorUtils.h>#include <ATen/TracerMode.h>#include <ATen/core/Generator.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <optional>
#include <ATen/ops/_prelu_kernel_backward_ops.h>
namespace at {
// aten::_prelu_kernel_backward(Tensor grad_output, Tensor self, Tensor weight) -> (Tensor, Tensor)inline ::std::tuple<at::Tensor,at::Tensor> _prelu_kernel_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & weight) { return at::_ops::_prelu_kernel_backward::call(grad_output, self, weight);}
}123456789101112131415161718192021222324#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace cpu {
TORCH_API at::Tensor _reshape_alias(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride);TORCH_API at::Tensor _reshape_alias_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride);
} // namespace cpu} // namespace at12345678910111213141516171819202122232425262728#pragma once
// @generated by torchgen/gen.py from Operator.h
#include <tuple>#include <vector>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {namespace _ops {
struct TORCH_API _thnn_differentiable_lstm_cell_backward { using schema = ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> (const ::std::optional<at::Tensor> &, const ::std::optional<at::Tensor> &, const at::Tensor &, const at::Tensor &, const ::std::optional<at::Tensor> &, const ::std::optional<at::Tensor> &, const at::Tensor &, const at::Tensor &); using ptr_schema = schema*; // See Note [static constexpr char* members for windows NVCC] STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_thnn_differentiable_lstm_cell_backward") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_thnn_differentiable_lstm_cell_backward(Tensor? grad_hy, Tensor? grad_cy, Tensor input_gates, Tensor hidden_gates, Tensor? input_bias, Tensor? hidden_bias, Tensor cx, Tensor cy) -> (Tensor, Tensor, Tensor, Tensor, Tensor)") static ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> call(const ::std::optional<at::Tensor> & grad_hy, const ::std::optional<at::Tensor> & grad_cy, const at::Tensor & input_gates, const at::Tensor & hidden_gates, const ::std::optional<at::Tensor> & input_bias, const ::std::optional<at::Tensor> & hidden_bias, const at::Tensor & cx, const at::Tensor & cy); static ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const ::std::optional<at::Tensor> & grad_hy, const ::std::optional<at::Tensor> & grad_cy, const at::Tensor & input_gates, const at::Tensor & hidden_gates, const ::std::optional<at::Tensor> & input_bias, const ::std::optional<at::Tensor> & hidden_bias, const at::Tensor & cx, const at::Tensor & cy);};
}} // namespace at::_ops12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091#pragma once
// @generated by torchgen/gen.py from Function.h
#include <ATen/Context.h>#include <ATen/DeviceGuard.h>#include <ATen/TensorUtils.h>#include <ATen/TracerMode.h>#include <ATen/core/Generator.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <optional>
#include <ATen/ops/_upsample_bilinear2d_aa_backward_ops.h>
namespace at {
// aten::_upsample_bilinear2d_aa_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)inline at::Tensor & _upsample_bilinear2d_aa_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt) { return at::_ops::_upsample_bilinear2d_aa_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w, grad_input);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>> at::Tensor & _upsample_bilinear2d_aa_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt) { return at::_ops::_upsample_bilinear2d_aa_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w, grad_input); }}
// aten::_upsample_bilinear2d_aa_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)inline at::Tensor & _upsample_bilinear2d_aa_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h, ::std::optional<double> scales_w, at::Tensor & grad_input) { return at::_ops::_upsample_bilinear2d_aa_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w, grad_input);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>> at::Tensor & _upsample_bilinear2d_aa_backward_outf(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h, ::std::optional<double> scales_w, at::Tensor & grad_input) { return at::_ops::_upsample_bilinear2d_aa_backward_grad_input::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w, grad_input); }}
// aten::_upsample_bilinear2d_aa_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)inline at::Tensor & _upsample_bilinear2d_aa_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt) { return at::_ops::_upsample_bilinear2d_aa_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w, grad_input);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>> at::Tensor & _upsample_bilinear2d_aa_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt) { return at::_ops::_upsample_bilinear2d_aa_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w, grad_input); }}
// aten::_upsample_bilinear2d_aa_backward.grad_input(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!)inline at::Tensor & _upsample_bilinear2d_aa_backward_symint_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h, ::std::optional<double> scales_w, at::Tensor & grad_input) { return at::_ops::_upsample_bilinear2d_aa_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w, grad_input);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>> at::Tensor & _upsample_bilinear2d_aa_backward_outf(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h, ::std::optional<double> scales_w, at::Tensor & grad_input) { return at::_ops::_upsample_bilinear2d_aa_backward_grad_input::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w, grad_input); }}
// aten::_upsample_bilinear2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensorinline at::Tensor _upsample_bilinear2d_aa_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt) { return at::_ops::_upsample_bilinear2d_aa_backward::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>> at::Tensor _upsample_bilinear2d_aa_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt) { return at::_ops::_upsample_bilinear2d_aa_backward::call(grad_output, c10::fromIntArrayRefSlow(output_size), c10::fromIntArrayRefSlow(input_size), align_corners, scales_h, scales_w); }}
// aten::_upsample_bilinear2d_aa_backward(Tensor grad_output, SymInt[2] output_size, SymInt[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensorinline at::Tensor _upsample_bilinear2d_aa_backward_symint(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt) { return at::_ops::_upsample_bilinear2d_aa_backward::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w);}namespace symint { template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>> at::Tensor _upsample_bilinear2d_aa_backward(const at::Tensor & grad_output, c10::SymIntArrayRef output_size, c10::SymIntArrayRef input_size, bool align_corners, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt) { return at::_ops::_upsample_bilinear2d_aa_backward::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w); }}
}1234567891011121314151617181920212223#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace compositeimplicitautograd {
TORCH_API at::Tensor _wrapped_quantized_linear_prepacked(const at::Tensor & input, const at::Tensor & input_scale, const at::Tensor & input_zero_point, const at::Tensor & packed_weight, const at::Tensor & output_scale, const at::Tensor & output_zero_point, int64_t out_channel);
} // namespace compositeimplicitautograd} // namespace at123456789101112131415161718192021222324252627282930313233343536373839#pragma once
// @generated by torchgen/gen.py from Function.h
#include <ATen/Context.h>#include <ATen/DeviceGuard.h>#include <ATen/TensorUtils.h>#include <ATen/TracerMode.h>#include <ATen/core/Generator.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <optional>
#include <ATen/ops/absolute_ops.h>
namespace at {
// aten::absolute(Tensor self) -> Tensorinline at::Tensor absolute(const at::Tensor & self) { return at::_ops::absolute::call(self);}
// aten::absolute.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)inline at::Tensor & absolute_out(at::Tensor & out, const at::Tensor & self) { return at::_ops::absolute_out::call(self, out);}// aten::absolute.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)inline at::Tensor & absolute_outf(const at::Tensor & self, at::Tensor & out) { return at::_ops::absolute_out::call(self, out);}
}1234567891011121314151617181920212223242526272829303132333435363738394041424344#pragma once
// @generated by torchgen/gen.py from Function.h
#include <ATen/Context.h>#include <ATen/DeviceGuard.h>#include <ATen/TensorUtils.h>#include <ATen/TracerMode.h>#include <ATen/core/Generator.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <optional>
#include <ATen/ops/asinh_ops.h>
namespace at {
// aten::asinh(Tensor self) -> Tensorinline at::Tensor asinh(const at::Tensor & self) { return at::_ops::asinh::call(self);}
// aten::asinh_(Tensor(a!) self) -> Tensor(a!)inline at::Tensor & asinh_(at::Tensor & self) { return at::_ops::asinh_::call(self);}
// aten::asinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)inline at::Tensor & asinh_out(at::Tensor & out, const at::Tensor & self) { return at::_ops::asinh_out::call(self, out);}// aten::asinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)inline at::Tensor & asinh_outf(const at::Tensor & self, at::Tensor & out) { return at::_ops::asinh_out::call(self, out);}
}1234567891011121314151617181920212223#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace cuda {
TORCH_API ::std::tuple<at::Tensor,at::Tensor> batch_norm_gather_stats(const at::Tensor & input, const at::Tensor & mean, const at::Tensor & invstd, const ::std::optional<at::Tensor> & running_mean, const ::std::optional<at::Tensor> & running_var, double momentum, double eps, int64_t count);
} // namespace cuda} // namespace at123456789101112131415161718192021222324252627282930313233343536373839#pragma once
// @generated by torchgen/gen.py from Function.h
#include <ATen/Context.h>#include <ATen/DeviceGuard.h>#include <ATen/TensorUtils.h>#include <ATen/TracerMode.h>#include <ATen/core/Generator.h>#include <ATen/core/Reduction.h>#include <ATen/core/Tensor.h>#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <optional>
#include <ATen/ops/cholesky_ops.h>
namespace at {
// aten::cholesky.out(Tensor self, bool upper=False, *, Tensor(a!) out) -> Tensor(a!)inline at::Tensor & cholesky_out(at::Tensor & out, const at::Tensor & self, bool upper=false) { return at::_ops::cholesky_out::call(self, upper, out);}// aten::cholesky.out(Tensor self, bool upper=False, *, Tensor(a!) out) -> Tensor(a!)inline at::Tensor & cholesky_outf(const at::Tensor & self, bool upper, at::Tensor & out) { return at::_ops::cholesky_out::call(self, upper, out);}
// aten::cholesky(Tensor self, bool upper=False) -> Tensorinline at::Tensor cholesky(const at::Tensor & self, bool upper=false) { return at::_ops::cholesky::call(self, upper);}
}1234567891011121314151617181920212223242526#pragma once// @generated by torchgen/gen.py from DispatchKeyFunction.h
// NB: The implementing C++ file is RegisterDispatchKey.cpp
// The only #includes we need are for custom classes that have defaults in the C++ API#include <c10/core/MemoryFormat.h>#include <c10/core/Scalar.h>#include <ATen/core/Reduction.h>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {
namespace compositeexplicitautogradnonfunctional {
TORCH_API at::Tensor clamp(const at::Tensor & self, const ::std::optional<at::Scalar> & min, const ::std::optional<at::Scalar> & max=::std::nullopt);TORCH_API at::Tensor & clamp_(at::Tensor & self, const ::std::optional<at::Scalar> & min, const ::std::optional<at::Scalar> & max=::std::nullopt);TORCH_API at::Tensor clamp(const at::Tensor & self, const ::std::optional<at::Tensor> & min={}, const ::std::optional<at::Tensor> & max={});TORCH_API at::Tensor & clamp_(at::Tensor & self, const ::std::optional<at::Tensor> & min={}, const ::std::optional<at::Tensor> & max={});
} // namespace compositeexplicitautogradnonfunctional} // namespace at12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061#pragma once
// @generated by torchgen/gen.py from Operator.h
#include <tuple>#include <vector>
// Forward declarations of any types needed in the operator signatures.// We can't directly include these classes because it will cause circular include dependencies.// This file is included by TensorBody.h, which defines the Tensor class.#include <ATen/core/ATen_fwd.h>
namespace at {namespace _ops {
struct TORCH_API concat { using schema = at::Tensor (at::TensorList, int64_t); using ptr_schema = schema*; // See Note [static constexpr char* members for windows NVCC] STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::concat") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "concat(Tensor[] tensors, int dim=0) -> Tensor") static at::Tensor call(at::TensorList tensors, int64_t dim); static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, int64_t dim);};
struct TORCH_API concat_out { using schema = at::Tensor & (at::TensorList, int64_t, at::Tensor &); using ptr_schema = schema*; // See Note [static constexpr char* members for windows NVCC] STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::concat") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "concat.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!)") static at::Tensor & call(at::TensorList tensors, int64_t dim, at::Tensor & out); static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, int64_t dim, at::Tensor & out);};
struct TORCH_API concat_names { using schema = at::Tensor (at::TensorList, at::Dimname); using ptr_schema = schema*; // See Note [static constexpr char* members for windows NVCC] STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::concat") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "names") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "concat.names(Tensor[] tensors, Dimname dim) -> Tensor") static at::Tensor call(at::TensorList tensors, at::Dimname dim); static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, at::Dimname dim);};
struct TORCH_API concat_names_out { using schema = at::Tensor & (at::TensorList, at::Dimname, at::Tensor &); using ptr_schema = schema*; // See Note [static constexpr char* members for windows NVCC] STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::concat") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "names_out") STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "concat.names_out(Tensor[] tensors, Dimname dim, *, Tensor(a!) out) -> Tensor(a!)") static at::Tensor & call(at::TensorList tensors, at::Dimname dim, at::Tensor & out); static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList tensors, at::Dimname dim, at::Tensor & out);};
}} // namespace at::_ops123456789101112131415161718192021222324252627#pragma once
// @generated by torchgen/gen.py from NativeMetaFunction.h
#include <c10/core/Scalar.h>#include <c10/core/Storage.h>#include <c10/core/TensorOptions.h>#include <c10/util/Deprecated.h>#include <optional>#include <c10/core/QScheme.h>#include <ATen/core/Reduction.h>#include <ATen/TensorIterator.h>#include <ATen/TensorMeta.h>#include <tuple>#include <vector>
namespace at {namespace meta {
struct TORCH_API structured_exp : public TensorIteratorBase { void meta(const at::Tensor & self);};
} // namespace native} // namespace at.gitattributes+1
videollama2/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.cpython-310-x86_64-linux-gnu.soAdded+3
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/base.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_base.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_common_curve_display.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_det_curve_display.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_predict_error_display.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/__init__.pyAdded+48
videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_bicluster.pyAdded+90
videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_supervised.pyAdded+1176
videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_unsupervised.pyAdded+366
videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/__init__.pyAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/__init__.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_classification.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_common.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_dist_metrics.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_pairwise.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_pairwise_distances_reduction.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_ranking.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_regression.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_score_objects.cpython-310.pycAdded
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_classification.pyAdded+2662
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_common.pyAdded+1734
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_dist_metrics.pyAdded+456
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise.pyAdded+1551
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_ranking.pyAdded+2117
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_score_objects.pyAdded+1200
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Half.hAdded+30
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_copy_from_ops.hAdded+39
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_backward_ops.hAdded+28
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_dense_backward_cpu_dispatch.hAdded+24
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_sparse_backward_compositeimplicitautograd_dispatch.hAdded+24
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_atan.hAdded+44
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sigmoid_cuda_dispatch.hAdded+24
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_fused_sdp_choice_cuda_dispatch.hAdded+23
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_gather_sparse_backward_native.hAdded+21
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_eigh_meta.hAdded+27
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_lu_with_info_native.hAdded+21
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_prelu_kernel_backward.hAdded+30
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_reshape_alias_cpu_dispatch.hAdded+24
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_differentiable_lstm_cell_backward_ops.hAdded+28
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bilinear2d_aa_backward.hAdded+91
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_wrapped_quantized_linear_prepacked_compositeimplicitautograd_dispatch.hAdded+23
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/absolute.hAdded+39
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/asinh.hAdded+44
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/batch_norm_gather_stats_cuda_dispatch.hAdded+23
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/cholesky.hAdded+39
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/clamp_compositeexplicitautogradnonfunctional_dispatch.hAdded+26
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/concat_ops.hAdded+61
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/exp_meta.hAdded+27