diff --git a/.gitattributes b/.gitattributes index bcf3e055155d4f42efb29a7d3f7021eeac51873e..bbb36793c9168863abb08bfc45ea1dcea849dd0d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1938,3 +1938,4 @@ videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_red videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text videollama2/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 -text videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d6d53d1b7aa7123d8e7f15ac7b97a06e40566a78 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8a7904e6f8118aa6196cec5b8005c67baf3cc15d81aded7240751d890419498 +size 651001 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/base.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6ecb96994dfe5399644f1fd17590c06798f3969 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/base.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_base.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..077d487fa1bf8754e30a56f2edca08c9d0269625 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_base.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_common_curve_display.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_common_curve_display.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..271052542d8c384dab8cbf906f69fca819571e19 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_common_curve_display.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_det_curve_display.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_det_curve_display.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac55c5a655790e685ef085b9cbf7c98f436f35db Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_det_curve_display.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_predict_error_display.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_predict_error_display.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d7727bdf8aee9cf21f6a256a4792d4e7729baf2 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/test_predict_error_display.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/__init__.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fefb47b11903a2e917b3d3a1e88e9d84866f0f68 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/__init__.py @@ -0,0 +1,48 @@ +""" +The :mod:`sklearn.metrics.cluster` submodule contains evaluation metrics for +cluster 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_score +from ._supervised import normalized_mutual_info_score +from ._supervised import adjusted_rand_score +from ._supervised import rand_score +from ._supervised import completeness_score +from ._supervised import contingency_matrix +from ._supervised import pair_confusion_matrix +from ._supervised import expected_mutual_information +from ._supervised import homogeneity_completeness_v_measure +from ._supervised import homogeneity_score +from ._supervised import mutual_info_score +from ._supervised import v_measure_score +from ._supervised import fowlkes_mallows_score +from ._supervised import entropy +from ._unsupervised import silhouette_samples +from ._unsupervised import silhouette_score +from ._unsupervised import calinski_harabasz_score +from ._unsupervised import davies_bouldin_score +from ._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", +] diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_bicluster.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_bicluster.py new file mode 100644 index 0000000000000000000000000000000000000000..eef311afcf463545da2fd775f9a1b94bc358bdc4 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_bicluster.py @@ -0,0 +1,90 @@ +import numpy as np +from 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 `. + + 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 + `__. + """ + 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) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_supervised.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_supervised.py new file mode 100644 index 0000000000000000000000000000000000000000..eb91862de14fbb8215edfcfc43d1123c6964813a --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_supervised.py @@ -0,0 +1,1176 @@ +"""Utilities to evaluate the clustering performance of models. + +Functions named as *_score return a scalar value to maximize: the higher the +better. +""" + +# Authors: Olivier Grisel +# Wei LI +# Diego Molla +# Arnaud Fouchet +# Thierry Guillemot +# Gregory Stupp +# Joel Nothman +# Arya McCarthy +# Uwe F Mayer +# License: BSD 3 clause + + +import warnings +from math import log + +import numpy as np +from scipy import sparse as sp + +from ._expected_mutual_info_fast import expected_mutual_information +from ...utils.multiclass import type_of_target +from ...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 `. + + 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 `. + + 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 + `_ + + .. [3] `Wikipedia: 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 `. + + 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 `. + + 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 `. + + 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 + `_ + + 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 `. + + 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 + `_ + + 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 `. + + 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 + `_ + + 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 `. + + 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 `. + + 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 + `_ + + .. [2] `Wikipedia entry for the 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 `. + + 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 `. + + 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 + `_ + + .. [2] `Wikipedia entry for the 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))) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_unsupervised.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_unsupervised.py new file mode 100644 index 0000000000000000000000000000000000000000..3c25330cde707c7916f616d89a42453914531013 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_unsupervised.py @@ -0,0 +1,366 @@ +"""Unsupervised evaluation metrics.""" + +# Authors: Robert Layton +# Arnaud Fouchet +# Thierry Guillemot +# License: BSD 3 clause + + +import functools + +import numpy as np + +from ...utils import check_random_state +from ...utils import check_X_y +from ...utils import _safe_indexing +from ..pairwise import pairwise_distances_chunked +from ..pairwise import pairwise_distances +from ...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 `. + + 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 + `. 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 `. + + **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. + `_ + + .. [2] `Wikipedia entry on the Silhouette Coefficient + `_ + """ + 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 `. + + 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. + `_ + + .. [2] `Wikipedia entry on the Silhouette Coefficient + `_ + """ + 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 `. + + 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 + `_ + """ + 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 `. + + .. 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" + `__. + 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) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/__init__.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39ebe52a9fb053b3108de28629058d5273409a81 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_classification.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_classification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4b4de9dccaf53a9ebfca9b17519f99ecf697034 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_classification.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_common.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d56cb0642fa6a1630b99e945c0b60274e091187 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_common.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_dist_metrics.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_dist_metrics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2336fff2b7f22429f11b5d8b1e5f952d2ff66bab Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_dist_metrics.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_pairwise.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_pairwise.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a64670415a439eb18a7747c724a25eb9b95f9f5 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_pairwise.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_pairwise_distances_reduction.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_pairwise_distances_reduction.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea09011608d961ffbdb98cdddcf2ee599ef7042d Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_pairwise_distances_reduction.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_ranking.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_ranking.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb5fcf54693996249dc4ad6f9fde90f1ba09cfd5 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_ranking.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_regression.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_regression.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8776f9ab7c7e05373513cd251b30acc89b46c4bf Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_regression.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_score_objects.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_score_objects.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d2f0db7947ba46b9509502d17b6235dde340752 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__pycache__/test_score_objects.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_classification.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..91826584f6797351bbd4e912599ce021cef55072 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_classification.py @@ -0,0 +1,2662 @@ +from functools import partial +from itertools import product +from itertools import chain +from itertools import permutations +import warnings +import re + +import numpy as np +from scipy import linalg +from scipy.stats import bernoulli +import pytest + +from sklearn import datasets +from sklearn import svm + +from sklearn.datasets import make_multilabel_classification +from sklearn.preprocessing import label_binarize, LabelBinarizer +from sklearn.utils.validation import check_random_state +from sklearn.utils._testing import assert_almost_equal +from sklearn.utils._testing import assert_array_equal +from sklearn.utils._testing import assert_array_almost_equal +from sklearn.utils._testing import assert_allclose +from sklearn.utils._testing import assert_no_warnings +from sklearn.utils._testing import ignore_warnings +from sklearn.utils._mocking import MockDataFrame + +from sklearn.metrics import accuracy_score +from sklearn.metrics import average_precision_score +from sklearn.metrics import balanced_accuracy_score +from sklearn.metrics import class_likelihood_ratios +from sklearn.metrics import classification_report +from sklearn.metrics import cohen_kappa_score +from sklearn.metrics import confusion_matrix +from sklearn.metrics import f1_score +from sklearn.metrics import fbeta_score +from sklearn.metrics import hamming_loss +from sklearn.metrics import hinge_loss +from sklearn.metrics import jaccard_score +from sklearn.metrics import log_loss +from sklearn.metrics import matthews_corrcoef +from sklearn.metrics import precision_recall_fscore_support +from sklearn.metrics import precision_score +from sklearn.metrics import recall_score +from sklearn.metrics import zero_one_loss +from sklearn.metrics import brier_score_loss +from sklearn.metrics import multilabel_confusion_matrix + +from sklearn.metrics._classification import _check_targets +from 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_warnings +def 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_warnings +def 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_warnings +def 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_warnings +def 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 75 +weighted 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 9 +weighted 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 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_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 75 +weighted 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 75 +weighted 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 75 +weighted 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 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_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 24 +greengreengreengreengreen 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_warnings +def 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 104 +weighted 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_warnings +def 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_warnings +def 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) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_common.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_common.py new file mode 100644 index 0000000000000000000000000000000000000000..335803c0ba383cdef587966364f3ef6bcef41026 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_common.py @@ -0,0 +1,1734 @@ +from functools import partial +from inspect import signature +from itertools import product +from itertools import chain +from itertools import permutations + +import numpy as np +import scipy.sparse as sp + +import pytest + +from sklearn.datasets import make_multilabel_classification +from sklearn.preprocessing import LabelBinarizer +from sklearn.utils.multiclass import type_of_target +from sklearn.utils.validation import _num_samples +from sklearn.utils.validation import check_random_state +from sklearn.utils import shuffle + +from sklearn.utils._testing import assert_allclose +from sklearn.utils._testing import assert_almost_equal +from sklearn.utils._testing import assert_array_equal +from sklearn.utils._testing import assert_array_less +from sklearn.utils._testing import ignore_warnings + +from sklearn.metrics import accuracy_score +from sklearn.metrics import average_precision_score +from sklearn.metrics import balanced_accuracy_score +from sklearn.metrics import brier_score_loss +from sklearn.metrics import cohen_kappa_score +from sklearn.metrics import confusion_matrix +from sklearn.metrics import coverage_error +from sklearn.metrics import d2_tweedie_score +from sklearn.metrics import d2_pinball_score +from sklearn.metrics import d2_absolute_error_score +from sklearn.metrics import det_curve +from sklearn.metrics import explained_variance_score +from sklearn.metrics import f1_score +from sklearn.metrics import fbeta_score +from sklearn.metrics import hamming_loss +from sklearn.metrics import hinge_loss +from sklearn.metrics import jaccard_score +from sklearn.metrics import label_ranking_average_precision_score +from sklearn.metrics import label_ranking_loss +from sklearn.metrics import log_loss +from sklearn.metrics import max_error +from sklearn.metrics import matthews_corrcoef +from sklearn.metrics import mean_absolute_error +from sklearn.metrics import mean_absolute_percentage_error +from sklearn.metrics import mean_squared_error +from sklearn.metrics import mean_tweedie_deviance +from sklearn.metrics import mean_poisson_deviance +from sklearn.metrics import mean_gamma_deviance +from sklearn.metrics import median_absolute_error +from sklearn.metrics import multilabel_confusion_matrix +from sklearn.metrics import mean_pinball_loss +from sklearn.metrics import precision_recall_curve +from sklearn.metrics import precision_score +from sklearn.metrics import r2_score +from sklearn.metrics import recall_score +from sklearn.metrics import roc_auc_score +from sklearn.metrics import roc_curve +from sklearn.metrics import zero_one_loss +from sklearn.metrics import ndcg_score +from sklearn.metrics import dcg_score +from 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 inputs +METRIC_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 inputs +METRIC_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" input +METRIC_UNDEFINED_BINARY_MULTICLASS = METRIC_UNDEFINED_BINARY.union( + METRIC_UNDEFINED_MULTICLASS +) + +# Metrics with an "average" argument +METRICS_WITH_AVERAGING = { + "precision_score", + "recall_score", + "f1_score", + "f2_score", + "f0.5_score", + "jaccard_score", +} + +# Threshold-based metrics with an "average" argument +THRESHOLDED_METRICS_WITH_AVERAGING = { + "roc_auc_score", + "average_precision_score", + "partial_roc_auc", +} + +# Metrics with a "pos_label" argument +METRICS_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_loss +METRICS_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" option +METRICS_WITH_NORMALIZE_OPTION = { + "accuracy_score", + "top_k_accuracy_score", + "zero_one_loss", +} + +# Threshold-based metrics with "multilabel-indicator" format support +THRESHOLDED_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" format +MULTILABELS_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 support +MULTIOUTPUT_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 support +METRICS_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_warnings +def 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_warnings +def 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_warnings +def 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_warnings +def 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_warnings +def _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_warnings +def 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_warnings +def 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) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_dist_metrics.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_dist_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..bb95681ebc90e94e08f13e04830f0a1221b6583f --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_dist_metrics.py @@ -0,0 +1,456 @@ +import itertools +import pickle +import copy + +import numpy as np +import pytest + +import scipy.sparse as sp +from scipy.spatial.distance import cdist +from 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_state +from sklearn.utils._testing import assert_allclose, create_memmap_backed_data +from 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 = 4 +n1 = 20 +n2 = 25 +X64 = 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 zeros +X_bool = (X64 < 0.3).astype(np.float64) # quite sparse +Y_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 removed +def 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) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise.py new file mode 100644 index 0000000000000000000000000000000000000000..3624983c4c481aee9116a113d630fa14658b62a4 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise.py @@ -0,0 +1,1551 @@ +import warnings +from types import GeneratorType + +import numpy as np +from numpy import linalg + +from scipy.sparse import dok_matrix, csr_matrix, issparse +from scipy.spatial.distance import cosine, cityblock, minkowski +from scipy.spatial.distance import cdist, pdist, squareform + +try: + from scipy.spatial.distance import wminkowski +except 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_allclose +from sklearn.utils._testing import assert_almost_equal +from sklearn.utils._testing import assert_array_equal +from sklearn.utils._testing import ignore_warnings + +from sklearn.metrics.pairwise import euclidean_distances +from sklearn.metrics.pairwise import nan_euclidean_distances +from sklearn.metrics.pairwise import manhattan_distances +from sklearn.metrics.pairwise import haversine_distances +from sklearn.metrics.pairwise import linear_kernel +from sklearn.metrics.pairwise import chi2_kernel, additive_chi2_kernel +from sklearn.metrics.pairwise import polynomial_kernel +from sklearn.metrics.pairwise import rbf_kernel +from sklearn.metrics.pairwise import laplacian_kernel +from sklearn.metrics.pairwise import sigmoid_kernel +from sklearn.metrics.pairwise import cosine_similarity +from sklearn.metrics.pairwise import cosine_distances +from sklearn.metrics.pairwise import pairwise_distances +from sklearn.metrics.pairwise import pairwise_distances_chunked +from sklearn.metrics.pairwise import pairwise_distances_argmin_min +from sklearn.metrics.pairwise import pairwise_distances_argmin +from sklearn.metrics.pairwise import pairwise_kernels +from sklearn.metrics.pairwise import PAIRWISE_KERNEL_FUNCTIONS +from sklearn.metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS +from sklearn.metrics.pairwise import PAIRWISE_BOOLEAN_FUNCTIONS +from sklearn.metrics.pairwise import PAIRED_DISTANCES +from sklearn.metrics.pairwise import check_pairwise_arrays +from sklearn.metrics.pairwise import check_paired_arrays +from sklearn.metrics.pairwise import paired_distances +from sklearn.metrics.pairwise import paired_euclidean_distances +from sklearn.metrics.pairwise import paired_manhattan_distances +from sklearn.metrics.pairwise import _euclidean_distances_upcast +from sklearn.preprocessing import normalize +from 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_warnings +def 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) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_ranking.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_ranking.py new file mode 100644 index 0000000000000000000000000000000000000000..827c145ed01dc7cf3a8d38397842fc1832d9eacb --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_ranking.py @@ -0,0 +1,2117 @@ +import re +import pytest +import numpy as np +import warnings +from scipy.sparse import csr_matrix +from scipy import stats + +from sklearn import datasets +from sklearn import svm + +from sklearn.utils.extmath import softmax +from sklearn.datasets import make_multilabel_classification +from sklearn.random_projection import _sparse_random_matrix +from sklearn.utils.validation import check_array, check_consistent_length +from sklearn.utils.validation import check_random_state + +from sklearn.utils._testing import assert_allclose +from sklearn.utils._testing import assert_almost_equal +from sklearn.utils._testing import assert_array_equal +from sklearn.utils._testing import assert_array_almost_equal + +from sklearn.metrics import accuracy_score +from sklearn.metrics import auc +from sklearn.metrics import average_precision_score +from sklearn.metrics import coverage_error +from sklearn.metrics import det_curve +from sklearn.metrics import label_ranking_average_precision_score +from sklearn.metrics import precision_recall_curve +from sklearn.metrics import label_ranking_loss +from sklearn.metrics import roc_auc_score +from sklearn.metrics import roc_curve +from sklearn.metrics._ranking import _ndcg_sample_scores, _dcg_sample_scores +from sklearn.metrics import ndcg_score, dcg_score +from sklearn.metrics import top_k_accuracy_score + +from sklearn.exceptions import UndefinedMetricWarning +from sklearn.model_selection import train_test_split +from sklearn.linear_model import LogisticRegression +from 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 + `_ + """ + 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="= 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) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_score_objects.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_score_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..d39db7fc894c4a548fcb4e4381112f9c3ef950c6 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_score_objects.py @@ -0,0 +1,1200 @@ +from copy import deepcopy +import pickle +import tempfile +import shutil +import os +import numbers +from unittest.mock import Mock +from functools import partial + +import numpy as np +import pytest +import joblib + +from numpy.testing import assert_allclose +from sklearn.utils._testing import assert_almost_equal +from sklearn.utils._testing import assert_array_equal +from sklearn.utils._testing import ignore_warnings + +from sklearn.base import BaseEstimator +from 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_module +from sklearn.metrics import check_scoring +from sklearn.metrics._scorer import ( + _PredictScorer, + _passthrough_scorer, + _MultimetricScorer, + _check_multimetric_scoring, +) +from sklearn.metrics import make_scorer, get_scorer, SCORERS, get_scorer_names +from sklearn.neighbors import KNeighborsClassifier +from sklearn.svm import LinearSVC +from sklearn.pipeline import make_pipeline +from sklearn.cluster import KMeans +from sklearn.linear_model import Ridge, LogisticRegression, Perceptron +from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor +from sklearn.datasets import make_blobs +from sklearn.datasets import make_classification, make_regression +from sklearn.datasets import make_multilabel_classification +from sklearn.datasets import load_diabetes +from sklearn.model_selection import train_test_split, cross_val_score +from sklearn.model_selection import GridSearchCV +from 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, None +ESTIMATORS = None +TEMP_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_warnings +def 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_warnings +def 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_warnings +def 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.fixture +def 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) Remove +def 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) diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Half.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Half.h new file mode 100644 index 0000000000000000000000000000000000000000..480574e824967277ede066721b07ac953f1063f7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Half.h @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_cast_Half(Tensor self, bool non_blocking=False) -> Tensor +inline at::Tensor _cast_Half(const at::Tensor & self, bool non_blocking=false) { + return at::_ops::_cast_Half::call(self, non_blocking); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_copy_from_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_copy_from_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..db978e3c878381977c2af867a5a54bd705b49bf4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_copy_from_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// 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 + +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::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_backward_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c7f5006167ff8f2f18855b749cbb8de509c83562 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_backward_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// 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 + +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 &, 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 & 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 & per_sample_weights, int64_t padding_idx); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_dense_backward_cpu_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_dense_backward_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..2e00716e84057b7dd7e1ed95825159c490618061 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_dense_backward_cpu_dispatch.h @@ -0,0 +1,24 @@ +#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 +#include +#include + +// 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 + +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 & 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 & per_sample_weights, int64_t padding_idx=-1); + +} // namespace cpu +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_sparse_backward_compositeimplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_sparse_backward_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..74e4428242d52f45e00854a6b1d889e1a5e6b11d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_sparse_backward_compositeimplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#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 +#include +#include + +// 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 + +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 & 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 & per_sample_weights, int64_t padding_idx=-1); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_atan.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_atan.h new file mode 100644 index 0000000000000000000000000000000000000000..34e9132247e0864a678d161fab633a458b0d4b0e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_atan.h @@ -0,0 +1,44 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_foreach_atan(Tensor[] self) -> Tensor[] +inline ::std::vector _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); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sigmoid_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sigmoid_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b68e7a8e08e3a904427aabc12c4a3ca08c57025c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sigmoid_cuda_dispatch.h @@ -0,0 +1,24 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace cuda { + +TORCH_API ::std::vector _foreach_sigmoid(at::TensorList self); +TORCH_API void _foreach_sigmoid_(at::TensorList self); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_fused_sdp_choice_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_fused_sdp_choice_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..99f23759cdf0624396805c487e2d4e1ec56788ee --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_fused_sdp_choice_cuda_dispatch.h @@ -0,0 +1,23 @@ +#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 +#include +#include + +// 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 + +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 & attn_mask={}, double dropout_p=0.0, bool is_causal=false, ::std::optional scale=::std::nullopt, bool enable_gqa=false); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_gather_sparse_backward_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_gather_sparse_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..69cf3dbd06982e289d42828323aa48768f99d1b4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_gather_sparse_backward_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +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 at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_eigh_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_eigh_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..25f9bdb45c6b71f7db6471b8ce2619daffe2b7bb --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_linalg_eigh_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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 at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_lu_with_info_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_lu_with_info_native.h new file mode 100644 index 0000000000000000000000000000000000000000..fbae1e8da573dd2c0cca4fec597d5b8fe17a72db --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_lu_with_info_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple _lu_with_info(const at::Tensor & self, bool pivot=true, bool check_errors=true); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_prelu_kernel_backward.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_prelu_kernel_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..62c2e4d9a3536e1e71f8f9a3cb624f8eca46ca5e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_prelu_kernel_backward.h @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_prelu_kernel_backward(Tensor grad_output, Tensor self, Tensor weight) -> (Tensor, Tensor) +inline ::std::tuple _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); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_reshape_alias_cpu_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_reshape_alias_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c09e7f54ba192b7b8694bdedc5b957c853951fc2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_reshape_alias_cpu_dispatch.h @@ -0,0 +1,24 @@ +#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 +#include +#include + +// 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 + +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 at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_differentiable_lstm_cell_backward_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_differentiable_lstm_cell_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..476c3fbd665fcfa4e5517264150d8f1b1de7f6cc --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_differentiable_lstm_cell_backward_ops.h @@ -0,0 +1,28 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// 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 + +namespace at { +namespace _ops { + + +struct TORCH_API _thnn_differentiable_lstm_cell_backward { + using schema = ::std::tuple (const ::std::optional &, const ::std::optional &, const at::Tensor &, const at::Tensor &, const ::std::optional &, const ::std::optional &, 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 call(const ::std::optional & grad_hy, const ::std::optional & grad_cy, const at::Tensor & input_gates, const at::Tensor & hidden_gates, const ::std::optional & input_bias, const ::std::optional & hidden_bias, const at::Tensor & cx, const at::Tensor & cy); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const ::std::optional & grad_hy, const ::std::optional & grad_cy, const at::Tensor & input_gates, const at::Tensor & hidden_gates, const ::std::optional & input_bias, const ::std::optional & hidden_bias, const at::Tensor & cx, const at::Tensor & cy); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bilinear2d_aa_backward.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bilinear2d_aa_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..bbddbc9322e5f2be7bec8c26c76a001905b6e625 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bilinear2d_aa_backward.h @@ -0,0 +1,91 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +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 scales_h=::std::nullopt, ::std::optional 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 ::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 scales_h=::std::nullopt, ::std::optional 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 scales_h, ::std::optional 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 ::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 scales_h, ::std::optional 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 scales_h=::std::nullopt, ::std::optional 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 ::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 scales_h=::std::nullopt, ::std::optional 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 scales_h, ::std::optional 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 ::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 scales_h, ::std::optional 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) -> Tensor +inline at::Tensor _upsample_bilinear2d_aa_backward(const at::Tensor & grad_output, at::IntArrayRef output_size, at::IntArrayRef input_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional 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 ::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 scales_h=::std::nullopt, ::std::optional 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) -> Tensor +inline 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 scales_h=::std::nullopt, ::std::optional 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 ::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 scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt) { + return at::_ops::_upsample_bilinear2d_aa_backward::call(grad_output, output_size, input_size, align_corners, scales_h, scales_w); + } +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_wrapped_quantized_linear_prepacked_compositeimplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_wrapped_quantized_linear_prepacked_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..ec730f9835741ed334a01bd9b723309b47a33759 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_wrapped_quantized_linear_prepacked_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#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 +#include +#include + +// 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 + +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 at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/absolute.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/absolute.h new file mode 100644 index 0000000000000000000000000000000000000000..ed93ba9ae555a055e34622820a3a8b627812447b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/absolute.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::absolute(Tensor self) -> Tensor +inline 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); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/asinh.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/asinh.h new file mode 100644 index 0000000000000000000000000000000000000000..1637cb1225bda457398c42c452ba32bb4f045815 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/asinh.h @@ -0,0 +1,44 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::asinh(Tensor self) -> Tensor +inline 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); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/batch_norm_gather_stats_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/batch_norm_gather_stats_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..4ce786f8cbffaa66f213c6be844363a6da1a4be8 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/batch_norm_gather_stats_cuda_dispatch.h @@ -0,0 +1,23 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple batch_norm_gather_stats(const at::Tensor & input, const at::Tensor & mean, const at::Tensor & invstd, const ::std::optional & running_mean, const ::std::optional & running_var, double momentum, double eps, int64_t count); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/cholesky.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/cholesky.h new file mode 100644 index 0000000000000000000000000000000000000000..014812ded08d582bdcca4e22d0c058cc6f655d4b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/cholesky.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +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) -> Tensor +inline at::Tensor cholesky(const at::Tensor & self, bool upper=false) { + return at::_ops::cholesky::call(self, upper); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/clamp_compositeexplicitautogradnonfunctional_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/clamp_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..7457b61df7061093fc3889ad4a2045a2532ba370 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/clamp_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,26 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor clamp(const at::Tensor & self, const ::std::optional & min, const ::std::optional & max=::std::nullopt); +TORCH_API at::Tensor & clamp_(at::Tensor & self, const ::std::optional & min, const ::std::optional & max=::std::nullopt); +TORCH_API at::Tensor clamp(const at::Tensor & self, const ::std::optional & min={}, const ::std::optional & max={}); +TORCH_API at::Tensor & clamp_(at::Tensor & self, const ::std::optional & min={}, const ::std::optional & max={}); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/concat_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/concat_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..2dcdbbd066d8ec8a4c3c5e3a5e4474079d4d24cc --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/concat_ops.h @@ -0,0 +1,61 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// 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 + +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::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/exp_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/exp_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..c19b9a83649278d041fa7534ed83f13631f2c1fc --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/exp_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_exp : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/expm1.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/expm1.h new file mode 100644 index 0000000000000000000000000000000000000000..d730175b7e3b6769028ceb4cc3b3f8c486b086d0 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/expm1.h @@ -0,0 +1,44 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::expm1(Tensor self) -> Tensor +inline at::Tensor expm1(const at::Tensor & self) { + return at::_ops::expm1::call(self); +} + +// aten::expm1_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & expm1_(at::Tensor & self) { + return at::_ops::expm1_::call(self); +} + +// aten::expm1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & expm1_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::expm1_out::call(self, out); +} +// aten::expm1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & expm1_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::expm1_out::call(self, out); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fake_quantize_per_channel_affine_cachemask_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fake_quantize_per_channel_affine_cachemask_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..3758201c755cdaf3e0d04e0eacb533969e1e4392 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fake_quantize_per_channel_affine_cachemask_compositeexplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API ::std::tuple fake_quantize_per_channel_affine_cachemask_out(at::Tensor & out0, at::Tensor & out1, const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, int64_t axis, int64_t quant_min, int64_t quant_max); +TORCH_API ::std::tuple fake_quantize_per_channel_affine_cachemask_outf(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, int64_t axis, int64_t quant_min, int64_t quant_max, at::Tensor & out0, at::Tensor & out1); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/floor_compositeexplicitautogradnonfunctional_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/floor_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..add8e67dd2cfc29ef7a6533c46619132417d4aac --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/floor_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,24 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor floor(const at::Tensor & self); +TORCH_API at::Tensor & floor_(at::Tensor & self); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fmin_meta_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fmin_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b7c1a54fe39fcfd062131299d3fc28a37372cd6a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fmin_meta_dispatch.h @@ -0,0 +1,25 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace meta { + +TORCH_API at::Tensor fmin(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & fmin_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & fmin_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + +} // namespace meta +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fractional_max_pool3d_backward_cpu_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fractional_max_pool3d_backward_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1282e3cfbddbe76d8cd749edb64cb28ed8a0a336 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fractional_max_pool3d_backward_cpu_dispatch.h @@ -0,0 +1,25 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor fractional_max_pool3d_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices); +TORCH_API at::Tensor & fractional_max_pool3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices); +TORCH_API at::Tensor & fractional_max_pool3d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices, at::Tensor & grad_input); + +} // namespace cpu +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/ge_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/ge_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..31d7d4adbbf922df5553a89357895981a9fa2822 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/ge_cuda_dispatch.h @@ -0,0 +1,30 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor ge(const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & ge_out(at::Tensor & out, const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor & ge_outf(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +TORCH_API at::Tensor & ge_(at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor ge(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & ge_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & ge_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & ge_(at::Tensor & self, const at::Tensor & other); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/hardtanh_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/hardtanh_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..00c64aa87a9c6a290b8681053625ec3fa275d978 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/hardtanh_ops.h @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// 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 + +namespace at { +namespace _ops { + + +struct TORCH_API hardtanh_out { + using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::hardtanh") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "hardtanh.out(Tensor self, Scalar min_val=-1, Scalar max_val=1, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val, at::Tensor & out); +}; + +struct TORCH_API hardtanh { + using schema = at::Tensor (const at::Tensor &, const at::Scalar &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::hardtanh") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "hardtanh(Tensor self, Scalar min_val=-1, Scalar max_val=1) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val); +}; + +struct TORCH_API hardtanh_ { + using schema = at::Tensor & (at::Tensor &, const at::Scalar &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::hardtanh_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "hardtanh_(Tensor(a!) self, Scalar min_val=-1, Scalar max_val=1) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & min_val, const at::Scalar & max_val); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_set_to_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_set_to_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..8385c5190105b13d293b910f29f08a0dd5fd3502 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_set_to_cuda_dispatch.h @@ -0,0 +1,23 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace cuda { + +TORCH_API bool is_set_to(const at::Tensor & self, const at::Tensor & tensor); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_lu_factor_ex_cpu_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_lu_factor_ex_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..8089cc19412242c8c06e88b1ef36d425cf2c136c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_lu_factor_ex_cpu_dispatch.h @@ -0,0 +1,25 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace cpu { + +TORCH_API ::std::tuple linalg_lu_factor_ex(const at::Tensor & A, bool pivot=true, bool check_errors=false); +TORCH_API ::std::tuple linalg_lu_factor_ex_out(at::Tensor & LU, at::Tensor & pivots, at::Tensor & info, const at::Tensor & A, bool pivot=true, bool check_errors=false); +TORCH_API ::std::tuple linalg_lu_factor_ex_outf(const at::Tensor & A, bool pivot, bool check_errors, at::Tensor & LU, at::Tensor & pivots, at::Tensor & info); + +} // namespace cpu +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linspace_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linspace_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..963caa8110c12941d59f8250a10d2ac6ffdb759e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linspace_cuda_dispatch.h @@ -0,0 +1,24 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor & linspace_out(at::Tensor & out, const at::Scalar & start, const at::Scalar & end, int64_t steps); +TORCH_API at::Tensor & linspace_outf(const at::Scalar & start, const at::Scalar & end, int64_t steps, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/lshift_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/lshift_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..903c4ffaec4e5e93f105b542f89ea92cd526c2a3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/lshift_ops.h @@ -0,0 +1,83 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// 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 + +namespace at { +namespace _ops { + + +struct TORCH_API __lshift___Scalar { + using schema = at::Tensor (const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::__lshift__") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__lshift__.Scalar(Tensor self, Scalar other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API __lshift___Tensor { + using schema = 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::__lshift__") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__lshift__.Tensor(Tensor self, Tensor other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API __ilshift___Scalar { + using schema = at::Tensor & (at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::__ilshift__") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__ilshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Scalar & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API __ilshift___Tensor { + using schema = at::Tensor & (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::__ilshift__") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__ilshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API __lshift___Scalar_out { + using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::__lshift__") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__lshift__.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +}; + +struct TORCH_API __lshift___Tensor_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::__lshift__") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__lshift__.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/masked_select_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/masked_select_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..2bf8cc436723bc8d0ed4d6a0bce951889fe7b40d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/masked_select_cuda_dispatch.h @@ -0,0 +1,25 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor masked_select(const at::Tensor & self, const at::Tensor & mask); +TORCH_API at::Tensor & masked_select_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & mask); +TORCH_API at::Tensor & masked_select_outf(const at::Tensor & self, const at::Tensor & mask, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/nextafter_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/nextafter_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..f4887af32625ef272f2a52c8976a63319ed15556 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/nextafter_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_nextafter : public TensorIteratorBase { + + + void meta(const at::Tensor & self, const at::Tensor & other); +}; + +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/quantized_rnn_relu_cell_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/quantized_rnn_relu_cell_native.h new file mode 100644 index 0000000000000000000000000000000000000000..13b4aecbd7741cb9cd079a1d68ba7c123bced5c2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/quantized_rnn_relu_cell_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor quantized_rnn_relu_cell(const at::Tensor & input, const at::Tensor & hx, const at::Tensor & w_ih, const at::Tensor & w_hh, const at::Tensor & b_ih, const at::Tensor & b_hh, const at::Tensor & packed_ih, const at::Tensor & packed_hh, const at::Tensor & col_offsets_ih, const at::Tensor & col_offsets_hh, const at::Scalar & scale_ih, const at::Scalar & scale_hh, const at::Scalar & zero_point_ih, const at::Scalar & zero_point_hh); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/renorm_compositeexplicitautogradnonfunctional_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/renorm_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..6bf381dfb06d1ab7c233eca11660dbb2ec017b1c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/renorm_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,24 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor renorm(const at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm); +TORCH_API at::Tensor & renorm_(at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/resolve_conj_compositeimplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/resolve_conj_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..5c8ef8f162daf1c289c3a41d1f831c8b7a543bd1 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/resolve_conj_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor resolve_conj(const at::Tensor & self); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/rrelu_with_noise_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/rrelu_with_noise_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..2f89379a26b8e1782c83e36be69c3116b559184c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/rrelu_with_noise_cuda_dispatch.h @@ -0,0 +1,26 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor rrelu_with_noise(const at::Tensor & self, const at::Tensor & noise, const at::Scalar & lower=0.125, const at::Scalar & upper=0.3333333333333333, bool training=false, ::std::optional generator=::std::nullopt); +TORCH_API at::Tensor & rrelu_with_noise_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & noise, const at::Scalar & lower=0.125, const at::Scalar & upper=0.3333333333333333, bool training=false, ::std::optional generator=::std::nullopt); +TORCH_API at::Tensor & rrelu_with_noise_outf(const at::Tensor & self, const at::Tensor & noise, const at::Scalar & lower, const at::Scalar & upper, bool training, ::std::optional generator, at::Tensor & out); +TORCH_API at::Tensor & rrelu_with_noise_(at::Tensor & self, const at::Tensor & noise, const at::Scalar & lower=0.125, const at::Scalar & upper=0.3333333333333333, bool training=false, ::std::optional generator=::std::nullopt); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/sigmoid_backward_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/sigmoid_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..7cc3d056dd4a43cbaa84b1766f7feeca81968e81 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/sigmoid_backward_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_sigmoid_backward_out : public at::meta::structured_sigmoid_backward { +void impl(const at::Tensor & grad_output, const at::Tensor & output, const at::Tensor & grad_input); +}; +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/slice_copy_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/slice_copy_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..46b0d9be3d79ea607bbc4e8e880ea3f491d3ff12 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/slice_copy_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// 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 + +namespace at { +namespace _ops { + + +struct TORCH_API slice_copy_Tensor { + using schema = at::Tensor (const at::Tensor &, int64_t, ::std::optional, ::std::optional, c10::SymInt); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::slice_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "slice_copy.Tensor(Tensor self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1) -> Tensor") + static at::Tensor call(const at::Tensor & self, int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step); +}; + +struct TORCH_API slice_copy_Tensor_out { + using schema = at::Tensor & (const at::Tensor &, int64_t, ::std::optional, ::std::optional, c10::SymInt, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::slice_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "slice_copy.Tensor_out(Tensor self, int dim=0, SymInt? start=None, SymInt? end=None, SymInt step=1, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, ::std::optional start, ::std::optional end, c10::SymInt step, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_v_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_v_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..285bf9da62f17d1404681e45e4c2dba3d071bf46 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_v_compositeexplicitautograd_dispatch.h @@ -0,0 +1,28 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor special_chebyshev_polynomial_v(const at::Scalar & x, const at::Tensor & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_v_out(at::Tensor & out, const at::Scalar & x, const at::Tensor & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_v_outf(const at::Scalar & x, const at::Tensor & n, at::Tensor & out); +TORCH_API at::Tensor special_chebyshev_polynomial_v(const at::Tensor & x, const at::Scalar & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_v_out(at::Tensor & out, const at::Tensor & x, const at::Scalar & n); +TORCH_API at::Tensor & special_chebyshev_polynomial_v_outf(const at::Tensor & x, const at::Scalar & n, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_w_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_w_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..9b9a5201a03c908bf816a422ca5217b019b99bd9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_w_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_special_chebyshev_polynomial_w : public TensorIteratorBase { + + + void meta(const at::Tensor & x, const at::Tensor & n); +}; + +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_logsumexp_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_logsumexp_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..80dd5a6e407f4940a5cf82918d88a9607b1e1d0d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_logsumexp_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// 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 + +namespace at { +namespace _ops { + + +struct TORCH_API special_logsumexp { + using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_logsumexp") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_logsumexp(Tensor self, int[1] dim, bool keepdim=False) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::IntArrayRef dim, bool keepdim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim, bool keepdim); +}; + +struct TORCH_API special_logsumexp_out { + using schema = at::Tensor & (const at::Tensor &, at::IntArrayRef, 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::special_logsumexp") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_logsumexp.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::IntArrayRef dim, bool keepdim, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim, bool keepdim, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_scaled_modified_bessel_k1_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_scaled_modified_bessel_k1_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..92e91ceca225a1c01c84cb15678ff83361b3b9d1 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_scaled_modified_bessel_k1_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// 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 + +namespace at { +namespace _ops { + + +struct TORCH_API special_scaled_modified_bessel_k1 { + using schema = 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::special_scaled_modified_bessel_k1") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_scaled_modified_bessel_k1(Tensor x) -> Tensor") + static at::Tensor call(const at::Tensor & x); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x); +}; + +struct TORCH_API special_scaled_modified_bessel_k1_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_scaled_modified_bessel_k1") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_scaled_modified_bessel_k1.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & x, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/uniform_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/uniform_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..d320c6372d59bb94bf150f396d6636172a26ea6d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/uniform_compositeexplicitautograd_dispatch.h @@ -0,0 +1,25 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor uniform(const at::Tensor & self, double from=0, double to=1, ::std::optional generator=::std::nullopt); +TORCH_API at::Tensor & uniform_out(at::Tensor & out, const at::Tensor & self, double from=0, double to=1, ::std::optional generator=::std::nullopt); +TORCH_API at::Tensor & uniform_outf(const at::Tensor & self, double from, double to, ::std::optional generator, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/uniform_meta_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/uniform_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..45d14193bf0691b0560665a18ef806eef408d909 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/uniform_meta_dispatch.h @@ -0,0 +1,23 @@ +#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 +#include +#include + +// 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 + +namespace at { + +namespace meta { + +TORCH_API at::Tensor & uniform_(at::Tensor & self, double from=0, double to=1, ::std::optional generator=::std::nullopt); + +} // namespace meta +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/unsqueeze_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/unsqueeze_native.h new file mode 100644 index 0000000000000000000000000000000000000000..a68b7e371dbd706c3e33477cee531ce0b5b40221 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/unsqueeze_native.h @@ -0,0 +1,25 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor unsqueeze(const at::Tensor & self, int64_t dim); +TORCH_API at::Tensor unsqueeze_nested(const at::Tensor & self, int64_t dim); +TORCH_API at::Tensor unsqueeze_sparse(const at::Tensor & self, int64_t dim); +TORCH_API at::Tensor unsqueeze_quantized(const at::Tensor & self, int64_t dim); +TORCH_API at::Tensor & unsqueeze_(at::Tensor & self, int64_t dim); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_nearest2d_backward_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_nearest2d_backward_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..eef0d3653a9d984189567f04a52c95e2ed984891 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_nearest2d_backward_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_upsample_nearest2d_backward : public at::impl::MetaBase { + + + void meta(const at::Tensor & grad_output, at::ArrayRef output_size, at::ArrayRef input_size, ::std::optional scales_h, ::std::optional scales_w); +}; + +} // namespace native +} // namespace at