diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/__init__.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4224bfbb9c04cb62b04d9a1b06e14773cca1ed27 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/__init__.py @@ -0,0 +1,181 @@ +""" +The :mod:`sklearn.metrics` module includes score functions, performance metrics +and pairwise metrics and distance computations. +""" + + +from ._ranking import auc +from ._ranking import average_precision_score +from ._ranking import coverage_error +from ._ranking import det_curve +from ._ranking import dcg_score +from ._ranking import label_ranking_average_precision_score +from ._ranking import label_ranking_loss +from ._ranking import ndcg_score +from ._ranking import precision_recall_curve +from ._ranking import roc_auc_score +from ._ranking import roc_curve +from ._ranking import top_k_accuracy_score + +from ._classification import accuracy_score +from ._classification import balanced_accuracy_score +from ._classification import class_likelihood_ratios +from ._classification import classification_report +from ._classification import cohen_kappa_score +from ._classification import confusion_matrix +from ._classification import f1_score +from ._classification import fbeta_score +from ._classification import hamming_loss +from ._classification import hinge_loss +from ._classification import jaccard_score +from ._classification import log_loss +from ._classification import matthews_corrcoef +from ._classification import precision_recall_fscore_support +from ._classification import precision_score +from ._classification import recall_score +from ._classification import zero_one_loss +from ._classification import brier_score_loss +from ._classification import multilabel_confusion_matrix + +from ._dist_metrics import DistanceMetric + +from . import cluster +from .cluster import adjusted_mutual_info_score +from .cluster import adjusted_rand_score +from .cluster import rand_score +from .cluster import pair_confusion_matrix +from .cluster import completeness_score +from .cluster import consensus_score +from .cluster import homogeneity_completeness_v_measure +from .cluster import homogeneity_score +from .cluster import mutual_info_score +from .cluster import normalized_mutual_info_score +from .cluster import fowlkes_mallows_score +from .cluster import silhouette_samples +from .cluster import silhouette_score +from .cluster import calinski_harabasz_score +from .cluster import v_measure_score +from .cluster import davies_bouldin_score + +from .pairwise import euclidean_distances +from .pairwise import nan_euclidean_distances +from .pairwise import pairwise_distances +from .pairwise import pairwise_distances_argmin +from .pairwise import pairwise_distances_argmin_min +from .pairwise import pairwise_kernels +from .pairwise import pairwise_distances_chunked + +from ._regression import explained_variance_score +from ._regression import max_error +from ._regression import mean_absolute_error +from ._regression import mean_squared_error +from ._regression import mean_squared_log_error +from ._regression import median_absolute_error +from ._regression import mean_absolute_percentage_error +from ._regression import mean_pinball_loss +from ._regression import r2_score +from ._regression import mean_tweedie_deviance +from ._regression import mean_poisson_deviance +from ._regression import mean_gamma_deviance +from ._regression import d2_tweedie_score +from ._regression import d2_pinball_score +from ._regression import d2_absolute_error_score + + +from ._scorer import check_scoring +from ._scorer import make_scorer +from ._scorer import SCORERS +from ._scorer import get_scorer +from ._scorer import get_scorer_names + + +from ._plot.det_curve import DetCurveDisplay +from ._plot.roc_curve import RocCurveDisplay +from ._plot.precision_recall_curve import PrecisionRecallDisplay +from ._plot.confusion_matrix import ConfusionMatrixDisplay +from ._plot.regression import PredictionErrorDisplay + + +__all__ = [ + "accuracy_score", + "adjusted_mutual_info_score", + "adjusted_rand_score", + "auc", + "average_precision_score", + "balanced_accuracy_score", + "calinski_harabasz_score", + "check_scoring", + "class_likelihood_ratios", + "classification_report", + "cluster", + "cohen_kappa_score", + "completeness_score", + "ConfusionMatrixDisplay", + "confusion_matrix", + "consensus_score", + "coverage_error", + "d2_tweedie_score", + "d2_absolute_error_score", + "d2_pinball_score", + "dcg_score", + "davies_bouldin_score", + "DetCurveDisplay", + "det_curve", + "DistanceMetric", + "euclidean_distances", + "explained_variance_score", + "f1_score", + "fbeta_score", + "fowlkes_mallows_score", + "get_scorer", + "hamming_loss", + "hinge_loss", + "homogeneity_completeness_v_measure", + "homogeneity_score", + "jaccard_score", + "label_ranking_average_precision_score", + "label_ranking_loss", + "log_loss", + "make_scorer", + "nan_euclidean_distances", + "matthews_corrcoef", + "max_error", + "mean_absolute_error", + "mean_squared_error", + "mean_squared_log_error", + "mean_pinball_loss", + "mean_poisson_deviance", + "mean_gamma_deviance", + "mean_tweedie_deviance", + "median_absolute_error", + "mean_absolute_percentage_error", + "multilabel_confusion_matrix", + "mutual_info_score", + "ndcg_score", + "normalized_mutual_info_score", + "pair_confusion_matrix", + "pairwise_distances", + "pairwise_distances_argmin", + "pairwise_distances_argmin_min", + "pairwise_distances_chunked", + "pairwise_kernels", + "PrecisionRecallDisplay", + "precision_recall_curve", + "precision_recall_fscore_support", + "precision_score", + "PredictionErrorDisplay", + "r2_score", + "rand_score", + "recall_score", + "RocCurveDisplay", + "roc_auc_score", + "roc_curve", + "SCORERS", + "get_scorer_names", + "silhouette_samples", + "silhouette_score", + "top_k_accuracy_score", + "v_measure_score", + "zero_one_loss", + "brier_score_loss", +] diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_classification.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..9c0f2af92c44d79fef1ad952d1555c6543d56dfa --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_classification.py @@ -0,0 +1,2902 @@ +"""Metrics to assess performance on classification task given class prediction. + +Functions named as ``*_score`` return a scalar value to maximize: the higher +the better. + +Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: +the lower the better. +""" + +# Authors: Alexandre Gramfort +# Mathieu Blondel +# Olivier Grisel +# Arnaud Joly +# Jochen Wersdorfer +# Lars Buitinck +# Joel Nothman +# Noel Dawe +# Jatin Shah +# Saurabh Jha +# Bernardo Stein +# Shangwu Yao +# Michal Karbownik +# License: BSD 3 clause + + +import warnings +import numpy as np + +from scipy.sparse import coo_matrix +from scipy.sparse import csr_matrix +from scipy.special import xlogy + +from ..preprocessing import LabelBinarizer +from ..preprocessing import LabelEncoder +from ..utils import assert_all_finite +from ..utils import check_array +from ..utils import check_consistent_length +from ..utils import column_or_1d +from ..utils.multiclass import unique_labels +from ..utils.multiclass import type_of_target +from ..utils.validation import _num_samples +from ..utils.sparsefuncs import count_nonzero +from ..utils._param_validation import validate_params +from ..exceptions import UndefinedMetricWarning + +from ._base import _check_pos_label_consistency + + +def _check_zero_division(zero_division): + if isinstance(zero_division, str) and zero_division == "warn": + return + elif isinstance(zero_division, (int, float)) and zero_division in [0, 1]: + return + raise ValueError( + 'Got zero_division={0}. Must be one of ["warn", 0, 1]'.format(zero_division) + ) + + +def _check_targets(y_true, y_pred): + """Check that y_true and y_pred belong to the same classification task. + + This converts multiclass or binary types to a common shape, and raises a + ValueError for a mix of multilabel and multiclass targets, a mix of + multilabel formats, for the presence of continuous-valued or multioutput + targets, or for targets of different lengths. + + Column vectors are squeezed to 1d, while multilabel formats are returned + as CSR sparse label indicators. + + Parameters + ---------- + y_true : array-like + + y_pred : array-like + + Returns + ------- + type_true : one of {'multilabel-indicator', 'multiclass', 'binary'} + The type of the true target data, as output by + ``utils.multiclass.type_of_target``. + + y_true : array or indicator matrix + + y_pred : array or indicator matrix + """ + check_consistent_length(y_true, y_pred) + type_true = type_of_target(y_true, input_name="y_true") + type_pred = type_of_target(y_pred, input_name="y_pred") + + y_type = {type_true, type_pred} + if y_type == {"binary", "multiclass"}: + y_type = {"multiclass"} + + if len(y_type) > 1: + raise ValueError( + "Classification metrics can't handle a mix of {0} and {1} targets".format( + type_true, type_pred + ) + ) + + # We can't have more than one value on y_type => The set is no more needed + y_type = y_type.pop() + + # No metrics support "multiclass-multioutput" format + if y_type not in ["binary", "multiclass", "multilabel-indicator"]: + raise ValueError("{0} is not supported".format(y_type)) + + if y_type in ["binary", "multiclass"]: + y_true = column_or_1d(y_true) + y_pred = column_or_1d(y_pred) + if y_type == "binary": + try: + unique_values = np.union1d(y_true, y_pred) + except TypeError as e: + # We expect y_true and y_pred to be of the same data type. + # If `y_true` was provided to the classifier as strings, + # `y_pred` given by the classifier will also be encoded with + # strings. So we raise a meaningful error + raise TypeError( + "Labels in y_true and y_pred should be of the same type. " + f"Got y_true={np.unique(y_true)} and " + f"y_pred={np.unique(y_pred)}. Make sure that the " + "predictions provided by the classifier coincides with " + "the true labels." + ) from e + if len(unique_values) > 2: + y_type = "multiclass" + + if y_type.startswith("multilabel"): + y_true = csr_matrix(y_true) + y_pred = csr_matrix(y_pred) + y_type = "multilabel-indicator" + + return y_type, y_true, y_pred + + +def _weighted_sum(sample_score, sample_weight, normalize=False): + if normalize: + return np.average(sample_score, weights=sample_weight) + elif sample_weight is not None: + return np.dot(sample_score, sample_weight) + else: + return sample_score.sum() + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_pred": ["array-like", "sparse matrix"], + "normalize": ["boolean"], + "sample_weight": ["array-like", None], + } +) +def accuracy_score(y_true, y_pred, *, normalize=True, sample_weight=None): + """Accuracy classification score. + + In multilabel classification, this function computes subset accuracy: + the set of labels predicted for a sample must *exactly* match the + corresponding set of labels in y_true. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) labels. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Predicted labels, as returned by a classifier. + + normalize : bool, default=True + If ``False``, return the number of correctly classified samples. + Otherwise, return the fraction of correctly classified samples. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + score : float + If ``normalize == True``, return the fraction of correctly + classified samples (float), else returns the number of correctly + classified samples (int). + + The best performance is 1 with ``normalize == True`` and the number + of samples with ``normalize == False``. + + See Also + -------- + balanced_accuracy_score : Compute the balanced accuracy to deal with + imbalanced datasets. + jaccard_score : Compute the Jaccard similarity coefficient score. + hamming_loss : Compute the average Hamming loss or Hamming distance between + two sets of samples. + zero_one_loss : Compute the Zero-one classification loss. By default, the + function will return the percentage of imperfectly predicted subsets. + + Notes + ----- + In binary classification, this function is equal to the `jaccard_score` + function. + + Examples + -------- + >>> from sklearn.metrics import accuracy_score + >>> y_pred = [0, 2, 1, 3] + >>> y_true = [0, 1, 2, 3] + >>> accuracy_score(y_true, y_pred) + 0.5 + >>> accuracy_score(y_true, y_pred, normalize=False) + 2 + + In the multilabel case with binary label indicators: + + >>> import numpy as np + >>> accuracy_score(np.array([[0, 1], [1, 1]]), np.ones((2, 2))) + 0.5 + """ + + # Compute accuracy for each possible representation + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + check_consistent_length(y_true, y_pred, sample_weight) + if y_type.startswith("multilabel"): + differing_labels = count_nonzero(y_true - y_pred, axis=1) + score = differing_labels == 0 + else: + score = y_true == y_pred + + return _weighted_sum(score, sample_weight, normalize) + + +def confusion_matrix( + y_true, y_pred, *, labels=None, sample_weight=None, normalize=None +): + """Compute confusion matrix to evaluate the accuracy of a classification. + + By definition a confusion matrix :math:`C` is such that :math:`C_{i, j}` + is equal to the number of observations known to be in group :math:`i` and + predicted to be in group :math:`j`. + + Thus in binary classification, the count of true negatives is + :math:`C_{0,0}`, false negatives is :math:`C_{1,0}`, true positives is + :math:`C_{1,1}` and false positives is :math:`C_{0,1}`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated targets as returned by a classifier. + + labels : array-like of shape (n_classes), default=None + List of labels to index the matrix. This may be used to reorder + or select a subset of labels. + If ``None`` is given, those that appear at least once + in ``y_true`` or ``y_pred`` are used in sorted order. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 0.18 + + normalize : {'true', 'pred', 'all'}, default=None + Normalizes confusion matrix over the true (rows), predicted (columns) + conditions or all the population. If None, confusion matrix will not be + normalized. + + Returns + ------- + C : ndarray of shape (n_classes, n_classes) + Confusion matrix whose i-th row and j-th + column entry indicates the number of + samples with true label being i-th class + and predicted label being j-th class. + + See Also + -------- + ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix + given an estimator, the data, and the label. + ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix + given the true and predicted labels. + ConfusionMatrixDisplay : Confusion Matrix visualization. + + References + ---------- + .. [1] `Wikipedia entry for the Confusion matrix + `_ + (Wikipedia and other references may use a different + convention for axes). + + Examples + -------- + >>> from sklearn.metrics import confusion_matrix + >>> y_true = [2, 0, 2, 2, 0, 1] + >>> y_pred = [0, 0, 2, 2, 0, 2] + >>> confusion_matrix(y_true, y_pred) + array([[2, 0, 0], + [0, 0, 1], + [1, 0, 2]]) + + >>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"] + >>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"] + >>> confusion_matrix(y_true, y_pred, labels=["ant", "bird", "cat"]) + array([[2, 0, 0], + [0, 0, 1], + [1, 0, 2]]) + + In the binary case, we can extract true positives, etc as follows: + + >>> tn, fp, fn, tp = confusion_matrix([0, 1, 0, 1], [1, 1, 1, 0]).ravel() + >>> (tn, fp, fn, tp) + (0, 2, 1, 1) + """ + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + if y_type not in ("binary", "multiclass"): + raise ValueError("%s is not supported" % y_type) + + if labels is None: + labels = unique_labels(y_true, y_pred) + else: + labels = np.asarray(labels) + n_labels = labels.size + if n_labels == 0: + raise ValueError("'labels' should contains at least one label.") + elif y_true.size == 0: + return np.zeros((n_labels, n_labels), dtype=int) + elif len(np.intersect1d(y_true, labels)) == 0: + raise ValueError("At least one label specified must be in y_true") + + if sample_weight is None: + sample_weight = np.ones(y_true.shape[0], dtype=np.int64) + else: + sample_weight = np.asarray(sample_weight) + + check_consistent_length(y_true, y_pred, sample_weight) + + if normalize not in ["true", "pred", "all", None]: + raise ValueError("normalize must be one of {'true', 'pred', 'all', None}") + + n_labels = labels.size + # If labels are not consecutive integers starting from zero, then + # y_true and y_pred must be converted into index form + need_index_conversion = not ( + labels.dtype.kind in {"i", "u", "b"} + and np.all(labels == np.arange(n_labels)) + and y_true.min() >= 0 + and y_pred.min() >= 0 + ) + if need_index_conversion: + label_to_ind = {y: x for x, y in enumerate(labels)} + y_pred = np.array([label_to_ind.get(x, n_labels + 1) for x in y_pred]) + y_true = np.array([label_to_ind.get(x, n_labels + 1) for x in y_true]) + + # intersect y_pred, y_true with labels, eliminate items not in labels + ind = np.logical_and(y_pred < n_labels, y_true < n_labels) + if not np.all(ind): + y_pred = y_pred[ind] + y_true = y_true[ind] + # also eliminate weights of eliminated items + sample_weight = sample_weight[ind] + + # Choose the accumulator dtype to always have high precision + if sample_weight.dtype.kind in {"i", "u", "b"}: + dtype = np.int64 + else: + dtype = np.float64 + + cm = coo_matrix( + (sample_weight, (y_true, y_pred)), + shape=(n_labels, n_labels), + dtype=dtype, + ).toarray() + + with np.errstate(all="ignore"): + if normalize == "true": + cm = cm / cm.sum(axis=1, keepdims=True) + elif normalize == "pred": + cm = cm / cm.sum(axis=0, keepdims=True) + elif normalize == "all": + cm = cm / cm.sum() + cm = np.nan_to_num(cm) + + return cm + + +def multilabel_confusion_matrix( + y_true, y_pred, *, sample_weight=None, labels=None, samplewise=False +): + """Compute a confusion matrix for each class or sample. + + .. versionadded:: 0.21 + + Compute class-wise (default) or sample-wise (samplewise=True) multilabel + confusion matrix to evaluate the accuracy of a classification, and output + confusion matrices for each class or sample. + + In multilabel confusion matrix :math:`MCM`, the count of true negatives + is :math:`MCM_{:,0,0}`, false negatives is :math:`MCM_{:,1,0}`, + true positives is :math:`MCM_{:,1,1}` and false positives is + :math:`MCM_{:,0,1}`. + + Multiclass data will be treated as if binarized under a one-vs-rest + transformation. Returned confusion matrices will be in the order of + sorted unique labels in the union of (y_true, y_pred). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : {array-like, sparse matrix} of shape (n_samples, n_outputs) or \ + (n_samples,) + Ground truth (correct) target values. + + y_pred : {array-like, sparse matrix} of shape (n_samples, n_outputs) or \ + (n_samples,) + Estimated targets as returned by a classifier. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + labels : array-like of shape (n_classes,), default=None + A list of classes or column indices to select some (or to force + inclusion of classes absent from the data). + + samplewise : bool, default=False + In the multilabel case, this calculates a confusion matrix per sample. + + Returns + ------- + multi_confusion : ndarray of shape (n_outputs, 2, 2) + A 2x2 confusion matrix corresponding to each output in the input. + When calculating class-wise multi_confusion (default), then + n_outputs = n_labels; when calculating sample-wise multi_confusion + (samplewise=True), n_outputs = n_samples. If ``labels`` is defined, + the results will be returned in the order specified in ``labels``, + otherwise the results will be returned in sorted order by default. + + See Also + -------- + confusion_matrix : Compute confusion matrix to evaluate the accuracy of a + classifier. + + Notes + ----- + The `multilabel_confusion_matrix` calculates class-wise or sample-wise + multilabel confusion matrices, and in multiclass tasks, labels are + binarized under a one-vs-rest way; while + :func:`~sklearn.metrics.confusion_matrix` calculates one confusion matrix + for confusion between every two classes. + + Examples + -------- + Multilabel-indicator case: + + >>> import numpy as np + >>> from sklearn.metrics import multilabel_confusion_matrix + >>> y_true = np.array([[1, 0, 1], + ... [0, 1, 0]]) + >>> y_pred = np.array([[1, 0, 0], + ... [0, 1, 1]]) + >>> multilabel_confusion_matrix(y_true, y_pred) + array([[[1, 0], + [0, 1]], + + [[1, 0], + [0, 1]], + + [[0, 1], + [1, 0]]]) + + Multiclass case: + + >>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"] + >>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"] + >>> multilabel_confusion_matrix(y_true, y_pred, + ... labels=["ant", "bird", "cat"]) + array([[[3, 1], + [0, 2]], + + [[5, 0], + [1, 0]], + + [[2, 1], + [1, 2]]]) + """ + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + if sample_weight is not None: + sample_weight = column_or_1d(sample_weight) + check_consistent_length(y_true, y_pred, sample_weight) + + if y_type not in ("binary", "multiclass", "multilabel-indicator"): + raise ValueError("%s is not supported" % y_type) + + present_labels = unique_labels(y_true, y_pred) + if labels is None: + labels = present_labels + n_labels = None + else: + n_labels = len(labels) + labels = np.hstack( + [labels, np.setdiff1d(present_labels, labels, assume_unique=True)] + ) + + if y_true.ndim == 1: + if samplewise: + raise ValueError( + "Samplewise metrics are not available outside of " + "multilabel classification." + ) + + le = LabelEncoder() + le.fit(labels) + y_true = le.transform(y_true) + y_pred = le.transform(y_pred) + sorted_labels = le.classes_ + + # labels are now from 0 to len(labels) - 1 -> use bincount + tp = y_true == y_pred + tp_bins = y_true[tp] + if sample_weight is not None: + tp_bins_weights = np.asarray(sample_weight)[tp] + else: + tp_bins_weights = None + + if len(tp_bins): + tp_sum = np.bincount( + tp_bins, weights=tp_bins_weights, minlength=len(labels) + ) + else: + # Pathological case + true_sum = pred_sum = tp_sum = np.zeros(len(labels)) + if len(y_pred): + pred_sum = np.bincount(y_pred, weights=sample_weight, minlength=len(labels)) + if len(y_true): + true_sum = np.bincount(y_true, weights=sample_weight, minlength=len(labels)) + + # Retain only selected labels + indices = np.searchsorted(sorted_labels, labels[:n_labels]) + tp_sum = tp_sum[indices] + true_sum = true_sum[indices] + pred_sum = pred_sum[indices] + + else: + sum_axis = 1 if samplewise else 0 + + # All labels are index integers for multilabel. + # Select labels: + if not np.array_equal(labels, present_labels): + if np.max(labels) > np.max(present_labels): + raise ValueError( + "All labels must be in [0, n labels) for " + "multilabel targets. " + "Got %d > %d" % (np.max(labels), np.max(present_labels)) + ) + if np.min(labels) < 0: + raise ValueError( + "All labels must be in [0, n labels) for " + "multilabel targets. " + "Got %d < 0" + % np.min(labels) + ) + + if n_labels is not None: + y_true = y_true[:, labels[:n_labels]] + y_pred = y_pred[:, labels[:n_labels]] + + # calculate weighted counts + true_and_pred = y_true.multiply(y_pred) + tp_sum = count_nonzero( + true_and_pred, axis=sum_axis, sample_weight=sample_weight + ) + pred_sum = count_nonzero(y_pred, axis=sum_axis, sample_weight=sample_weight) + true_sum = count_nonzero(y_true, axis=sum_axis, sample_weight=sample_weight) + + fp = pred_sum - tp_sum + fn = true_sum - tp_sum + tp = tp_sum + + if sample_weight is not None and samplewise: + sample_weight = np.array(sample_weight) + tp = np.array(tp) + fp = np.array(fp) + fn = np.array(fn) + tn = sample_weight * y_true.shape[1] - tp - fp - fn + elif sample_weight is not None: + tn = sum(sample_weight) - tp - fp - fn + elif samplewise: + tn = y_true.shape[1] - tp - fp - fn + else: + tn = y_true.shape[0] - tp - fp - fn + + return np.array([tn, fp, fn, tp]).T.reshape(-1, 2, 2) + + +def cohen_kappa_score(y1, y2, *, labels=None, weights=None, sample_weight=None): + r"""Compute Cohen's kappa: a statistic that measures inter-annotator agreement. + + This function computes Cohen's kappa [1]_, a score that expresses the level + of agreement between two annotators on a classification problem. It is + defined as + + .. math:: + \kappa = (p_o - p_e) / (1 - p_e) + + where :math:`p_o` is the empirical probability of agreement on the label + assigned to any sample (the observed agreement ratio), and :math:`p_e` is + the expected agreement when both annotators assign labels randomly. + :math:`p_e` is estimated using a per-annotator empirical prior over the + class labels [2]_. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y1 : array of shape (n_samples,) + Labels assigned by the first annotator. + + y2 : array of shape (n_samples,) + Labels assigned by the second annotator. The kappa statistic is + symmetric, so swapping ``y1`` and ``y2`` doesn't change the value. + + labels : array-like of shape (n_classes,), default=None + List of labels to index the matrix. This may be used to select a + subset of labels. If `None`, all labels that appear at least once in + ``y1`` or ``y2`` are used. + + weights : {'linear', 'quadratic'}, default=None + Weighting type to calculate the score. `None` means no weighted; + "linear" means linear weighted; "quadratic" means quadratic weighted. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + kappa : float + The kappa statistic, which is a number between -1 and 1. The maximum + value means complete agreement; zero or lower means chance agreement. + + References + ---------- + .. [1] :doi:`J. Cohen (1960). "A coefficient of agreement for nominal scales". + Educational and Psychological Measurement 20(1):37-46. + <10.1177/001316446002000104>` + .. [2] `R. Artstein and M. Poesio (2008). "Inter-coder agreement for + computational linguistics". Computational Linguistics 34(4):555-596 + `_. + .. [3] `Wikipedia entry for the Cohen's kappa + `_. + """ + confusion = confusion_matrix(y1, y2, labels=labels, sample_weight=sample_weight) + n_classes = confusion.shape[0] + sum0 = np.sum(confusion, axis=0) + sum1 = np.sum(confusion, axis=1) + expected = np.outer(sum0, sum1) / np.sum(sum0) + + if weights is None: + w_mat = np.ones([n_classes, n_classes], dtype=int) + w_mat.flat[:: n_classes + 1] = 0 + elif weights == "linear" or weights == "quadratic": + w_mat = np.zeros([n_classes, n_classes], dtype=int) + w_mat += np.arange(n_classes) + if weights == "linear": + w_mat = np.abs(w_mat - w_mat.T) + else: + w_mat = (w_mat - w_mat.T) ** 2 + else: + raise ValueError("Unknown kappa weighting type.") + + k = np.sum(w_mat * confusion) / np.sum(w_mat * expected) + return 1 - k + + +def jaccard_score( + y_true, + y_pred, + *, + labels=None, + pos_label=1, + average="binary", + sample_weight=None, + zero_division="warn", +): + """Jaccard similarity coefficient score. + + The Jaccard index [1], or Jaccard similarity coefficient, defined as + the size of the intersection divided by the size of the union of two label + sets, is used to compare set of predicted labels for a sample to the + corresponding set of labels in ``y_true``. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) labels. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Predicted labels, as returned by a classifier. + + labels : array-like of shape (n_classes,), default=None + The set of labels to include when ``average != 'binary'``, and their + order if ``average is None``. Labels present in the data can be + excluded, for example to calculate a multiclass average ignoring a + majority negative class, while labels not present in the data will + result in 0 components in a macro average. For multilabel targets, + labels are column indices. By default, all labels in ``y_true`` and + ``y_pred`` are used in sorted order. + + pos_label : str or int, default=1 + The class to report if ``average='binary'`` and the data is binary. + If the data are multiclass or multilabel, this will be ignored; + setting ``labels=[pos_label]`` and ``average != 'binary'`` will report + scores for that label only. + + average : {'micro', 'macro', 'samples', 'weighted', \ + 'binary'} or None, default='binary' + If ``None``, the scores for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average, weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + zero_division : "warn", {0.0, 1.0}, default="warn" + Sets the value to return when there is a zero division, i.e. when there + there are no negative values in predictions and labels. If set to + "warn", this acts like 0, but a warning is also raised. + + Returns + ------- + score : float or ndarray of shape (n_unique_labels,), dtype=np.float64 + The Jaccard score. When `average` is not `None`, a single scalar is + returned. + + See Also + -------- + accuracy_score : Function for calculating the accuracy score. + f1_score : Function for calculating the F1 score. + multilabel_confusion_matrix : Function for computing a confusion matrix\ + for each class or sample. + + Notes + ----- + :func:`jaccard_score` may be a poor metric if there are no + positives for some samples or classes. Jaccard is undefined if there are + no true or predicted labels, and our implementation will return a score + of 0 with a warning. + + References + ---------- + .. [1] `Wikipedia entry for the Jaccard index + `_. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import jaccard_score + >>> y_true = np.array([[0, 1, 1], + ... [1, 1, 0]]) + >>> y_pred = np.array([[1, 1, 1], + ... [1, 0, 0]]) + + In the binary case: + + >>> jaccard_score(y_true[0], y_pred[0]) + 0.6666... + + In the 2D comparison case (e.g. image similarity): + + >>> jaccard_score(y_true, y_pred, average="micro") + 0.6 + + In the multilabel case: + + >>> jaccard_score(y_true, y_pred, average='samples') + 0.5833... + >>> jaccard_score(y_true, y_pred, average='macro') + 0.6666... + >>> jaccard_score(y_true, y_pred, average=None) + array([0.5, 0.5, 1. ]) + + In the multiclass case: + + >>> y_pred = [0, 2, 1, 2] + >>> y_true = [0, 1, 2, 2] + >>> jaccard_score(y_true, y_pred, average=None) + array([1. , 0. , 0.33...]) + """ + labels = _check_set_wise_labels(y_true, y_pred, average, labels, pos_label) + samplewise = average == "samples" + MCM = multilabel_confusion_matrix( + y_true, + y_pred, + sample_weight=sample_weight, + labels=labels, + samplewise=samplewise, + ) + numerator = MCM[:, 1, 1] + denominator = MCM[:, 1, 1] + MCM[:, 0, 1] + MCM[:, 1, 0] + + if average == "micro": + numerator = np.array([numerator.sum()]) + denominator = np.array([denominator.sum()]) + + jaccard = _prf_divide( + numerator, + denominator, + "jaccard", + "true or predicted", + average, + ("jaccard",), + zero_division=zero_division, + ) + if average is None: + return jaccard + if average == "weighted": + weights = MCM[:, 1, 0] + MCM[:, 1, 1] + if not np.any(weights): + # numerator is 0, and warning should have already been issued + weights = None + elif average == "samples" and sample_weight is not None: + weights = sample_weight + else: + weights = None + return np.average(jaccard, weights=weights) + + +def matthews_corrcoef(y_true, y_pred, *, sample_weight=None): + """Compute the Matthews correlation coefficient (MCC). + + The Matthews correlation coefficient is used in machine learning as a + measure of the quality of binary and multiclass classifications. It takes + into account true and false positives and negatives and is generally + regarded as a balanced measure which can be used even if the classes are of + very different sizes. The MCC is in essence a correlation coefficient value + between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 + an average random prediction and -1 an inverse prediction. The statistic + is also known as the phi coefficient. [source: Wikipedia] + + Binary and multiclass labels are supported. Only in the binary case does + this relate to information about true and false positives and negatives. + See references below. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array, shape = [n_samples] + Ground truth (correct) target values. + + y_pred : array, shape = [n_samples] + Estimated targets as returned by a classifier. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 0.18 + + Returns + ------- + mcc : float + The Matthews correlation coefficient (+1 represents a perfect + prediction, 0 an average random prediction and -1 and inverse + prediction). + + References + ---------- + .. [1] :doi:`Baldi, Brunak, Chauvin, Andersen and Nielsen, (2000). Assessing the + accuracy of prediction algorithms for classification: an overview. + <10.1093/bioinformatics/16.5.412>` + + .. [2] `Wikipedia entry for the Matthews Correlation Coefficient + `_. + + .. [3] `Gorodkin, (2004). Comparing two K-category assignments by a + K-category correlation coefficient + `_. + + .. [4] `Jurman, Riccadonna, Furlanello, (2012). A Comparison of MCC and CEN + Error Measures in MultiClass Prediction + `_. + + Examples + -------- + >>> from sklearn.metrics import matthews_corrcoef + >>> y_true = [+1, +1, +1, -1] + >>> y_pred = [+1, -1, +1, +1] + >>> matthews_corrcoef(y_true, y_pred) + -0.33... + """ + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + check_consistent_length(y_true, y_pred, sample_weight) + if y_type not in {"binary", "multiclass"}: + raise ValueError("%s is not supported" % y_type) + + lb = LabelEncoder() + lb.fit(np.hstack([y_true, y_pred])) + y_true = lb.transform(y_true) + y_pred = lb.transform(y_pred) + + C = confusion_matrix(y_true, y_pred, sample_weight=sample_weight) + t_sum = C.sum(axis=1, dtype=np.float64) + p_sum = C.sum(axis=0, dtype=np.float64) + n_correct = np.trace(C, dtype=np.float64) + n_samples = p_sum.sum() + cov_ytyp = n_correct * n_samples - np.dot(t_sum, p_sum) + cov_ypyp = n_samples**2 - np.dot(p_sum, p_sum) + cov_ytyt = n_samples**2 - np.dot(t_sum, t_sum) + + if cov_ypyp * cov_ytyt == 0: + return 0.0 + else: + return cov_ytyp / np.sqrt(cov_ytyt * cov_ypyp) + + +def zero_one_loss(y_true, y_pred, *, normalize=True, sample_weight=None): + """Zero-one classification loss. + + If normalize is ``True``, return the fraction of misclassifications + (float), else it returns the number of misclassifications (int). The best + performance is 0. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) labels. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Predicted labels, as returned by a classifier. + + normalize : bool, default=True + If ``False``, return the number of misclassifications. + Otherwise, return the fraction of misclassifications. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + loss : float or int, + If ``normalize == True``, return the fraction of misclassifications + (float), else it returns the number of misclassifications (int). + + See Also + -------- + accuracy_score : Compute the accuracy score. By default, the function will + return the fraction of correct predictions divided by the total number + of predictions. + hamming_loss : Compute the average Hamming loss or Hamming distance between + two sets of samples. + jaccard_score : Compute the Jaccard similarity coefficient score. + + Notes + ----- + In multilabel classification, the zero_one_loss function corresponds to + the subset zero-one loss: for each sample, the entire set of labels must be + correctly predicted, otherwise the loss for that sample is equal to one. + + Examples + -------- + >>> from sklearn.metrics import zero_one_loss + >>> y_pred = [1, 2, 3, 4] + >>> y_true = [2, 2, 3, 4] + >>> zero_one_loss(y_true, y_pred) + 0.25 + >>> zero_one_loss(y_true, y_pred, normalize=False) + 1 + + In the multilabel case with binary label indicators: + + >>> import numpy as np + >>> zero_one_loss(np.array([[0, 1], [1, 1]]), np.ones((2, 2))) + 0.5 + """ + score = accuracy_score( + y_true, y_pred, normalize=normalize, sample_weight=sample_weight + ) + + if normalize: + return 1 - score + else: + if sample_weight is not None: + n_samples = np.sum(sample_weight) + else: + n_samples = _num_samples(y_true) + return n_samples - score + + +def f1_score( + y_true, + y_pred, + *, + labels=None, + pos_label=1, + average="binary", + sample_weight=None, + zero_division="warn", +): + """Compute the F1 score, also known as balanced F-score or F-measure. + + The F1 score can be interpreted as a harmonic mean of the precision and + recall, where an F1 score reaches its best value at 1 and worst score at 0. + The relative contribution of precision and recall to the F1 score are + equal. The formula for the F1 score is:: + + F1 = 2 * (precision * recall) / (precision + recall) + + In the multi-class and multi-label case, this is the average of + the F1 score of each class with weighting depending on the ``average`` + parameter. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array-like, default=None + The set of labels to include when ``average != 'binary'``, and their + order if ``average is None``. Labels present in the data can be + excluded, for example to calculate a multiclass average ignoring a + majority negative class, while labels not present in the data will + result in 0 components in a macro average. For multilabel targets, + labels are column indices. By default, all labels in ``y_true`` and + ``y_pred`` are used in sorted order. + + .. versionchanged:: 0.17 + Parameter `labels` improved for multiclass problem. + + pos_label : str or int, default=1 + The class to report if ``average='binary'`` and the data is binary. + If the data are multiclass or multilabel, this will be ignored; + setting ``labels=[pos_label]`` and ``average != 'binary'`` will report + scores for that label only. + + average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ + default='binary' + This parameter is required for multiclass/multilabel targets. + If ``None``, the scores for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + zero_division : "warn", 0 or 1, default="warn" + Sets the value to return when there is a zero division, i.e. when all + predictions and labels are negative. If set to "warn", this acts as 0, + but warnings are also raised. + + Returns + ------- + f1_score : float or array of float, shape = [n_unique_labels] + F1 score of the positive class in binary classification or weighted + average of the F1 scores of each class for the multiclass task. + + See Also + -------- + fbeta_score : Compute the F-beta score. + precision_recall_fscore_support : Compute the precision, recall, F-score, + and support. + jaccard_score : Compute the Jaccard similarity coefficient score. + multilabel_confusion_matrix : Compute a confusion matrix for each class or + sample. + + Notes + ----- + When ``true positive + false positive == 0``, precision is undefined. + When ``true positive + false negative == 0``, recall is undefined. + In such cases, by default the metric will be set to 0, as will f-score, + and ``UndefinedMetricWarning`` will be raised. This behavior can be + modified with ``zero_division``. + + References + ---------- + .. [1] `Wikipedia entry for the F1-score + `_. + + Examples + -------- + >>> from sklearn.metrics import f1_score + >>> y_true = [0, 1, 2, 0, 1, 2] + >>> y_pred = [0, 2, 1, 0, 0, 1] + >>> f1_score(y_true, y_pred, average='macro') + 0.26... + >>> f1_score(y_true, y_pred, average='micro') + 0.33... + >>> f1_score(y_true, y_pred, average='weighted') + 0.26... + >>> f1_score(y_true, y_pred, average=None) + array([0.8, 0. , 0. ]) + >>> y_true = [0, 0, 0, 0, 0, 0] + >>> y_pred = [0, 0, 0, 0, 0, 0] + >>> f1_score(y_true, y_pred, zero_division=1) + 1.0... + >>> # multilabel classification + >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] + >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] + >>> f1_score(y_true, y_pred, average=None) + array([0.66666667, 1. , 0.66666667]) + """ + return fbeta_score( + y_true, + y_pred, + beta=1, + labels=labels, + pos_label=pos_label, + average=average, + sample_weight=sample_weight, + zero_division=zero_division, + ) + + +def fbeta_score( + y_true, + y_pred, + *, + beta, + labels=None, + pos_label=1, + average="binary", + sample_weight=None, + zero_division="warn", +): + """Compute the F-beta score. + + The F-beta score is the weighted harmonic mean of precision and recall, + reaching its optimal value at 1 and its worst value at 0. + + The `beta` parameter determines the weight of recall in the combined + score. ``beta < 1`` lends more weight to precision, while ``beta > 1`` + favors recall (``beta -> 0`` considers only precision, ``beta -> +inf`` + only recall). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + beta : float + Determines the weight of recall in the combined score. + + labels : array-like, default=None + The set of labels to include when ``average != 'binary'``, and their + order if ``average is None``. Labels present in the data can be + excluded, for example to calculate a multiclass average ignoring a + majority negative class, while labels not present in the data will + result in 0 components in a macro average. For multilabel targets, + labels are column indices. By default, all labels in ``y_true`` and + ``y_pred`` are used in sorted order. + + .. versionchanged:: 0.17 + Parameter `labels` improved for multiclass problem. + + pos_label : str or int, default=1 + The class to report if ``average='binary'`` and the data is binary. + If the data are multiclass or multilabel, this will be ignored; + setting ``labels=[pos_label]`` and ``average != 'binary'`` will report + scores for that label only. + + average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ + default='binary' + This parameter is required for multiclass/multilabel targets. + If ``None``, the scores for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + zero_division : "warn", 0 or 1, default="warn" + Sets the value to return when there is a zero division, i.e. when all + predictions and labels are negative. If set to "warn", this acts as 0, + but warnings are also raised. + + Returns + ------- + fbeta_score : float (if average is not None) or array of float, shape =\ + [n_unique_labels] + F-beta score of the positive class in binary classification or weighted + average of the F-beta score of each class for the multiclass task. + + See Also + -------- + precision_recall_fscore_support : Compute the precision, recall, F-score, + and support. + multilabel_confusion_matrix : Compute a confusion matrix for each class or + sample. + + Notes + ----- + When ``true positive + false positive == 0`` or + ``true positive + false negative == 0``, f-score returns 0 and raises + ``UndefinedMetricWarning``. This behavior can be + modified with ``zero_division``. + + References + ---------- + .. [1] R. Baeza-Yates and B. Ribeiro-Neto (2011). + Modern Information Retrieval. Addison Wesley, pp. 327-328. + + .. [2] `Wikipedia entry for the F1-score + `_. + + Examples + -------- + >>> from sklearn.metrics import fbeta_score + >>> y_true = [0, 1, 2, 0, 1, 2] + >>> y_pred = [0, 2, 1, 0, 0, 1] + >>> fbeta_score(y_true, y_pred, average='macro', beta=0.5) + 0.23... + >>> fbeta_score(y_true, y_pred, average='micro', beta=0.5) + 0.33... + >>> fbeta_score(y_true, y_pred, average='weighted', beta=0.5) + 0.23... + >>> fbeta_score(y_true, y_pred, average=None, beta=0.5) + array([0.71..., 0. , 0. ]) + """ + + _, _, f, _ = precision_recall_fscore_support( + y_true, + y_pred, + beta=beta, + labels=labels, + pos_label=pos_label, + average=average, + warn_for=("f-score",), + sample_weight=sample_weight, + zero_division=zero_division, + ) + return f + + +def _prf_divide( + numerator, denominator, metric, modifier, average, warn_for, zero_division="warn" +): + """Performs division and handles divide-by-zero. + + On zero-division, sets the corresponding result elements equal to + 0 or 1 (according to ``zero_division``). Plus, if + ``zero_division != "warn"`` raises a warning. + + The metric, modifier and average arguments are used only for determining + an appropriate warning. + """ + mask = denominator == 0.0 + denominator = denominator.copy() + denominator[mask] = 1 # avoid infs/nans + result = numerator / denominator + + if not np.any(mask): + return result + + # if ``zero_division=1``, set those with denominator == 0 equal to 1 + result[mask] = 0.0 if zero_division in ["warn", 0] else 1.0 + + # the user will be removing warnings if zero_division is set to something + # different than its default value. If we are computing only f-score + # the warning will be raised only if precision and recall are ill-defined + if zero_division != "warn" or metric not in warn_for: + return result + + # build appropriate warning + # E.g. "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." + + if metric in warn_for and "f-score" in warn_for: + msg_start = "{0} and F-score are".format(metric.title()) + elif metric in warn_for: + msg_start = "{0} is".format(metric.title()) + elif "f-score" in warn_for: + msg_start = "F-score is" + else: + return result + + _warn_prf(average, modifier, msg_start, len(result)) + + return result + + +def _warn_prf(average, modifier, msg_start, result_size): + axis0, axis1 = "sample", "label" + if average == "samples": + axis0, axis1 = axis1, axis0 + msg = ( + "{0} ill-defined and being set to 0.0 {{0}} " + "no {1} {2}s. Use `zero_division` parameter to control" + " this behavior.".format(msg_start, modifier, axis0) + ) + if result_size == 1: + msg = msg.format("due to") + else: + msg = msg.format("in {0}s with".format(axis1)) + warnings.warn(msg, UndefinedMetricWarning, stacklevel=2) + + +def _check_set_wise_labels(y_true, y_pred, average, labels, pos_label): + """Validation associated with set-wise metrics. + + Returns identified labels. + """ + average_options = (None, "micro", "macro", "weighted", "samples") + if average not in average_options and average != "binary": + raise ValueError("average has to be one of " + str(average_options)) + + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + # Convert to Python primitive type to avoid NumPy type / Python str + # comparison. See https://github.com/numpy/numpy/issues/6784 + present_labels = unique_labels(y_true, y_pred).tolist() + if average == "binary": + if y_type == "binary": + if pos_label not in present_labels: + if len(present_labels) >= 2: + raise ValueError( + f"pos_label={pos_label} is not a valid label. It " + f"should be one of {present_labels}" + ) + labels = [pos_label] + else: + average_options = list(average_options) + if y_type == "multiclass": + average_options.remove("samples") + raise ValueError( + "Target is %s but average='binary'. Please " + "choose another average setting, one of %r." % (y_type, average_options) + ) + elif pos_label not in (None, 1): + warnings.warn( + "Note that pos_label (set to %r) is ignored when " + "average != 'binary' (got %r). You may use " + "labels=[pos_label] to specify a single positive class." + % (pos_label, average), + UserWarning, + ) + return labels + + +def precision_recall_fscore_support( + y_true, + y_pred, + *, + beta=1.0, + labels=None, + pos_label=1, + average=None, + warn_for=("precision", "recall", "f-score"), + sample_weight=None, + zero_division="warn", +): + """Compute precision, recall, F-measure and support for each class. + + The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of + true positives and ``fp`` the number of false positives. The precision is + intuitively the ability of the classifier not to label a negative sample as + positive. + + The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of + true positives and ``fn`` the number of false negatives. The recall is + intuitively the ability of the classifier to find all the positive samples. + + The F-beta score can be interpreted as a weighted harmonic mean of + the precision and recall, where an F-beta score reaches its best + value at 1 and worst score at 0. + + The F-beta score weights recall more than precision by a factor of + ``beta``. ``beta == 1.0`` means recall and precision are equally important. + + The support is the number of occurrences of each class in ``y_true``. + + If ``pos_label is None`` and in binary classification, this function + returns the average precision, recall and F-measure if ``average`` + is one of ``'micro'``, ``'macro'``, ``'weighted'`` or ``'samples'``. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + beta : float, default=1.0 + The strength of recall versus precision in the F-score. + + labels : array-like, default=None + The set of labels to include when ``average != 'binary'``, and their + order if ``average is None``. Labels present in the data can be + excluded, for example to calculate a multiclass average ignoring a + majority negative class, while labels not present in the data will + result in 0 components in a macro average. For multilabel targets, + labels are column indices. By default, all labels in ``y_true`` and + ``y_pred`` are used in sorted order. + + pos_label : str or int, default=1 + The class to report if ``average='binary'`` and the data is binary. + If the data are multiclass or multilabel, this will be ignored; + setting ``labels=[pos_label]`` and ``average != 'binary'`` will report + scores for that label only. + + average : {'binary', 'micro', 'macro', 'samples', 'weighted'}, \ + default=None + If ``None``, the scores for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + warn_for : tuple or set, for internal use + This determines which warnings will be made in the case that this + function is being used to return only one of its metrics. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + zero_division : "warn", 0 or 1, default="warn" + Sets the value to return when there is a zero division: + - recall: when there are no positive labels + - precision: when there are no positive predictions + - f-score: both + + If set to "warn", this acts as 0, but warnings are also raised. + + Returns + ------- + precision : float (if average is not None) or array of float, shape =\ + [n_unique_labels] + Precision score. + + recall : float (if average is not None) or array of float, shape =\ + [n_unique_labels] + Recall score. + + fbeta_score : float (if average is not None) or array of float, shape =\ + [n_unique_labels] + F-beta score. + + support : None (if average is not None) or array of int, shape =\ + [n_unique_labels] + The number of occurrences of each label in ``y_true``. + + Notes + ----- + When ``true positive + false positive == 0``, precision is undefined. + When ``true positive + false negative == 0``, recall is undefined. + In such cases, by default the metric will be set to 0, as will f-score, + and ``UndefinedMetricWarning`` will be raised. This behavior can be + modified with ``zero_division``. + + References + ---------- + .. [1] `Wikipedia entry for the Precision and recall + `_. + + .. [2] `Wikipedia entry for the F1-score + `_. + + .. [3] `Discriminative Methods for Multi-labeled Classification Advances + in Knowledge Discovery and Data Mining (2004), pp. 22-30 by Shantanu + Godbole, Sunita Sarawagi + `_. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import precision_recall_fscore_support + >>> y_true = np.array(['cat', 'dog', 'pig', 'cat', 'dog', 'pig']) + >>> y_pred = np.array(['cat', 'pig', 'dog', 'cat', 'cat', 'dog']) + >>> precision_recall_fscore_support(y_true, y_pred, average='macro') + (0.22..., 0.33..., 0.26..., None) + >>> precision_recall_fscore_support(y_true, y_pred, average='micro') + (0.33..., 0.33..., 0.33..., None) + >>> precision_recall_fscore_support(y_true, y_pred, average='weighted') + (0.22..., 0.33..., 0.26..., None) + + It is possible to compute per-label precisions, recalls, F1-scores and + supports instead of averaging: + + >>> precision_recall_fscore_support(y_true, y_pred, average=None, + ... labels=['pig', 'dog', 'cat']) + (array([0. , 0. , 0.66...]), + array([0., 0., 1.]), array([0. , 0. , 0.8]), + array([2, 2, 2])) + """ + _check_zero_division(zero_division) + if beta < 0: + raise ValueError("beta should be >=0 in the F-beta score") + labels = _check_set_wise_labels(y_true, y_pred, average, labels, pos_label) + + # Calculate tp_sum, pred_sum, true_sum ### + samplewise = average == "samples" + MCM = multilabel_confusion_matrix( + y_true, + y_pred, + sample_weight=sample_weight, + labels=labels, + samplewise=samplewise, + ) + tp_sum = MCM[:, 1, 1] + pred_sum = tp_sum + MCM[:, 0, 1] + true_sum = tp_sum + MCM[:, 1, 0] + + if average == "micro": + tp_sum = np.array([tp_sum.sum()]) + pred_sum = np.array([pred_sum.sum()]) + true_sum = np.array([true_sum.sum()]) + + # Finally, we have all our sufficient statistics. Divide! # + beta2 = beta**2 + + # Divide, and on zero-division, set scores and/or warn according to + # zero_division: + precision = _prf_divide( + tp_sum, pred_sum, "precision", "predicted", average, warn_for, zero_division + ) + recall = _prf_divide( + tp_sum, true_sum, "recall", "true", average, warn_for, zero_division + ) + + # warn for f-score only if zero_division is warn, it is in warn_for + # and BOTH prec and rec are ill-defined + if zero_division == "warn" and ("f-score",) == warn_for: + if (pred_sum[true_sum == 0] == 0).any(): + _warn_prf(average, "true nor predicted", "F-score is", len(true_sum)) + + # if tp == 0 F will be 1 only if all predictions are zero, all labels are + # zero, and zero_division=1. In all other case, 0 + if np.isposinf(beta): + f_score = recall + else: + denom = beta2 * precision + recall + + denom[denom == 0.0] = 1 # avoid division by 0 + f_score = (1 + beta2) * precision * recall / denom + + # Average the results + if average == "weighted": + weights = true_sum + if weights.sum() == 0: + zero_division_value = np.float64(1.0) + if zero_division in ["warn", 0]: + zero_division_value = np.float64(0.0) + # precision is zero_division if there are no positive predictions + # recall is zero_division if there are no positive labels + # fscore is zero_division if all labels AND predictions are + # negative + if pred_sum.sum() == 0: + return ( + zero_division_value, + zero_division_value, + zero_division_value, + None, + ) + else: + return (np.float64(0.0), zero_division_value, np.float64(0.0), None) + + elif average == "samples": + weights = sample_weight + else: + weights = None + + if average is not None: + assert average != "binary" or len(precision) == 1 + precision = np.average(precision, weights=weights) + recall = np.average(recall, weights=weights) + f_score = np.average(f_score, weights=weights) + true_sum = None # return no support + + return precision, recall, f_score, true_sum + + +def class_likelihood_ratios( + y_true, + y_pred, + *, + labels=None, + sample_weight=None, + raise_warning=True, +): + """Compute binary classification positive and negative likelihood ratios. + + The positive likelihood ratio is `LR+ = sensitivity / (1 - specificity)` + where the sensitivity or recall is the ratio `tp / (tp + fn)` and the + specificity is `tn / (tn + fp)`. The negative likelihood ratio is `LR- = (1 + - sensitivity) / specificity`. Here `tp` is the number of true positives, + `fp` the number of false positives, `tn` is the number of true negatives and + `fn` the number of false negatives. Both class likelihood ratios can be used + to obtain post-test probabilities given a pre-test probability. + + `LR+` ranges from 1 to infinity. A `LR+` of 1 indicates that the probability + of predicting the positive class is the same for samples belonging to either + class; therefore, the test is useless. The greater `LR+` is, the more a + positive prediction is likely to be a true positive when compared with the + pre-test probability. A value of `LR+` lower than 1 is invalid as it would + indicate that the odds of a sample being a true positive decrease with + respect to the pre-test odds. + + `LR-` ranges from 0 to 1. The closer it is to 0, the lower the probability + of a given sample to be a false negative. A `LR-` of 1 means the test is + useless because the odds of having the condition did not change after the + test. A value of `LR-` greater than 1 invalidates the classifier as it + indicates an increase in the odds of a sample belonging to the positive + class after being classified as negative. This is the case when the + classifier systematically predicts the opposite of the true label. + + A typical application in medicine is to identify the positive/negative class + to the presence/absence of a disease, respectively; the classifier being a + diagnostic test; the pre-test probability of an individual having the + disease can be the prevalence of such disease (proportion of a particular + population found to be affected by a medical condition); and the post-test + probabilities would be the probability that the condition is truly present + given a positive test result. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array-like, default=None + List of labels to index the matrix. This may be used to select the + positive and negative classes with the ordering `labels=[negative_class, + positive_class]`. If `None` is given, those that appear at least once in + `y_true` or `y_pred` are used in sorted order. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + raise_warning : bool, default=True + Whether or not a case-specific warning message is raised when there is a + zero division. Even if the error is not raised, the function will return + nan in such cases. + + Returns + ------- + (positive_likelihood_ratio, negative_likelihood_ratio) : tuple + A tuple of two float, the first containing the Positive likelihood ratio + and the second the Negative likelihood ratio. + + Warns + ----- + When `false positive == 0`, the positive likelihood ratio is undefined. + When `true negative == 0`, the negative likelihood ratio is undefined. + When `true positive + false negative == 0` both ratios are undefined. + In such cases, `UserWarning` will be raised if raise_warning=True. + + References + ---------- + .. [1] `Wikipedia entry for the Likelihood ratios in diagnostic testing + `_. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import class_likelihood_ratios + >>> class_likelihood_ratios([0, 1, 0, 1, 0], [1, 1, 0, 0, 0]) + (1.5, 0.75) + >>> y_true = np.array(["non-cat", "cat", "non-cat", "cat", "non-cat"]) + >>> y_pred = np.array(["cat", "cat", "non-cat", "non-cat", "non-cat"]) + >>> class_likelihood_ratios(y_true, y_pred) + (1.33..., 0.66...) + >>> y_true = np.array(["non-zebra", "zebra", "non-zebra", "zebra", "non-zebra"]) + >>> y_pred = np.array(["zebra", "zebra", "non-zebra", "non-zebra", "non-zebra"]) + >>> class_likelihood_ratios(y_true, y_pred) + (1.5, 0.75) + + To avoid ambiguities, use the notation `labels=[negative_class, + positive_class]` + + >>> y_true = np.array(["non-cat", "cat", "non-cat", "cat", "non-cat"]) + >>> y_pred = np.array(["cat", "cat", "non-cat", "non-cat", "non-cat"]) + >>> class_likelihood_ratios(y_true, y_pred, labels=["non-cat", "cat"]) + (1.5, 0.75) + """ + + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + if y_type != "binary": + raise ValueError( + "class_likelihood_ratios only supports binary classification " + f"problems, got targets of type: {y_type}" + ) + + cm = confusion_matrix( + y_true, + y_pred, + sample_weight=sample_weight, + labels=labels, + ) + + # Case when `y_test` contains a single class and `y_test == y_pred`. + # This may happen when cross-validating imbalanced data and should + # not be interpreted as a perfect score. + if cm.shape == (1, 1): + msg = "samples of only one class were seen during testing " + if raise_warning: + warnings.warn(msg, UserWarning, stacklevel=2) + positive_likelihood_ratio = np.nan + negative_likelihood_ratio = np.nan + else: + tn, fp, fn, tp = cm.ravel() + support_pos = tp + fn + support_neg = tn + fp + pos_num = tp * support_neg + pos_denom = fp * support_pos + neg_num = fn * support_neg + neg_denom = tn * support_pos + + # If zero division warn and set scores to nan, else divide + if support_pos == 0: + msg = "no samples of the positive class were present in the testing set " + if raise_warning: + warnings.warn(msg, UserWarning, stacklevel=2) + positive_likelihood_ratio = np.nan + negative_likelihood_ratio = np.nan + if fp == 0: + if tp == 0: + msg = "no samples predicted for the positive class" + else: + msg = "positive_likelihood_ratio ill-defined and being set to nan " + if raise_warning: + warnings.warn(msg, UserWarning, stacklevel=2) + positive_likelihood_ratio = np.nan + else: + positive_likelihood_ratio = pos_num / pos_denom + if tn == 0: + msg = "negative_likelihood_ratio ill-defined and being set to nan " + if raise_warning: + warnings.warn(msg, UserWarning, stacklevel=2) + negative_likelihood_ratio = np.nan + else: + negative_likelihood_ratio = neg_num / neg_denom + + return positive_likelihood_ratio, negative_likelihood_ratio + + +def precision_score( + y_true, + y_pred, + *, + labels=None, + pos_label=1, + average="binary", + sample_weight=None, + zero_division="warn", +): + """Compute the precision. + + The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of + true positives and ``fp`` the number of false positives. The precision is + intuitively the ability of the classifier not to label as positive a sample + that is negative. + + The best value is 1 and the worst value is 0. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array-like, default=None + The set of labels to include when ``average != 'binary'``, and their + order if ``average is None``. Labels present in the data can be + excluded, for example to calculate a multiclass average ignoring a + majority negative class, while labels not present in the data will + result in 0 components in a macro average. For multilabel targets, + labels are column indices. By default, all labels in ``y_true`` and + ``y_pred`` are used in sorted order. + + .. versionchanged:: 0.17 + Parameter `labels` improved for multiclass problem. + + pos_label : str or int, default=1 + The class to report if ``average='binary'`` and the data is binary. + If the data are multiclass or multilabel, this will be ignored; + setting ``labels=[pos_label]`` and ``average != 'binary'`` will report + scores for that label only. + + average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ + default='binary' + This parameter is required for multiclass/multilabel targets. + If ``None``, the scores for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + zero_division : "warn", 0 or 1, default="warn" + Sets the value to return when there is a zero division. If set to + "warn", this acts as 0, but warnings are also raised. + + Returns + ------- + precision : float (if average is not None) or array of float of shape \ + (n_unique_labels,) + Precision of the positive class in binary classification or weighted + average of the precision of each class for the multiclass task. + + See Also + -------- + precision_recall_fscore_support : Compute precision, recall, F-measure and + support for each class. + recall_score : Compute the ratio ``tp / (tp + fn)`` where ``tp`` is the + number of true positives and ``fn`` the number of false negatives. + PrecisionRecallDisplay.from_estimator : Plot precision-recall curve given + an estimator and some data. + PrecisionRecallDisplay.from_predictions : Plot precision-recall curve given + binary class predictions. + multilabel_confusion_matrix : Compute a confusion matrix for each class or + sample. + + Notes + ----- + When ``true positive + false positive == 0``, precision returns 0 and + raises ``UndefinedMetricWarning``. This behavior can be + modified with ``zero_division``. + + Examples + -------- + >>> from sklearn.metrics import precision_score + >>> y_true = [0, 1, 2, 0, 1, 2] + >>> y_pred = [0, 2, 1, 0, 0, 1] + >>> precision_score(y_true, y_pred, average='macro') + 0.22... + >>> precision_score(y_true, y_pred, average='micro') + 0.33... + >>> precision_score(y_true, y_pred, average='weighted') + 0.22... + >>> precision_score(y_true, y_pred, average=None) + array([0.66..., 0. , 0. ]) + >>> y_pred = [0, 0, 0, 0, 0, 0] + >>> precision_score(y_true, y_pred, average=None) + array([0.33..., 0. , 0. ]) + >>> precision_score(y_true, y_pred, average=None, zero_division=1) + array([0.33..., 1. , 1. ]) + >>> # multilabel classification + >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] + >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] + >>> precision_score(y_true, y_pred, average=None) + array([0.5, 1. , 1. ]) + """ + p, _, _, _ = precision_recall_fscore_support( + y_true, + y_pred, + labels=labels, + pos_label=pos_label, + average=average, + warn_for=("precision",), + sample_weight=sample_weight, + zero_division=zero_division, + ) + return p + + +def recall_score( + y_true, + y_pred, + *, + labels=None, + pos_label=1, + average="binary", + sample_weight=None, + zero_division="warn", +): + """Compute the recall. + + The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of + true positives and ``fn`` the number of false negatives. The recall is + intuitively the ability of the classifier to find all the positive samples. + + The best value is 1 and the worst value is 0. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array-like, default=None + The set of labels to include when ``average != 'binary'``, and their + order if ``average is None``. Labels present in the data can be + excluded, for example to calculate a multiclass average ignoring a + majority negative class, while labels not present in the data will + result in 0 components in a macro average. For multilabel targets, + labels are column indices. By default, all labels in ``y_true`` and + ``y_pred`` are used in sorted order. + + .. versionchanged:: 0.17 + Parameter `labels` improved for multiclass problem. + + pos_label : str or int, default=1 + The class to report if ``average='binary'`` and the data is binary. + If the data are multiclass or multilabel, this will be ignored; + setting ``labels=[pos_label]`` and ``average != 'binary'`` will report + scores for that label only. + + average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ + default='binary' + This parameter is required for multiclass/multilabel targets. + If ``None``, the scores for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. Weighted recall + is equal to accuracy. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + zero_division : "warn", 0 or 1, default="warn" + Sets the value to return when there is a zero division. If set to + "warn", this acts as 0, but warnings are also raised. + + Returns + ------- + recall : float (if average is not None) or array of float of shape \ + (n_unique_labels,) + Recall of the positive class in binary classification or weighted + average of the recall of each class for the multiclass task. + + See Also + -------- + precision_recall_fscore_support : Compute precision, recall, F-measure and + support for each class. + precision_score : Compute the ratio ``tp / (tp + fp)`` where ``tp`` is the + number of true positives and ``fp`` the number of false positives. + balanced_accuracy_score : Compute balanced accuracy to deal with imbalanced + datasets. + multilabel_confusion_matrix : Compute a confusion matrix for each class or + sample. + PrecisionRecallDisplay.from_estimator : Plot precision-recall curve given + an estimator and some data. + PrecisionRecallDisplay.from_predictions : Plot precision-recall curve given + binary class predictions. + + Notes + ----- + When ``true positive + false negative == 0``, recall returns 0 and raises + ``UndefinedMetricWarning``. This behavior can be modified with + ``zero_division``. + + Examples + -------- + >>> from sklearn.metrics import recall_score + >>> y_true = [0, 1, 2, 0, 1, 2] + >>> y_pred = [0, 2, 1, 0, 0, 1] + >>> recall_score(y_true, y_pred, average='macro') + 0.33... + >>> recall_score(y_true, y_pred, average='micro') + 0.33... + >>> recall_score(y_true, y_pred, average='weighted') + 0.33... + >>> recall_score(y_true, y_pred, average=None) + array([1., 0., 0.]) + >>> y_true = [0, 0, 0, 0, 0, 0] + >>> recall_score(y_true, y_pred, average=None) + array([0.5, 0. , 0. ]) + >>> recall_score(y_true, y_pred, average=None, zero_division=1) + array([0.5, 1. , 1. ]) + >>> # multilabel classification + >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] + >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] + >>> recall_score(y_true, y_pred, average=None) + array([1. , 1. , 0.5]) + """ + _, r, _, _ = precision_recall_fscore_support( + y_true, + y_pred, + labels=labels, + pos_label=pos_label, + average=average, + warn_for=("recall",), + sample_weight=sample_weight, + zero_division=zero_division, + ) + return r + + +def balanced_accuracy_score(y_true, y_pred, *, sample_weight=None, adjusted=False): + """Compute the balanced accuracy. + + The balanced accuracy in binary and multiclass classification problems to + deal with imbalanced datasets. It is defined as the average of recall + obtained on each class. + + The best value is 1 and the worst value is 0 when ``adjusted=False``. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.20 + + Parameters + ---------- + y_true : 1d array-like + Ground truth (correct) target values. + + y_pred : 1d array-like + Estimated targets as returned by a classifier. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + adjusted : bool, default=False + When true, the result is adjusted for chance, so that random + performance would score 0, while keeping perfect performance at a score + of 1. + + Returns + ------- + balanced_accuracy : float + Balanced accuracy score. + + See Also + -------- + average_precision_score : Compute average precision (AP) from prediction + scores. + precision_score : Compute the precision score. + recall_score : Compute the recall score. + roc_auc_score : Compute Area Under the Receiver Operating Characteristic + Curve (ROC AUC) from prediction scores. + + Notes + ----- + Some literature promotes alternative definitions of balanced accuracy. Our + definition is equivalent to :func:`accuracy_score` with class-balanced + sample weights, and shares desirable properties with the binary case. + See the :ref:`User Guide `. + + References + ---------- + .. [1] Brodersen, K.H.; Ong, C.S.; Stephan, K.E.; Buhmann, J.M. (2010). + The balanced accuracy and its posterior distribution. + Proceedings of the 20th International Conference on Pattern + Recognition, 3121-24. + .. [2] John. D. Kelleher, Brian Mac Namee, Aoife D'Arcy, (2015). + `Fundamentals of Machine Learning for Predictive Data Analytics: + Algorithms, Worked Examples, and Case Studies + `_. + + Examples + -------- + >>> from sklearn.metrics import balanced_accuracy_score + >>> y_true = [0, 1, 0, 0, 1, 0] + >>> y_pred = [0, 1, 0, 0, 0, 1] + >>> balanced_accuracy_score(y_true, y_pred) + 0.625 + """ + C = confusion_matrix(y_true, y_pred, sample_weight=sample_weight) + with np.errstate(divide="ignore", invalid="ignore"): + per_class = np.diag(C) / C.sum(axis=1) + if np.any(np.isnan(per_class)): + warnings.warn("y_pred contains classes not in y_true") + per_class = per_class[~np.isnan(per_class)] + score = np.mean(per_class) + if adjusted: + n_classes = len(per_class) + chance = 1 / n_classes + score -= chance + score /= 1 - chance + return score + + +def classification_report( + y_true, + y_pred, + *, + labels=None, + target_names=None, + sample_weight=None, + digits=2, + output_dict=False, + zero_division="warn", +): + """Build a text report showing the main classification metrics. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array-like of shape (n_labels,), default=None + Optional list of label indices to include in the report. + + target_names : list of str of shape (n_labels,), default=None + Optional display names matching the labels (same order). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + digits : int, default=2 + Number of digits for formatting output floating point values. + When ``output_dict`` is ``True``, this will be ignored and the + returned values will not be rounded. + + output_dict : bool, default=False + If True, return output as dict. + + .. versionadded:: 0.20 + + zero_division : "warn", 0 or 1, default="warn" + Sets the value to return when there is a zero division. If set to + "warn", this acts as 0, but warnings are also raised. + + Returns + ------- + report : str or dict + Text summary of the precision, recall, F1 score for each class. + Dictionary returned if output_dict is True. Dictionary has the + following structure:: + + {'label 1': {'precision':0.5, + 'recall':1.0, + 'f1-score':0.67, + 'support':1}, + 'label 2': { ... }, + ... + } + + The reported averages include macro average (averaging the unweighted + mean per label), weighted average (averaging the support-weighted mean + per label), and sample average (only for multilabel classification). + Micro average (averaging the total true positives, false negatives and + false positives) is only shown for multi-label or multi-class + with a subset of classes, because it corresponds to accuracy + otherwise and would be the same for all metrics. + See also :func:`precision_recall_fscore_support` for more details + on averages. + + Note that in binary classification, recall of the positive class + is also known as "sensitivity"; recall of the negative class is + "specificity". + + See Also + -------- + precision_recall_fscore_support: Compute precision, recall, F-measure and + support for each class. + confusion_matrix: Compute confusion matrix to evaluate the accuracy of a + classification. + multilabel_confusion_matrix: Compute a confusion matrix for each class or sample. + + Examples + -------- + >>> from sklearn.metrics import classification_report + >>> y_true = [0, 1, 2, 2, 2] + >>> y_pred = [0, 0, 2, 2, 1] + >>> target_names = ['class 0', 'class 1', 'class 2'] + >>> print(classification_report(y_true, y_pred, target_names=target_names)) + precision recall f1-score support + + class 0 0.50 1.00 0.67 1 + class 1 0.00 0.00 0.00 1 + class 2 1.00 0.67 0.80 3 + + accuracy 0.60 5 + macro avg 0.50 0.56 0.49 5 + weighted avg 0.70 0.60 0.61 5 + + >>> y_pred = [1, 1, 0] + >>> y_true = [1, 1, 1] + >>> print(classification_report(y_true, y_pred, labels=[1, 2, 3])) + precision recall f1-score support + + 1 1.00 0.67 0.80 3 + 2 0.00 0.00 0.00 0 + 3 0.00 0.00 0.00 0 + + micro avg 1.00 0.67 0.80 3 + macro avg 0.33 0.22 0.27 3 + weighted avg 1.00 0.67 0.80 3 + + """ + + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + + if labels is None: + labels = unique_labels(y_true, y_pred) + labels_given = False + else: + labels = np.asarray(labels) + labels_given = True + + # labelled micro average + micro_is_accuracy = (y_type == "multiclass" or y_type == "binary") and ( + not labels_given or (set(labels) == set(unique_labels(y_true, y_pred))) + ) + + if target_names is not None and len(labels) != len(target_names): + if labels_given: + warnings.warn( + "labels size, {0}, does not match size of target_names, {1}".format( + len(labels), len(target_names) + ) + ) + else: + raise ValueError( + "Number of classes, {0}, does not match size of " + "target_names, {1}. Try specifying the labels " + "parameter".format(len(labels), len(target_names)) + ) + if target_names is None: + target_names = ["%s" % l for l in labels] + + headers = ["precision", "recall", "f1-score", "support"] + # compute per-class results without averaging + p, r, f1, s = precision_recall_fscore_support( + y_true, + y_pred, + labels=labels, + average=None, + sample_weight=sample_weight, + zero_division=zero_division, + ) + rows = zip(target_names, p, r, f1, s) + + if y_type.startswith("multilabel"): + average_options = ("micro", "macro", "weighted", "samples") + else: + average_options = ("micro", "macro", "weighted") + + if output_dict: + report_dict = {label[0]: label[1:] for label in rows} + for label, scores in report_dict.items(): + report_dict[label] = dict(zip(headers, [i.item() for i in scores])) + else: + longest_last_line_heading = "weighted avg" + name_width = max(len(cn) for cn in target_names) + width = max(name_width, len(longest_last_line_heading), digits) + head_fmt = "{:>{width}s} " + " {:>9}" * len(headers) + report = head_fmt.format("", *headers, width=width) + report += "\n\n" + row_fmt = "{:>{width}s} " + " {:>9.{digits}f}" * 3 + " {:>9}\n" + for row in rows: + report += row_fmt.format(*row, width=width, digits=digits) + report += "\n" + + # compute all applicable averages + for average in average_options: + if average.startswith("micro") and micro_is_accuracy: + line_heading = "accuracy" + else: + line_heading = average + " avg" + + # compute averages with specified averaging method + avg_p, avg_r, avg_f1, _ = precision_recall_fscore_support( + y_true, + y_pred, + labels=labels, + average=average, + sample_weight=sample_weight, + zero_division=zero_division, + ) + avg = [avg_p, avg_r, avg_f1, np.sum(s)] + + if output_dict: + report_dict[line_heading] = dict(zip(headers, [i.item() for i in avg])) + else: + if line_heading == "accuracy": + row_fmt_accuracy = ( + "{:>{width}s} " + + " {:>9.{digits}}" * 2 + + " {:>9.{digits}f}" + + " {:>9}\n" + ) + report += row_fmt_accuracy.format( + line_heading, "", "", *avg[2:], width=width, digits=digits + ) + else: + report += row_fmt.format(line_heading, *avg, width=width, digits=digits) + + if output_dict: + if "accuracy" in report_dict.keys(): + report_dict["accuracy"] = report_dict["accuracy"]["precision"] + return report_dict + else: + return report + + +def hamming_loss(y_true, y_pred, *, sample_weight=None): + """Compute the average Hamming loss. + + The Hamming loss is the fraction of labels that are incorrectly predicted. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) labels. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Predicted labels, as returned by a classifier. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 0.18 + + Returns + ------- + loss : float or int + Return the average Hamming loss between element of ``y_true`` and + ``y_pred``. + + See Also + -------- + accuracy_score : Compute the accuracy score. By default, the function will + return the fraction of correct predictions divided by the total number + of predictions. + jaccard_score : Compute the Jaccard similarity coefficient score. + zero_one_loss : Compute the Zero-one classification loss. By default, the + function will return the percentage of imperfectly predicted subsets. + + Notes + ----- + In multiclass classification, the Hamming loss corresponds to the Hamming + distance between ``y_true`` and ``y_pred`` which is equivalent to the + subset ``zero_one_loss`` function, when `normalize` parameter is set to + True. + + In multilabel classification, the Hamming loss is different from the + subset zero-one loss. The zero-one loss considers the entire set of labels + for a given sample incorrect if it does not entirely match the true set of + labels. Hamming loss is more forgiving in that it penalizes only the + individual labels. + + The Hamming loss is upperbounded by the subset zero-one loss, when + `normalize` parameter is set to True. It is always between 0 and 1, + lower being better. + + References + ---------- + .. [1] Grigorios Tsoumakas, Ioannis Katakis. Multi-Label Classification: + An Overview. International Journal of Data Warehousing & Mining, + 3(3), 1-13, July-September 2007. + + .. [2] `Wikipedia entry on the Hamming distance + `_. + + Examples + -------- + >>> from sklearn.metrics import hamming_loss + >>> y_pred = [1, 2, 3, 4] + >>> y_true = [2, 2, 3, 4] + >>> hamming_loss(y_true, y_pred) + 0.25 + + In the multilabel case with binary label indicators: + + >>> import numpy as np + >>> hamming_loss(np.array([[0, 1], [1, 1]]), np.zeros((2, 2))) + 0.75 + """ + + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + check_consistent_length(y_true, y_pred, sample_weight) + + if sample_weight is None: + weight_average = 1.0 + else: + weight_average = np.mean(sample_weight) + + if y_type.startswith("multilabel"): + n_differences = count_nonzero(y_true - y_pred, sample_weight=sample_weight) + return n_differences / (y_true.shape[0] * y_true.shape[1] * weight_average) + + elif y_type in ["binary", "multiclass"]: + return _weighted_sum(y_true != y_pred, sample_weight, normalize=True) + else: + raise ValueError("{0} is not supported".format(y_type)) + + +def log_loss( + y_true, y_pred, *, eps="auto", normalize=True, sample_weight=None, labels=None +): + r"""Log loss, aka logistic loss or cross-entropy loss. + + This is the loss function used in (multinomial) logistic regression + and extensions of it such as neural networks, defined as the negative + log-likelihood of a logistic model that returns ``y_pred`` probabilities + for its training data ``y_true``. + The log loss is only defined for two or more labels. + For a single sample with true label :math:`y \in \{0,1\}` and + a probability estimate :math:`p = \operatorname{Pr}(y = 1)`, the log + loss is: + + .. math:: + L_{\log}(y, p) = -(y \log (p) + (1 - y) \log (1 - p)) + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like or label indicator matrix + Ground truth (correct) labels for n_samples samples. + + y_pred : array-like of float, shape = (n_samples, n_classes) or (n_samples,) + Predicted probabilities, as returned by a classifier's + predict_proba method. If ``y_pred.shape = (n_samples,)`` + the probabilities provided are assumed to be that of the + positive class. The labels in ``y_pred`` are assumed to be + ordered alphabetically, as done by + :class:`preprocessing.LabelBinarizer`. + + eps : float or "auto", default="auto" + Log loss is undefined for p=0 or p=1, so probabilities are + clipped to `max(eps, min(1 - eps, p))`. The default will depend on the + data type of `y_pred` and is set to `np.finfo(y_pred.dtype).eps`. + + .. versionadded:: 1.2 + + .. versionchanged:: 1.2 + The default value changed from `1e-15` to `"auto"` that is + equivalent to `np.finfo(y_pred.dtype).eps`. + + normalize : bool, default=True + If true, return the mean loss per sample. + Otherwise, return the sum of the per-sample losses. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + labels : array-like, default=None + If not provided, labels will be inferred from y_true. If ``labels`` + is ``None`` and ``y_pred`` has shape (n_samples,) the labels are + assumed to be binary and are inferred from ``y_true``. + + .. versionadded:: 0.18 + + Returns + ------- + loss : float + Log loss, aka logistic loss or cross-entropy loss. + + Notes + ----- + The logarithm used is the natural logarithm (base-e). + + References + ---------- + C.M. Bishop (2006). Pattern Recognition and Machine Learning. Springer, + p. 209. + + Examples + -------- + >>> from sklearn.metrics import log_loss + >>> log_loss(["spam", "ham", "ham", "spam"], + ... [[.1, .9], [.9, .1], [.8, .2], [.35, .65]]) + 0.21616... + """ + y_pred = check_array( + y_pred, ensure_2d=False, dtype=[np.float64, np.float32, np.float16] + ) + eps = np.finfo(y_pred.dtype).eps if eps == "auto" else eps + + check_consistent_length(y_pred, y_true, sample_weight) + lb = LabelBinarizer() + + if labels is not None: + lb.fit(labels) + else: + lb.fit(y_true) + + if len(lb.classes_) == 1: + if labels is None: + raise ValueError( + "y_true contains only one label ({0}). Please " + "provide the true labels explicitly through the " + "labels argument.".format(lb.classes_[0]) + ) + else: + raise ValueError( + "The labels array needs to contain at least two " + "labels for log_loss, " + "got {0}.".format(lb.classes_) + ) + + transformed_labels = lb.transform(y_true) + + if transformed_labels.shape[1] == 1: + transformed_labels = np.append( + 1 - transformed_labels, transformed_labels, axis=1 + ) + + # Clipping + y_pred = np.clip(y_pred, eps, 1 - eps) + + # If y_pred is of single dimension, assume y_true to be binary + # and then check. + if y_pred.ndim == 1: + y_pred = y_pred[:, np.newaxis] + if y_pred.shape[1] == 1: + y_pred = np.append(1 - y_pred, y_pred, axis=1) + + # Check if dimensions are consistent. + transformed_labels = check_array(transformed_labels) + if len(lb.classes_) != y_pred.shape[1]: + if labels is None: + raise ValueError( + "y_true and y_pred contain different number of " + "classes {0}, {1}. Please provide the true " + "labels explicitly through the labels argument. " + "Classes found in " + "y_true: {2}".format( + transformed_labels.shape[1], y_pred.shape[1], lb.classes_ + ) + ) + else: + raise ValueError( + "The number of classes in labels is different " + "from that in y_pred. Classes found in " + "labels: {0}".format(lb.classes_) + ) + + # Renormalize + y_pred_sum = y_pred.sum(axis=1) + y_pred = y_pred / y_pred_sum[:, np.newaxis] + loss = -xlogy(transformed_labels, y_pred).sum(axis=1) + + return _weighted_sum(loss, sample_weight, normalize) + + +def hinge_loss(y_true, pred_decision, *, labels=None, sample_weight=None): + """Average hinge loss (non-regularized). + + In binary class case, assuming labels in y_true are encoded with +1 and -1, + when a prediction mistake is made, ``margin = y_true * pred_decision`` is + always negative (since the signs disagree), implying ``1 - margin`` is + always greater than 1. The cumulated hinge loss is therefore an upper + bound of the number of mistakes made by the classifier. + + In multiclass case, the function expects that either all the labels are + included in y_true or an optional labels argument is provided which + contains all the labels. The multilabel margin is calculated according + to Crammer-Singer's method. As in the binary case, the cumulated hinge loss + is an upper bound of the number of mistakes made by the classifier. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array of shape (n_samples,) + True target, consisting of integers of two values. The positive label + must be greater than the negative label. + + pred_decision : array of shape (n_samples,) or (n_samples, n_classes) + Predicted decisions, as output by decision_function (floats). + + labels : array-like, default=None + Contains all the labels for the problem. Used in multiclass hinge loss. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + loss : float + Average hinge loss. + + References + ---------- + .. [1] `Wikipedia entry on the Hinge loss + `_. + + .. [2] Koby Crammer, Yoram Singer. On the Algorithmic + Implementation of Multiclass Kernel-based Vector + Machines. Journal of Machine Learning Research 2, + (2001), 265-292. + + .. [3] `L1 AND L2 Regularization for Multiclass Hinge Loss Models + by Robert C. Moore, John DeNero + `_. + + Examples + -------- + >>> from sklearn import svm + >>> from sklearn.metrics import hinge_loss + >>> X = [[0], [1]] + >>> y = [-1, 1] + >>> est = svm.LinearSVC(random_state=0) + >>> est.fit(X, y) + LinearSVC(random_state=0) + >>> pred_decision = est.decision_function([[-2], [3], [0.5]]) + >>> pred_decision + array([-2.18..., 2.36..., 0.09...]) + >>> hinge_loss([-1, 1, 1], pred_decision) + 0.30... + + In the multiclass case: + + >>> import numpy as np + >>> X = np.array([[0], [1], [2], [3]]) + >>> Y = np.array([0, 1, 2, 3]) + >>> labels = np.array([0, 1, 2, 3]) + >>> est = svm.LinearSVC() + >>> est.fit(X, Y) + LinearSVC() + >>> pred_decision = est.decision_function([[-1], [2], [3]]) + >>> y_true = [0, 2, 3] + >>> hinge_loss(y_true, pred_decision, labels=labels) + 0.56... + """ + check_consistent_length(y_true, pred_decision, sample_weight) + pred_decision = check_array(pred_decision, ensure_2d=False) + y_true = column_or_1d(y_true) + y_true_unique = np.unique(labels if labels is not None else y_true) + + if y_true_unique.size > 2: + + if pred_decision.ndim <= 1: + raise ValueError( + "The shape of pred_decision cannot be 1d array" + "with a multiclass target. pred_decision shape " + "must be (n_samples, n_classes), that is " + f"({y_true.shape[0]}, {y_true_unique.size})." + f" Got: {pred_decision.shape}" + ) + + # pred_decision.ndim > 1 is true + if y_true_unique.size != pred_decision.shape[1]: + if labels is None: + raise ValueError( + "Please include all labels in y_true " + "or pass labels as third argument" + ) + else: + raise ValueError( + "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 " + f"({y_true.shape[0]}, {y_true_unique.size}). " + f"Got: {pred_decision.shape}" + ) + if labels is None: + labels = y_true_unique + le = LabelEncoder() + le.fit(labels) + y_true = le.transform(y_true) + mask = np.ones_like(pred_decision, dtype=bool) + mask[np.arange(y_true.shape[0]), y_true] = False + margin = pred_decision[~mask] + margin -= np.max(pred_decision[mask].reshape(y_true.shape[0], -1), axis=1) + + else: + # Handles binary class case + # this code assumes that positive and negative labels + # are encoded as +1 and -1 respectively + pred_decision = column_or_1d(pred_decision) + pred_decision = np.ravel(pred_decision) + + lbin = LabelBinarizer(neg_label=-1) + y_true = lbin.fit_transform(y_true)[:, 0] + + try: + margin = y_true * pred_decision + except TypeError: + raise TypeError("pred_decision should be an array of floats.") + + losses = 1 - margin + # The hinge_loss doesn't penalize good enough predictions. + np.clip(losses, 0, None, out=losses) + return np.average(losses, weights=sample_weight) + + +def brier_score_loss(y_true, y_prob, *, sample_weight=None, pos_label=None): + """Compute the Brier score loss. + + The smaller the Brier score loss, the better, hence the naming with "loss". + The Brier score measures the mean squared difference between the predicted + probability and the actual outcome. The Brier score always + takes on a value between zero and one, since this is the largest + possible difference between a predicted probability (which must be + between zero and one) and the actual outcome (which can take on values + of only 0 and 1). It can be decomposed as the sum of refinement loss and + calibration loss. + + The Brier score is appropriate for binary and categorical outcomes that + can be structured as true or false, but is inappropriate for ordinal + variables which can take on three or more values (this is because the + Brier score assumes that all possible outcomes are equivalently + "distant" from one another). Which label is considered to be the positive + label is controlled via the parameter `pos_label`, which defaults to + the greater label unless `y_true` is all 0 or all -1, in which case + `pos_label` defaults to 1. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array of shape (n_samples,) + True targets. + + y_prob : array of shape (n_samples,) + Probabilities of the positive class. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + pos_label : int or str, default=None + Label of the positive class. `pos_label` will be inferred in the + following manner: + + * if `y_true` in {-1, 1} or {0, 1}, `pos_label` defaults to 1; + * else if `y_true` contains string, an error will be raised and + `pos_label` should be explicitly specified; + * otherwise, `pos_label` defaults to the greater label, + i.e. `np.unique(y_true)[-1]`. + + Returns + ------- + score : float + Brier score loss. + + References + ---------- + .. [1] `Wikipedia entry for the Brier score + `_. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import brier_score_loss + >>> y_true = np.array([0, 1, 1, 0]) + >>> y_true_categorical = np.array(["spam", "ham", "ham", "spam"]) + >>> y_prob = np.array([0.1, 0.9, 0.8, 0.3]) + >>> brier_score_loss(y_true, y_prob) + 0.037... + >>> brier_score_loss(y_true, 1-y_prob, pos_label=0) + 0.037... + >>> brier_score_loss(y_true_categorical, y_prob, pos_label="ham") + 0.037... + >>> brier_score_loss(y_true, np.array(y_prob) > 0.5) + 0.0 + """ + y_true = column_or_1d(y_true) + y_prob = column_or_1d(y_prob) + assert_all_finite(y_true) + assert_all_finite(y_prob) + check_consistent_length(y_true, y_prob, sample_weight) + + y_type = type_of_target(y_true, input_name="y_true") + if y_type != "binary": + raise ValueError( + "Only binary classification is supported. The type of the target " + f"is {y_type}." + ) + + if y_prob.max() > 1: + raise ValueError("y_prob contains values greater than 1.") + if y_prob.min() < 0: + raise ValueError("y_prob contains values less than 0.") + + try: + pos_label = _check_pos_label_consistency(pos_label, y_true) + except ValueError: + classes = np.unique(y_true) + if classes.dtype.kind not in ("O", "U", "S"): + # for backward compatibility, if classes are not string then + # `pos_label` will correspond to the greater label + pos_label = classes[-1] + else: + raise + y_true = np.array(y_true == pos_label, int) + return np.average((y_true - y_prob) ** 2, weights=sample_weight) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9b29d4acabf0a7d220bc51ff5fd76d5c4546cea Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__pycache__/_dispatcher.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__pycache__/_dispatcher.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61e26bbe5e4fca0ed0eae0bf1827df000a459ef3 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__pycache__/_dispatcher.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pxd b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2460d2f993e8feb71576be6045997315385148d0 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pxd @@ -0,0 +1,56 @@ +cimport numpy as cnp +from ...utils._typedefs cimport ITYPE_t, DTYPE_t + +cnp.import_array() + +from ._base cimport BaseDistancesReduction64 +from ._middle_term_computer cimport MiddleTermComputer64 + +cdef class ArgKmin64(BaseDistancesReduction64): + """float64 implementation of the ArgKmin.""" + + cdef: + ITYPE_t k + + ITYPE_t[:, ::1] argkmin_indices + DTYPE_t[:, ::1] argkmin_distances + + # Used as array of pointers to private datastructures used in threads. + DTYPE_t ** heaps_r_distances_chunks + ITYPE_t ** heaps_indices_chunks + + +cdef class EuclideanArgKmin64(ArgKmin64): + """EuclideanDistance-specialisation of ArgKmin64.""" + cdef: + MiddleTermComputer64 middle_term_computer + const DTYPE_t[::1] X_norm_squared + const DTYPE_t[::1] Y_norm_squared + + bint use_squared_distances + +from ._base cimport BaseDistancesReduction32 +from ._middle_term_computer cimport MiddleTermComputer32 + +cdef class ArgKmin32(BaseDistancesReduction32): + """float32 implementation of the ArgKmin.""" + + cdef: + ITYPE_t k + + ITYPE_t[:, ::1] argkmin_indices + DTYPE_t[:, ::1] argkmin_distances + + # Used as array of pointers to private datastructures used in threads. + DTYPE_t ** heaps_r_distances_chunks + ITYPE_t ** heaps_indices_chunks + + +cdef class EuclideanArgKmin32(ArgKmin32): + """EuclideanDistance-specialisation of ArgKmin32.""" + cdef: + MiddleTermComputer32 middle_term_computer + const DTYPE_t[::1] X_norm_squared + const DTYPE_t[::1] Y_norm_squared + + bint use_squared_distances diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__init__.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/roc_curve.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/roc_curve.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54e68c3e6efc326a0de190f5787f6dcc01c50914 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/roc_curve.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/base.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/base.py new file mode 100644 index 0000000000000000000000000000000000000000..60377e3b10f66de49b5f7fda128b984638ea9124 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/base.py @@ -0,0 +1,116 @@ +from ...base import is_classifier + + +def _check_classifier_response_method(estimator, response_method): + """Return prediction method from the response_method + + Parameters + ---------- + estimator: object + Classifier to check + + response_method: {'auto', 'predict_proba', 'decision_function'} + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the target response. If set to 'auto', + :term:`predict_proba` is tried first and if it does not exist + :term:`decision_function` is tried next. + + Returns + ------- + prediction_method: callable + prediction method of estimator + """ + + if response_method not in ("predict_proba", "decision_function", "auto"): + raise ValueError( + "response_method must be 'predict_proba', 'decision_function' or 'auto'" + ) + + error_msg = "response method {} is not defined in {}" + if response_method != "auto": + prediction_method = getattr(estimator, response_method, None) + if prediction_method is None: + raise ValueError( + error_msg.format(response_method, estimator.__class__.__name__) + ) + else: + predict_proba = getattr(estimator, "predict_proba", None) + decision_function = getattr(estimator, "decision_function", None) + prediction_method = predict_proba or decision_function + if prediction_method is None: + raise ValueError( + error_msg.format( + "decision_function or predict_proba", estimator.__class__.__name__ + ) + ) + + return prediction_method + + +def _get_response(X, estimator, response_method, pos_label=None): + """Return response and positive label. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + estimator : estimator instance + Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a classifier. + + response_method: {'auto', 'predict_proba', 'decision_function'} + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the target response. If set to 'auto', + :term:`predict_proba` is tried first and if it does not exist + :term:`decision_function` is tried next. + + pos_label : str or int, default=None + The class considered as the positive class when computing + the metrics. By default, `estimators.classes_[1]` is + considered as the positive class. + + Returns + ------- + y_pred: ndarray of shape (n_samples,) + Target scores calculated from the provided response_method + and pos_label. + + pos_label: str or int + The class considered as the positive class when computing + the metrics. + """ + classification_error = ( + "Expected 'estimator' to be a binary classifier, but got" + f" {estimator.__class__.__name__}" + ) + + if not is_classifier(estimator): + raise ValueError(classification_error) + + prediction_method = _check_classifier_response_method(estimator, response_method) + y_pred = prediction_method(X) + if pos_label is not None: + try: + class_idx = estimator.classes_.tolist().index(pos_label) + except ValueError as e: + raise ValueError( + "The class provided by 'pos_label' is unknown. Got " + f"{pos_label} instead of one of {set(estimator.classes_)}" + ) from e + else: + class_idx = 1 + pos_label = estimator.classes_[class_idx] + + if y_pred.ndim != 1: # `predict_proba` + y_pred_shape = y_pred.shape[1] + if y_pred_shape != 2: + raise ValueError( + f"{classification_error} fit on multiclass ({y_pred_shape} classes)" + " data" + ) + y_pred = y_pred[:, class_idx] + elif pos_label == estimator.classes_[0]: # `decision_function` + y_pred *= -1 + + return y_pred, pos_label diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/confusion_matrix.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/confusion_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..1611bb9605d85e5e4840d7bc71bdd97aa741abea --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/confusion_matrix.py @@ -0,0 +1,482 @@ +from itertools import product + +import numpy as np + +from .. import confusion_matrix +from ...utils import check_matplotlib_support +from ...utils.multiclass import unique_labels +from ...base import is_classifier + + +class ConfusionMatrixDisplay: + """Confusion Matrix visualization. + + It is recommend to use + :func:`~sklearn.metrics.ConfusionMatrixDisplay.from_estimator` or + :func:`~sklearn.metrics.ConfusionMatrixDisplay.from_predictions` to + create a :class:`ConfusionMatrixDisplay`. All parameters are stored as + attributes. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + confusion_matrix : ndarray of shape (n_classes, n_classes) + Confusion matrix. + + display_labels : ndarray of shape (n_classes,), default=None + Display labels for plot. If None, display labels are set from 0 to + `n_classes - 1`. + + Attributes + ---------- + im_ : matplotlib AxesImage + Image representing the confusion matrix. + + text_ : ndarray of shape (n_classes, n_classes), dtype=matplotlib Text, \ + or None + Array of matplotlib axes. `None` if `include_values` is false. + + ax_ : matplotlib Axes + Axes with confusion matrix. + + figure_ : matplotlib Figure + Figure containing the confusion matrix. + + See Also + -------- + confusion_matrix : Compute Confusion Matrix to evaluate the accuracy of a + classification. + ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix + given an estimator, the data, and the label. + ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix + given the true and predicted labels. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split(X, y, + ... random_state=0) + >>> clf = SVC(random_state=0) + >>> clf.fit(X_train, y_train) + SVC(random_state=0) + >>> predictions = clf.predict(X_test) + >>> cm = confusion_matrix(y_test, predictions, labels=clf.classes_) + >>> disp = ConfusionMatrixDisplay(confusion_matrix=cm, + ... display_labels=clf.classes_) + >>> disp.plot() + <...> + >>> plt.show() + """ + + def __init__(self, confusion_matrix, *, display_labels=None): + self.confusion_matrix = confusion_matrix + self.display_labels = display_labels + + def plot( + self, + *, + include_values=True, + cmap="viridis", + xticks_rotation="horizontal", + values_format=None, + ax=None, + colorbar=True, + im_kw=None, + text_kw=None, + ): + """Plot visualization. + + Parameters + ---------- + include_values : bool, default=True + Includes values in confusion matrix. + + cmap : str or matplotlib Colormap, default='viridis' + Colormap recognized by matplotlib. + + xticks_rotation : {'vertical', 'horizontal'} or float, \ + default='horizontal' + Rotation of xtick labels. + + values_format : str, default=None + Format specification for values in confusion matrix. If `None`, + the format specification is 'd' or '.2g' whichever is shorter. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + colorbar : bool, default=True + Whether or not to add a colorbar to the plot. + + im_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.imshow` call. + + text_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.text` call. + + .. versionadded:: 1.2 + + Returns + ------- + display : :class:`~sklearn.metrics.ConfusionMatrixDisplay` + Returns a :class:`~sklearn.metrics.ConfusionMatrixDisplay` instance + that contains all the information to plot the confusion matrix. + """ + check_matplotlib_support("ConfusionMatrixDisplay.plot") + import matplotlib.pyplot as plt + + if ax is None: + fig, ax = plt.subplots() + else: + fig = ax.figure + + cm = self.confusion_matrix + n_classes = cm.shape[0] + + default_im_kw = dict(interpolation="nearest", cmap=cmap) + im_kw = im_kw or {} + im_kw = {**default_im_kw, **im_kw} + text_kw = text_kw or {} + + self.im_ = ax.imshow(cm, **im_kw) + self.text_ = None + cmap_min, cmap_max = self.im_.cmap(0), self.im_.cmap(1.0) + + if include_values: + self.text_ = np.empty_like(cm, dtype=object) + + # print text with appropriate color depending on background + thresh = (cm.max() + cm.min()) / 2.0 + + for i, j in product(range(n_classes), range(n_classes)): + color = cmap_max if cm[i, j] < thresh else cmap_min + + if values_format is None: + text_cm = format(cm[i, j], ".2g") + if cm.dtype.kind != "f": + text_d = format(cm[i, j], "d") + if len(text_d) < len(text_cm): + text_cm = text_d + else: + text_cm = format(cm[i, j], values_format) + + default_text_kwargs = dict(ha="center", va="center", color=color) + text_kwargs = {**default_text_kwargs, **text_kw} + + self.text_[i, j] = ax.text(j, i, text_cm, **text_kwargs) + + if self.display_labels is None: + display_labels = np.arange(n_classes) + else: + display_labels = self.display_labels + if colorbar: + fig.colorbar(self.im_, ax=ax) + ax.set( + xticks=np.arange(n_classes), + yticks=np.arange(n_classes), + xticklabels=display_labels, + yticklabels=display_labels, + ylabel="True label", + xlabel="Predicted label", + ) + + ax.set_ylim((n_classes - 0.5, -0.5)) + plt.setp(ax.get_xticklabels(), rotation=xticks_rotation) + + self.figure_ = fig + self.ax_ = ax + return self + + @classmethod + def from_estimator( + cls, + estimator, + X, + y, + *, + labels=None, + sample_weight=None, + normalize=None, + display_labels=None, + include_values=True, + xticks_rotation="horizontal", + values_format=None, + cmap="viridis", + ax=None, + colorbar=True, + im_kw=None, + text_kw=None, + ): + """Plot Confusion Matrix given an estimator and some data. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + estimator : estimator instance + Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a classifier. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + y : array-like of shape (n_samples,) + Target values. + + labels : array-like of shape (n_classes,), default=None + List of labels to index the confusion matrix. This may be used to + reorder or select a subset of labels. If `None` is given, those + that appear at least once in `y_true` or `y_pred` are used in + sorted order. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + normalize : {'true', 'pred', 'all'}, default=None + Either to normalize the counts display in the matrix: + + - if `'true'`, the confusion matrix is normalized over the true + conditions (e.g. rows); + - if `'pred'`, the confusion matrix is normalized over the + predicted conditions (e.g. columns); + - if `'all'`, the confusion matrix is normalized by the total + number of samples; + - if `None` (default), the confusion matrix will not be normalized. + + display_labels : array-like of shape (n_classes,), default=None + Target names used for plotting. By default, `labels` will be used + if it is defined, otherwise the unique labels of `y_true` and + `y_pred` will be used. + + include_values : bool, default=True + Includes values in confusion matrix. + + xticks_rotation : {'vertical', 'horizontal'} or float, \ + default='horizontal' + Rotation of xtick labels. + + values_format : str, default=None + Format specification for values in confusion matrix. If `None`, the + format specification is 'd' or '.2g' whichever is shorter. + + cmap : str or matplotlib Colormap, default='viridis' + Colormap recognized by matplotlib. + + ax : matplotlib Axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + colorbar : bool, default=True + Whether or not to add a colorbar to the plot. + + im_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.imshow` call. + + text_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.text` call. + + .. versionadded:: 1.2 + + Returns + ------- + display : :class:`~sklearn.metrics.ConfusionMatrixDisplay` + + See Also + -------- + ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix + given the true and predicted labels. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import ConfusionMatrixDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = SVC(random_state=0) + >>> clf.fit(X_train, y_train) + SVC(random_state=0) + >>> ConfusionMatrixDisplay.from_estimator( + ... clf, X_test, y_test) + <...> + >>> plt.show() + """ + method_name = f"{cls.__name__}.from_estimator" + check_matplotlib_support(method_name) + if not is_classifier(estimator): + raise ValueError(f"{method_name} only supports classifiers") + y_pred = estimator.predict(X) + + return cls.from_predictions( + y, + y_pred, + sample_weight=sample_weight, + labels=labels, + normalize=normalize, + display_labels=display_labels, + include_values=include_values, + cmap=cmap, + ax=ax, + xticks_rotation=xticks_rotation, + values_format=values_format, + colorbar=colorbar, + im_kw=im_kw, + text_kw=text_kw, + ) + + @classmethod + def from_predictions( + cls, + y_true, + y_pred, + *, + labels=None, + sample_weight=None, + normalize=None, + display_labels=None, + include_values=True, + xticks_rotation="horizontal", + values_format=None, + cmap="viridis", + ax=None, + colorbar=True, + im_kw=None, + text_kw=None, + ): + """Plot Confusion Matrix given true and predicted labels. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True labels. + + y_pred : array-like of shape (n_samples,) + The predicted labels given by the method `predict` of an + classifier. + + labels : array-like of shape (n_classes,), default=None + List of labels to index the confusion matrix. This may be used to + reorder or select a subset of labels. If `None` is given, those + that appear at least once in `y_true` or `y_pred` are used in + sorted order. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + normalize : {'true', 'pred', 'all'}, default=None + Either to normalize the counts display in the matrix: + + - if `'true'`, the confusion matrix is normalized over the true + conditions (e.g. rows); + - if `'pred'`, the confusion matrix is normalized over the + predicted conditions (e.g. columns); + - if `'all'`, the confusion matrix is normalized by the total + number of samples; + - if `None` (default), the confusion matrix will not be normalized. + + display_labels : array-like of shape (n_classes,), default=None + Target names used for plotting. By default, `labels` will be used + if it is defined, otherwise the unique labels of `y_true` and + `y_pred` will be used. + + include_values : bool, default=True + Includes values in confusion matrix. + + xticks_rotation : {'vertical', 'horizontal'} or float, \ + default='horizontal' + Rotation of xtick labels. + + values_format : str, default=None + Format specification for values in confusion matrix. If `None`, the + format specification is 'd' or '.2g' whichever is shorter. + + cmap : str or matplotlib Colormap, default='viridis' + Colormap recognized by matplotlib. + + ax : matplotlib Axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + colorbar : bool, default=True + Whether or not to add a colorbar to the plot. + + im_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.imshow` call. + + text_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.text` call. + + .. versionadded:: 1.2 + + Returns + ------- + display : :class:`~sklearn.metrics.ConfusionMatrixDisplay` + + See Also + -------- + ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix + given an estimator, the data, and the label. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import ConfusionMatrixDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = SVC(random_state=0) + >>> clf.fit(X_train, y_train) + SVC(random_state=0) + >>> y_pred = clf.predict(X_test) + >>> ConfusionMatrixDisplay.from_predictions( + ... y_test, y_pred) + <...> + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_predictions") + + if display_labels is None: + if labels is None: + display_labels = unique_labels(y_true, y_pred) + else: + display_labels = labels + + cm = confusion_matrix( + y_true, + y_pred, + sample_weight=sample_weight, + labels=labels, + normalize=normalize, + ) + + disp = cls(confusion_matrix=cm, display_labels=display_labels) + + return disp.plot( + include_values=include_values, + cmap=cmap, + ax=ax, + xticks_rotation=xticks_rotation, + values_format=values_format, + colorbar=colorbar, + im_kw=im_kw, + text_kw=text_kw, + ) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/det_curve.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/det_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a868b195dd086fcc6edb0c4fc56cd72cd93a51 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/det_curve.py @@ -0,0 +1,346 @@ +import scipy as sp + +from .base import _get_response + +from .. import det_curve +from .._base import _check_pos_label_consistency + +from ...utils import check_matplotlib_support + + +class DetCurveDisplay: + """DET curve visualization. + + It is recommend to use :func:`~sklearn.metrics.DetCurveDisplay.from_estimator` + or :func:`~sklearn.metrics.DetCurveDisplay.from_predictions` to create a + visualizer. All parameters are stored as attributes. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.24 + + Parameters + ---------- + fpr : ndarray + False positive rate. + + fnr : ndarray + False negative rate. + + estimator_name : str, default=None + Name of estimator. If None, the estimator name is not shown. + + pos_label : str or int, default=None + The label of the positive class. + + Attributes + ---------- + line_ : matplotlib Artist + DET Curve. + + ax_ : matplotlib Axes + Axes with DET Curve. + + figure_ : matplotlib Figure + Figure containing the curve. + + See Also + -------- + det_curve : Compute error rates for different probability thresholds. + DetCurveDisplay.from_estimator : Plot DET curve given an estimator and + some data. + DetCurveDisplay.from_predictions : Plot DET curve given the true and + predicted labels. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import det_curve, DetCurveDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(n_samples=1000, random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, test_size=0.4, random_state=0) + >>> clf = SVC(random_state=0).fit(X_train, y_train) + >>> y_pred = clf.decision_function(X_test) + >>> fpr, fnr, _ = det_curve(y_test, y_pred) + >>> display = DetCurveDisplay( + ... fpr=fpr, fnr=fnr, estimator_name="SVC" + ... ) + >>> display.plot() + <...> + >>> plt.show() + """ + + def __init__(self, *, fpr, fnr, estimator_name=None, pos_label=None): + self.fpr = fpr + self.fnr = fnr + self.estimator_name = estimator_name + self.pos_label = pos_label + + @classmethod + def from_estimator( + cls, + estimator, + X, + y, + *, + sample_weight=None, + response_method="auto", + pos_label=None, + name=None, + ax=None, + **kwargs, + ): + """Plot DET curve given an estimator and data. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + estimator : estimator instance + Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a classifier. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + y : array-like of shape (n_samples,) + Target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + response_method : {'predict_proba', 'decision_function', 'auto'} \ + default='auto' + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the predicted target response. If set + to 'auto', :term:`predict_proba` is tried first and if it does not + exist :term:`decision_function` is tried next. + + pos_label : str or int, default=None + The label of the positive class. When `pos_label=None`, if `y_true` + is in {-1, 1} or {0, 1}, `pos_label` is set to 1, otherwise an + error will be raised. + + name : str, default=None + Name of DET curve for labeling. If `None`, use the name of the + estimator. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + **kwargs : dict + Additional keywords arguments passed to matplotlib `plot` function. + + Returns + ------- + display : :class:`~sklearn.metrics.DetCurveDisplay` + Object that stores computed values. + + See Also + -------- + det_curve : Compute error rates for different probability thresholds. + DetCurveDisplay.from_predictions : Plot DET curve given the true and + predicted labels. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import DetCurveDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(n_samples=1000, random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, test_size=0.4, random_state=0) + >>> clf = SVC(random_state=0).fit(X_train, y_train) + >>> DetCurveDisplay.from_estimator( + ... clf, X_test, y_test) + <...> + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_estimator") + + name = estimator.__class__.__name__ if name is None else name + + y_pred, pos_label = _get_response( + X, + estimator, + response_method, + pos_label=pos_label, + ) + + return cls.from_predictions( + y_true=y, + y_pred=y_pred, + sample_weight=sample_weight, + name=name, + ax=ax, + pos_label=pos_label, + **kwargs, + ) + + @classmethod + def from_predictions( + cls, + y_true, + y_pred, + *, + sample_weight=None, + pos_label=None, + name=None, + ax=None, + **kwargs, + ): + """Plot the DET curve given the true and predicted labels. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True labels. + + y_pred : array-like of shape (n_samples,) + Target scores, can either be probability estimates of the positive + class, confidence values, or non-thresholded measure of decisions + (as returned by `decision_function` on some classifiers). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + pos_label : str or int, default=None + The label of the positive class. When `pos_label=None`, if `y_true` + is in {-1, 1} or {0, 1}, `pos_label` is set to 1, otherwise an + error will be raised. + + name : str, default=None + Name of DET curve for labeling. If `None`, name will be set to + `"Classifier"`. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + **kwargs : dict + Additional keywords arguments passed to matplotlib `plot` function. + + Returns + ------- + display : :class:`~sklearn.metrics.DetCurveDisplay` + Object that stores computed values. + + See Also + -------- + det_curve : Compute error rates for different probability thresholds. + DetCurveDisplay.from_estimator : Plot DET curve given an estimator and + some data. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import DetCurveDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(n_samples=1000, random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, test_size=0.4, random_state=0) + >>> clf = SVC(random_state=0).fit(X_train, y_train) + >>> y_pred = clf.decision_function(X_test) + >>> DetCurveDisplay.from_predictions( + ... y_test, y_pred) + <...> + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_predictions") + fpr, fnr, _ = det_curve( + y_true, + y_pred, + pos_label=pos_label, + sample_weight=sample_weight, + ) + + pos_label = _check_pos_label_consistency(pos_label, y_true) + name = "Classifier" if name is None else name + + viz = DetCurveDisplay( + fpr=fpr, + fnr=fnr, + estimator_name=name, + pos_label=pos_label, + ) + + return viz.plot(ax=ax, name=name, **kwargs) + + def plot(self, ax=None, *, name=None, **kwargs): + """Plot visualization. + + Parameters + ---------- + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + name : str, default=None + Name of DET curve for labeling. If `None`, use `estimator_name` if + it is not `None`, otherwise no labeling is shown. + + **kwargs : dict + Additional keywords arguments passed to matplotlib `plot` function. + + Returns + ------- + display : :class:`~sklearn.metrics.plot.DetCurveDisplay` + Object that stores computed values. + """ + check_matplotlib_support("DetCurveDisplay.plot") + + name = self.estimator_name if name is None else name + line_kwargs = {} if name is None else {"label": name} + line_kwargs.update(**kwargs) + + import matplotlib.pyplot as plt + + if ax is None: + _, ax = plt.subplots() + + (self.line_,) = ax.plot( + sp.stats.norm.ppf(self.fpr), + sp.stats.norm.ppf(self.fnr), + **line_kwargs, + ) + info_pos_label = ( + f" (Positive label: {self.pos_label})" if self.pos_label is not None else "" + ) + + xlabel = "False Positive Rate" + info_pos_label + ylabel = "False Negative Rate" + info_pos_label + ax.set(xlabel=xlabel, ylabel=ylabel) + + if "label" in line_kwargs: + ax.legend(loc="lower right") + + ticks = [0.001, 0.01, 0.05, 0.20, 0.5, 0.80, 0.95, 0.99, 0.999] + tick_locations = sp.stats.norm.ppf(ticks) + tick_labels = [ + "{:.0%}".format(s) if (100 * s).is_integer() else "{:.1%}".format(s) + for s in ticks + ] + ax.set_xticks(tick_locations) + ax.set_xticklabels(tick_labels) + ax.set_xlim(-3, 3) + ax.set_yticks(tick_locations) + ax.set_yticklabels(tick_labels) + ax.set_ylim(-3, 3) + + self.ax_ = ax + self.figure_ = ax.figure + return self diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/precision_recall_curve.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/precision_recall_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..35cf72e618e8406275aea9ed268212c910050104 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/precision_recall_curve.py @@ -0,0 +1,393 @@ +from sklearn.base import is_classifier +from .base import _get_response + +from .. import average_precision_score +from .. import precision_recall_curve +from .._base import _check_pos_label_consistency +from .._classification import check_consistent_length + +from ...utils import check_matplotlib_support + + +class PrecisionRecallDisplay: + """Precision Recall visualization. + + It is recommend to use + :func:`~sklearn.metrics.PrecisionRecallDisplay.from_estimator` or + :func:`~sklearn.metrics.PrecisionRecallDisplay.from_predictions` to create + a :class:`~sklearn.metrics.PredictionRecallDisplay`. All parameters are + stored as attributes. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + precision : ndarray + Precision values. + + recall : ndarray + Recall values. + + average_precision : float, default=None + Average precision. If None, the average precision is not shown. + + estimator_name : str, default=None + Name of estimator. If None, then the estimator name is not shown. + + pos_label : str or int, default=None + The class considered as the positive class. If None, the class will not + be shown in the legend. + + .. versionadded:: 0.24 + + Attributes + ---------- + line_ : matplotlib Artist + Precision recall curve. + + ax_ : matplotlib Axes + Axes with precision recall curve. + + figure_ : matplotlib Figure + Figure containing the curve. + + See Also + -------- + precision_recall_curve : Compute precision-recall pairs for different + probability thresholds. + PrecisionRecallDisplay.from_estimator : Plot Precision Recall Curve given + a binary classifier. + PrecisionRecallDisplay.from_predictions : Plot Precision Recall Curve + using predictions from a binary classifier. + + Notes + ----- + The average precision (cf. :func:`~sklearn.metrics.average_precision`) in + scikit-learn is computed without any interpolation. To be consistent with + this metric, the precision-recall curve is plotted without any + interpolation as well (step-wise style). + + You can change this style by passing the keyword argument + `drawstyle="default"` in :meth:`plot`, :meth:`from_estimator`, or + :meth:`from_predictions`. However, the curve will not be strictly + consistent with the reported average precision. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import (precision_recall_curve, + ... PrecisionRecallDisplay) + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split(X, y, + ... random_state=0) + >>> clf = SVC(random_state=0) + >>> clf.fit(X_train, y_train) + SVC(random_state=0) + >>> predictions = clf.predict(X_test) + >>> precision, recall, _ = precision_recall_curve(y_test, predictions) + >>> disp = PrecisionRecallDisplay(precision=precision, recall=recall) + >>> disp.plot() + <...> + >>> plt.show() + """ + + def __init__( + self, + precision, + recall, + *, + average_precision=None, + estimator_name=None, + pos_label=None, + ): + self.estimator_name = estimator_name + self.precision = precision + self.recall = recall + self.average_precision = average_precision + self.pos_label = pos_label + + def plot(self, ax=None, *, name=None, **kwargs): + """Plot visualization. + + Extra keyword arguments will be passed to matplotlib's `plot`. + + Parameters + ---------- + ax : Matplotlib Axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + name : str, default=None + Name of precision recall curve for labeling. If `None`, use + `estimator_name` if not `None`, otherwise no labeling is shown. + + **kwargs : dict + Keyword arguments to be passed to matplotlib's `plot`. + + Returns + ------- + display : :class:`~sklearn.metrics.PrecisionRecallDisplay` + Object that stores computed values. + + Notes + ----- + The average precision (cf. :func:`~sklearn.metrics.average_precision`) + in scikit-learn is computed without any interpolation. To be consistent + with this metric, the precision-recall curve is plotted without any + interpolation as well (step-wise style). + + You can change this style by passing the keyword argument + `drawstyle="default"`. However, the curve will not be strictly + consistent with the reported average precision. + """ + check_matplotlib_support("PrecisionRecallDisplay.plot") + + name = self.estimator_name if name is None else name + + line_kwargs = {"drawstyle": "steps-post"} + if self.average_precision is not None and name is not None: + line_kwargs["label"] = f"{name} (AP = {self.average_precision:0.2f})" + elif self.average_precision is not None: + line_kwargs["label"] = f"AP = {self.average_precision:0.2f}" + elif name is not None: + line_kwargs["label"] = name + line_kwargs.update(**kwargs) + + import matplotlib.pyplot as plt + + if ax is None: + fig, ax = plt.subplots() + + (self.line_,) = ax.plot(self.recall, self.precision, **line_kwargs) + info_pos_label = ( + f" (Positive label: {self.pos_label})" if self.pos_label is not None else "" + ) + + xlabel = "Recall" + info_pos_label + ylabel = "Precision" + info_pos_label + ax.set(xlabel=xlabel, ylabel=ylabel) + + if "label" in line_kwargs: + ax.legend(loc="lower left") + + self.ax_ = ax + self.figure_ = ax.figure + return self + + @classmethod + def from_estimator( + cls, + estimator, + X, + y, + *, + sample_weight=None, + pos_label=None, + response_method="auto", + name=None, + ax=None, + **kwargs, + ): + """Plot precision-recall curve given an estimator and some data. + + Parameters + ---------- + estimator : estimator instance + Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a classifier. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + y : array-like of shape (n_samples,) + Target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + pos_label : str or int, default=None + The class considered as the positive class when computing the + precision and recall metrics. By default, `estimators.classes_[1]` + is considered as the positive class. + + response_method : {'predict_proba', 'decision_function', 'auto'}, \ + default='auto' + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the target response. If set to 'auto', + :term:`predict_proba` is tried first and if it does not exist + :term:`decision_function` is tried next. + + name : str, default=None + Name for labeling curve. If `None`, no name is used. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is created. + + **kwargs : dict + Keyword arguments to be passed to matplotlib's `plot`. + + Returns + ------- + display : :class:`~sklearn.metrics.PrecisionRecallDisplay` + + See Also + -------- + PrecisionRecallDisplay.from_predictions : Plot precision-recall curve + using estimated probabilities or output of decision function. + + Notes + ----- + The average precision (cf. :func:`~sklearn.metrics.average_precision`) + in scikit-learn is computed without any interpolation. To be consistent + with this metric, the precision-recall curve is plotted without any + interpolation as well (step-wise style). + + You can change this style by passing the keyword argument + `drawstyle="default"`. However, the curve will not be strictly + consistent with the reported average precision. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import PrecisionRecallDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.linear_model import LogisticRegression + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = LogisticRegression() + >>> clf.fit(X_train, y_train) + LogisticRegression() + >>> PrecisionRecallDisplay.from_estimator( + ... clf, X_test, y_test) + <...> + >>> plt.show() + """ + method_name = f"{cls.__name__}.from_estimator" + check_matplotlib_support(method_name) + if not is_classifier(estimator): + raise ValueError(f"{method_name} only supports classifiers") + y_pred, pos_label = _get_response( + X, + estimator, + response_method, + pos_label=pos_label, + ) + + name = name if name is not None else estimator.__class__.__name__ + + return cls.from_predictions( + y, + y_pred, + sample_weight=sample_weight, + name=name, + pos_label=pos_label, + ax=ax, + **kwargs, + ) + + @classmethod + def from_predictions( + cls, + y_true, + y_pred, + *, + sample_weight=None, + pos_label=None, + name=None, + ax=None, + **kwargs, + ): + """Plot precision-recall curve given binary class predictions. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True binary labels. + + y_pred : array-like of shape (n_samples,) + Estimated probabilities or output of decision function. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + pos_label : str or int, default=None + The class considered as the positive class when computing the + precision and recall metrics. + + name : str, default=None + Name for labeling curve. If `None`, name will be set to + `"Classifier"`. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is created. + + **kwargs : dict + Keyword arguments to be passed to matplotlib's `plot`. + + Returns + ------- + display : :class:`~sklearn.metrics.PrecisionRecallDisplay` + + See Also + -------- + PrecisionRecallDisplay.from_estimator : Plot precision-recall curve + using an estimator. + + Notes + ----- + The average precision (cf. :func:`~sklearn.metrics.average_precision`) + in scikit-learn is computed without any interpolation. To be consistent + with this metric, the precision-recall curve is plotted without any + interpolation as well (step-wise style). + + You can change this style by passing the keyword argument + `drawstyle="default"`. However, the curve will not be strictly + consistent with the reported average precision. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import PrecisionRecallDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.linear_model import LogisticRegression + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = LogisticRegression() + >>> clf.fit(X_train, y_train) + LogisticRegression() + >>> y_pred = clf.predict_proba(X_test)[:, 1] + >>> PrecisionRecallDisplay.from_predictions( + ... y_test, y_pred) + <...> + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_predictions") + + check_consistent_length(y_true, y_pred, sample_weight) + pos_label = _check_pos_label_consistency(pos_label, y_true) + + precision, recall, _ = precision_recall_curve( + y_true, y_pred, pos_label=pos_label, sample_weight=sample_weight + ) + average_precision = average_precision_score( + y_true, y_pred, pos_label=pos_label, sample_weight=sample_weight + ) + + name = name if name is not None else "Classifier" + + viz = PrecisionRecallDisplay( + precision=precision, + recall=recall, + average_precision=average_precision, + estimator_name=name, + pos_label=pos_label, + ) + + return viz.plot(ax=ax, name=name, **kwargs) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/regression.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/regression.py new file mode 100644 index 0000000000000000000000000000000000000000..46440c3e133b1c01951afc39780a96dd7072a89a --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/regression.py @@ -0,0 +1,406 @@ +import numbers + +import numpy as np + +from ...utils import check_matplotlib_support +from ...utils import check_random_state +from ...utils import _safe_indexing + + +class PredictionErrorDisplay: + """Visualization of the prediction error of a regression model. + + This tool can display "residuals vs predicted" or "actual vs predicted" + using scatter plots to qualitatively assess the behavior of a regressor, + preferably on held-out data points. + + See the details in the docstrings of + :func:`~sklearn.metrics.PredictionErrorDisplay.from_estimator` or + :func:`~sklearn.metrics.PredictionErrorDisplay.from_predictions` to + create a visualizer. All parameters are stored as attributes. + + For general information regarding `scikit-learn` visualization tools, read + more in the :ref:`Visualization Guide `. + For details regarding interpreting these plots, refer to the + :ref:`Model Evaluation Guide `. + + .. versionadded:: 1.2 + + Parameters + ---------- + y_true : ndarray of shape (n_samples,) + True values. + + y_pred : ndarray of shape (n_samples,) + Prediction values. + + Attributes + ---------- + line_ : matplotlib Artist + Optimal line representing `y_true == y_pred`. Therefore, it is a + diagonal line for `kind="predictions"` and a horizontal line for + `kind="residuals"`. + + errors_lines_ : matplotlib Artist or None + Residual lines. If `with_errors=False`, then it is set to `None`. + + scatter_ : matplotlib Artist + Scatter data points. + + ax_ : matplotlib Axes + Axes with the different matplotlib axis. + + figure_ : matplotlib Figure + Figure containing the scatter and lines. + + See Also + -------- + PredictionErrorDisplay.from_estimator : Prediction error visualization + given an estimator and some data. + PredictionErrorDisplay.from_predictions : Prediction error visualization + given the true and predicted targets. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import load_diabetes + >>> from sklearn.linear_model import Ridge + >>> from sklearn.metrics import PredictionErrorDisplay + >>> X, y = load_diabetes(return_X_y=True) + >>> ridge = Ridge().fit(X, y) + >>> y_pred = ridge.predict(X) + >>> display = PredictionErrorDisplay(y_true=y, y_pred=y_pred) + >>> display.plot() + <...> + >>> plt.show() + """ + + def __init__(self, *, y_true, y_pred): + self.y_true = y_true + self.y_pred = y_pred + + def plot( + self, + ax=None, + *, + kind="residual_vs_predicted", + scatter_kwargs=None, + line_kwargs=None, + ): + """Plot visualization. + + Extra keyword arguments will be passed to matplotlib's ``plot``. + + Parameters + ---------- + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + kind : {"actual_vs_predicted", "residual_vs_predicted"}, \ + default="residual_vs_predicted" + The type of plot to draw: + + - "actual_vs_predicted" draws the the observed values (y-axis) vs. + the predicted values (x-axis). + - "residual_vs_predicted" draws the residuals, i.e difference + between observed and predicted values, (y-axis) vs. the predicted + values (x-axis). + + scatter_kwargs : dict, default=None + Dictionary with keywords passed to the `matplotlib.pyplot.scatter` + call. + + line_kwargs : dict, default=None + Dictionary with keyword passed to the `matplotlib.pyplot.plot` + call to draw the optimal line. + + Returns + ------- + display : :class:`~sklearn.metrics.plot.PredictionErrorDisplay` + Object that stores computed values. + """ + check_matplotlib_support(f"{self.__class__.__name__}.plot") + + expected_kind = ("actual_vs_predicted", "residual_vs_predicted") + if kind not in expected_kind: + raise ValueError( + f"`kind` must be one of {', '.join(expected_kind)}. " + f"Got {kind!r} instead." + ) + + import matplotlib.pyplot as plt + + if scatter_kwargs is None: + scatter_kwargs = {} + if line_kwargs is None: + line_kwargs = {} + + default_scatter_kwargs = {"color": "tab:blue", "alpha": 0.8} + default_line_kwargs = {"color": "black", "alpha": 0.7, "linestyle": "--"} + + scatter_kwargs = {**default_scatter_kwargs, **scatter_kwargs} + line_kwargs = {**default_line_kwargs, **line_kwargs} + + if ax is None: + _, ax = plt.subplots() + + if kind == "actual_vs_predicted": + max_value = max(np.max(self.y_true), np.max(self.y_pred)) + min_value = min(np.min(self.y_true), np.min(self.y_pred)) + self.line_ = ax.plot( + [min_value, max_value], [min_value, max_value], **line_kwargs + )[0] + + x_data, y_data = self.y_pred, self.y_true + xlabel, ylabel = "Predicted values", "Actual values" + + self.scatter_ = ax.scatter(x_data, y_data, **scatter_kwargs) + + # force to have a squared axis + ax.set_aspect("equal", adjustable="datalim") + ax.set_xticks(np.linspace(min_value, max_value, num=5)) + ax.set_yticks(np.linspace(min_value, max_value, num=5)) + else: # kind == "residual_vs_predicted" + self.line_ = ax.plot( + [np.min(self.y_pred), np.max(self.y_pred)], + [0, 0], + **line_kwargs, + )[0] + self.scatter_ = ax.scatter( + self.y_pred, self.y_true - self.y_pred, **scatter_kwargs + ) + xlabel, ylabel = "Predicted values", "Residuals (actual - predicted)" + + ax.set(xlabel=xlabel, ylabel=ylabel) + + self.ax_ = ax + self.figure_ = ax.figure + + return self + + @classmethod + def from_estimator( + cls, + estimator, + X, + y, + *, + kind="residual_vs_predicted", + subsample=1_000, + random_state=None, + ax=None, + scatter_kwargs=None, + line_kwargs=None, + ): + """Plot the prediction error given a regressor and some data. + + For general information regarding `scikit-learn` visualization tools, + read more in the :ref:`Visualization Guide `. + For details regarding interpreting these plots, refer to the + :ref:`Model Evaluation Guide `. + + .. versionadded:: 1.2 + + Parameters + ---------- + estimator : estimator instance + Fitted regressor or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a regressor. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + y : array-like of shape (n_samples,) + Target values. + + kind : {"actual_vs_predicted", "residual_vs_predicted"}, \ + default="residual_vs_predicted" + The type of plot to draw: + + - "actual_vs_predicted" draws the the observed values (y-axis) vs. + the predicted values (x-axis). + - "residual_vs_predicted" draws the residuals, i.e difference + between observed and predicted values, (y-axis) vs. the predicted + values (x-axis). + + subsample : float, int or None, default=1_000 + Sampling the samples to be shown on the scatter plot. If `float`, + it should be between 0 and 1 and represents the proportion of the + original dataset. If `int`, it represents the number of samples + display on the scatter plot. If `None`, no subsampling will be + applied. by default, a 1000 samples or less will be displayed. + + random_state : int or RandomState, default=None + Controls the randomness when `subsample` is not `None`. + See :term:`Glossary ` for details. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + scatter_kwargs : dict, default=None + Dictionary with keywords passed to the `matplotlib.pyplot.scatter` + call. + + line_kwargs : dict, default=None + Dictionary with keyword passed to the `matplotlib.pyplot.plot` + call to draw the optimal line. + + Returns + ------- + display : :class:`~sklearn.metrics.PredictionErrorDisplay` + Object that stores the computed values. + + See Also + -------- + PredictionErrorDisplay : Prediction error visualization for regression. + PredictionErrorDisplay.from_predictions : Prediction error visualization + given the true and predicted targets. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import load_diabetes + >>> from sklearn.linear_model import Ridge + >>> from sklearn.metrics import PredictionErrorDisplay + >>> X, y = load_diabetes(return_X_y=True) + >>> ridge = Ridge().fit(X, y) + >>> disp = PredictionErrorDisplay.from_estimator(ridge, X, y) + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_estimator") + + y_pred = estimator.predict(X) + + return cls.from_predictions( + y_true=y, + y_pred=y_pred, + kind=kind, + subsample=subsample, + random_state=random_state, + ax=ax, + scatter_kwargs=scatter_kwargs, + line_kwargs=line_kwargs, + ) + + @classmethod + def from_predictions( + cls, + y_true, + y_pred, + *, + kind="residual_vs_predicted", + subsample=1_000, + random_state=None, + ax=None, + scatter_kwargs=None, + line_kwargs=None, + ): + """Plot the prediction error given the true and predicted targets. + + For general information regarding `scikit-learn` visualization tools, + read more in the :ref:`Visualization Guide `. + For details regarding interpreting these plots, refer to the + :ref:`Model Evaluation Guide `. + + .. versionadded:: 1.2 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True target values. + + y_pred : array-like of shape (n_samples,) + Predicted target values. + + kind : {"actual_vs_predicted", "residual_vs_predicted"}, \ + default="residual_vs_predicted" + The type of plot to draw: + + - "actual_vs_predicted" draws the the observed values (y-axis) vs. + the predicted values (x-axis). + - "residual_vs_predicted" draws the residuals, i.e difference + between observed and predicted values, (y-axis) vs. the predicted + values (x-axis). + + subsample : float, int or None, default=1_000 + Sampling the samples to be shown on the scatter plot. If `float`, + it should be between 0 and 1 and represents the proportion of the + original dataset. If `int`, it represents the number of samples + display on the scatter plot. If `None`, no subsampling will be + applied. by default, a 1000 samples or less will be displayed. + + random_state : int or RandomState, default=None + Controls the randomness when `subsample` is not `None`. + See :term:`Glossary ` for details. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + scatter_kwargs : dict, default=None + Dictionary with keywords passed to the `matplotlib.pyplot.scatter` + call. + + line_kwargs : dict, default=None + Dictionary with keyword passed to the `matplotlib.pyplot.plot` + call to draw the optimal line. + + Returns + ------- + display : :class:`~sklearn.metrics.PredictionErrorDisplay` + Object that stores the computed values. + + See Also + -------- + PredictionErrorDisplay : Prediction error visualization for regression. + PredictionErrorDisplay.from_estimator : Prediction error visualization + given an estimator and some data. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import load_diabetes + >>> from sklearn.linear_model import Ridge + >>> from sklearn.metrics import PredictionErrorDisplay + >>> X, y = load_diabetes(return_X_y=True) + >>> ridge = Ridge().fit(X, y) + >>> y_pred = ridge.predict(X) + >>> disp = PredictionErrorDisplay.from_predictions(y_true=y, y_pred=y_pred) + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_predictions") + + random_state = check_random_state(random_state) + + n_samples = len(y_true) + if isinstance(subsample, numbers.Integral): + if subsample <= 0: + raise ValueError( + f"When an integer, subsample={subsample} should be positive." + ) + elif isinstance(subsample, numbers.Real): + if subsample <= 0 or subsample >= 1: + raise ValueError( + f"When a floating-point, subsample={subsample} should" + " be in the (0, 1) range." + ) + subsample = int(n_samples * subsample) + + if subsample is not None and subsample < n_samples: + indices = random_state.choice(np.arange(n_samples), size=subsample) + y_true = _safe_indexing(y_true, indices, axis=0) + y_pred = _safe_indexing(y_pred, indices, axis=0) + + viz = PredictionErrorDisplay( + y_true=y_true, + y_pred=y_pred, + ) + + return viz.plot( + ax=ax, + kind=kind, + scatter_kwargs=scatter_kwargs, + line_kwargs=line_kwargs, + ) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/roc_curve.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/roc_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..256183787e4707333adb0ff3af7d5201a62fff87 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/roc_curve.py @@ -0,0 +1,352 @@ +from .base import _get_response + +from .. import auc +from .. import roc_curve +from .._base import _check_pos_label_consistency + +from ...utils import check_matplotlib_support + + +class RocCurveDisplay: + """ROC Curve visualization. + + It is recommend to use + :func:`~sklearn.metrics.RocCurveDisplay.from_estimator` or + :func:`~sklearn.metrics.RocCurveDisplay.from_predictions` to create + a :class:`~sklearn.metrics.RocCurveDisplay`. All parameters are + stored as attributes. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + fpr : ndarray + False positive rate. + + tpr : ndarray + True positive rate. + + roc_auc : float, default=None + Area under ROC curve. If None, the roc_auc score is not shown. + + estimator_name : str, default=None + Name of estimator. If None, the estimator name is not shown. + + pos_label : str or int, default=None + The class considered as the positive class when computing the roc auc + metrics. By default, `estimators.classes_[1]` is considered + as the positive class. + + .. versionadded:: 0.24 + + Attributes + ---------- + line_ : matplotlib Artist + ROC Curve. + + ax_ : matplotlib Axes + Axes with ROC Curve. + + figure_ : matplotlib Figure + Figure containing the curve. + + See Also + -------- + roc_curve : Compute Receiver operating characteristic (ROC) curve. + RocCurveDisplay.from_estimator : Plot Receiver Operating Characteristic + (ROC) curve given an estimator and some data. + RocCurveDisplay.from_predictions : Plot Receiver Operating Characteristic + (ROC) curve given the true and predicted values. + roc_auc_score : Compute the area under the ROC curve. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from sklearn import metrics + >>> y = np.array([0, 0, 1, 1]) + >>> pred = np.array([0.1, 0.4, 0.35, 0.8]) + >>> fpr, tpr, thresholds = metrics.roc_curve(y, pred) + >>> roc_auc = metrics.auc(fpr, tpr) + >>> display = metrics.RocCurveDisplay(fpr=fpr, tpr=tpr, roc_auc=roc_auc, + ... estimator_name='example estimator') + >>> display.plot() + <...> + >>> plt.show() + """ + + def __init__(self, *, fpr, tpr, roc_auc=None, estimator_name=None, pos_label=None): + self.estimator_name = estimator_name + self.fpr = fpr + self.tpr = tpr + self.roc_auc = roc_auc + self.pos_label = pos_label + + def plot(self, ax=None, *, name=None, **kwargs): + """Plot visualization. + + Extra keyword arguments will be passed to matplotlib's ``plot``. + + Parameters + ---------- + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + name : str, default=None + Name of ROC Curve for labeling. If `None`, use `estimator_name` if + not `None`, otherwise no labeling is shown. + + **kwargs : dict + Keyword arguments to be passed to matplotlib's `plot`. + + Returns + ------- + display : :class:`~sklearn.metrics.plot.RocCurveDisplay` + Object that stores computed values. + """ + check_matplotlib_support("RocCurveDisplay.plot") + + name = self.estimator_name if name is None else name + + line_kwargs = {} + if self.roc_auc is not None and name is not None: + line_kwargs["label"] = f"{name} (AUC = {self.roc_auc:0.2f})" + elif self.roc_auc is not None: + line_kwargs["label"] = f"AUC = {self.roc_auc:0.2f}" + elif name is not None: + line_kwargs["label"] = name + + line_kwargs.update(**kwargs) + + import matplotlib.pyplot as plt + + if ax is None: + fig, ax = plt.subplots() + + (self.line_,) = ax.plot(self.fpr, self.tpr, **line_kwargs) + info_pos_label = ( + f" (Positive label: {self.pos_label})" if self.pos_label is not None else "" + ) + + xlabel = "False Positive Rate" + info_pos_label + ylabel = "True Positive Rate" + info_pos_label + ax.set(xlabel=xlabel, ylabel=ylabel) + + if "label" in line_kwargs: + ax.legend(loc="lower right") + + self.ax_ = ax + self.figure_ = ax.figure + return self + + @classmethod + def from_estimator( + cls, + estimator, + X, + y, + *, + sample_weight=None, + drop_intermediate=True, + response_method="auto", + pos_label=None, + name=None, + ax=None, + **kwargs, + ): + """Create a ROC Curve display from an estimator. + + Parameters + ---------- + estimator : estimator instance + Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a classifier. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + y : array-like of shape (n_samples,) + Target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + drop_intermediate : bool, default=True + Whether to drop some suboptimal thresholds which would not appear + on a plotted ROC curve. This is useful in order to create lighter + ROC curves. + + response_method : {'predict_proba', 'decision_function', 'auto'} \ + default='auto' + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the target response. If set to 'auto', + :term:`predict_proba` is tried first and if it does not exist + :term:`decision_function` is tried next. + + pos_label : str or int, default=None + The class considered as the positive class when computing the roc auc + metrics. By default, `estimators.classes_[1]` is considered + as the positive class. + + name : str, default=None + Name of ROC Curve for labeling. If `None`, use the name of the + estimator. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is created. + + **kwargs : dict + Keyword arguments to be passed to matplotlib's `plot`. + + Returns + ------- + display : :class:`~sklearn.metrics.plot.RocCurveDisplay` + The ROC Curve display. + + See Also + -------- + roc_curve : Compute Receiver operating characteristic (ROC) curve. + RocCurveDisplay.from_predictions : ROC Curve visualization given the + probabilities of scores of a classifier. + roc_auc_score : Compute the area under the ROC curve. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import RocCurveDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = SVC(random_state=0).fit(X_train, y_train) + >>> RocCurveDisplay.from_estimator( + ... clf, X_test, y_test) + <...> + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_estimator") + + name = estimator.__class__.__name__ if name is None else name + + y_pred, pos_label = _get_response( + X, + estimator, + response_method=response_method, + pos_label=pos_label, + ) + + return cls.from_predictions( + y_true=y, + y_pred=y_pred, + sample_weight=sample_weight, + drop_intermediate=drop_intermediate, + name=name, + ax=ax, + pos_label=pos_label, + **kwargs, + ) + + @classmethod + def from_predictions( + cls, + y_true, + y_pred, + *, + sample_weight=None, + drop_intermediate=True, + pos_label=None, + name=None, + ax=None, + **kwargs, + ): + """Plot ROC curve given the true and predicted values. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True labels. + + y_pred : array-like of shape (n_samples,) + Target scores, can either be probability estimates of the positive + class, confidence values, or non-thresholded measure of decisions + (as returned by “decision_function” on some classifiers). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + drop_intermediate : bool, default=True + Whether to drop some suboptimal thresholds which would not appear + on a plotted ROC curve. This is useful in order to create lighter + ROC curves. + + pos_label : str or int, default=None + The label of the positive class. When `pos_label=None`, if `y_true` + is in {-1, 1} or {0, 1}, `pos_label` is set to 1, otherwise an + error will be raised. + + name : str, default=None + Name of ROC curve for labeling. If `None`, name will be set to + `"Classifier"`. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + **kwargs : dict + Additional keywords arguments passed to matplotlib `plot` function. + + Returns + ------- + display : :class:`~sklearn.metrics.RocCurveDisplay` + Object that stores computed values. + + See Also + -------- + roc_curve : Compute Receiver operating characteristic (ROC) curve. + RocCurveDisplay.from_estimator : ROC Curve visualization given an + estimator and some data. + roc_auc_score : Compute the area under the ROC curve. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import RocCurveDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = SVC(random_state=0).fit(X_train, y_train) + >>> y_pred = clf.decision_function(X_test) + >>> RocCurveDisplay.from_predictions( + ... y_test, y_pred) + <...> + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_predictions") + + fpr, tpr, _ = roc_curve( + y_true, + y_pred, + pos_label=pos_label, + sample_weight=sample_weight, + drop_intermediate=drop_intermediate, + ) + roc_auc = auc(fpr, tpr) + + name = "Classifier" if name is None else name + pos_label = _check_pos_label_consistency(pos_label, y_true) + + viz = RocCurveDisplay( + fpr=fpr, tpr=tpr, roc_auc=roc_auc, estimator_name=name, pos_label=pos_label + ) + + return viz.plot(ax=ax, name=name, **kwargs) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__init__.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_common_curve_display.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_common_curve_display.py new file mode 100644 index 0000000000000000000000000000000000000000..5ed036b77f4d0cdde174d2611a9c1c08804595fc --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_common_curve_display.py @@ -0,0 +1,152 @@ +import pytest + +from sklearn.base import ClassifierMixin, clone +from sklearn.compose import make_column_transformer +from sklearn.datasets import load_iris +from sklearn.exceptions import NotFittedError +from sklearn.linear_model import LogisticRegression +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.tree import DecisionTreeClassifier + +from sklearn.metrics import ( + DetCurveDisplay, + PrecisionRecallDisplay, + RocCurveDisplay, +) + + +@pytest.fixture(scope="module") +def data(): + return load_iris(return_X_y=True) + + +@pytest.fixture(scope="module") +def data_binary(data): + X, y = data + return X[y < 2], y[y < 2] + + +@pytest.mark.parametrize( + "Display", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay] +) +def test_display_curve_error_non_binary(pyplot, data, Display): + """Check that a proper error is raised when only binary classification is + supported.""" + X, y = data + clf = DecisionTreeClassifier().fit(X, y) + + msg = ( + "Expected 'estimator' to be a binary classifier, but got DecisionTreeClassifier" + ) + with pytest.raises(ValueError, match=msg): + Display.from_estimator(clf, X, y) + + +@pytest.mark.parametrize( + "response_method, msg", + [ + ( + "predict_proba", + "response method predict_proba is not defined in MyClassifier", + ), + ( + "decision_function", + "response method decision_function is not defined in MyClassifier", + ), + ( + "auto", + "response method decision_function or predict_proba is not " + "defined in MyClassifier", + ), + ( + "bad_method", + "response_method must be 'predict_proba', 'decision_function' or 'auto'", + ), + ], +) +@pytest.mark.parametrize( + "Display", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay] +) +def test_display_curve_error_no_response( + pyplot, + data_binary, + response_method, + msg, + Display, +): + """Check that a proper error is raised when the response method requested + is not defined for the given trained classifier.""" + X, y = data_binary + + class MyClassifier(ClassifierMixin): + def fit(self, X, y): + self.classes_ = [0, 1] + return self + + clf = MyClassifier().fit(X, y) + + with pytest.raises(ValueError, match=msg): + Display.from_estimator(clf, X, y, response_method=response_method) + + +@pytest.mark.parametrize( + "Display", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay] +) +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_display_curve_estimator_name_multiple_calls( + pyplot, + data_binary, + Display, + constructor_name, +): + """Check that passing `name` when calling `plot` will overwrite the original name + in the legend.""" + X, y = data_binary + clf_name = "my hand-crafted name" + clf = LogisticRegression().fit(X, y) + y_pred = clf.predict_proba(X)[:, 1] + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + if constructor_name == "from_estimator": + disp = Display.from_estimator(clf, X, y, name=clf_name) + else: + disp = Display.from_predictions(y, y_pred, name=clf_name) + assert disp.estimator_name == clf_name + pyplot.close("all") + disp.plot() + assert clf_name in disp.line_.get_label() + pyplot.close("all") + clf_name = "another_name" + disp.plot(name=clf_name) + assert clf_name in disp.line_.get_label() + + +@pytest.mark.parametrize( + "clf", + [ + LogisticRegression(), + make_pipeline(StandardScaler(), LogisticRegression()), + make_pipeline( + make_column_transformer((StandardScaler(), [0, 1])), LogisticRegression() + ), + ], +) +@pytest.mark.parametrize( + "Display", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay] +) +def test_display_curve_not_fitted_errors(pyplot, data_binary, clf, Display): + """Check that a proper error is raised when the classifier is not + fitted.""" + X, y = data_binary + # clone since we parametrize the test and the classifier will be fitted + # when testing the second and subsequent plotting function + model = clone(clf) + with pytest.raises(NotFittedError): + Display.from_estimator(model, X, y) + model.fit(X, y) + disp = Display.from_estimator(model, X, y) + assert model.__class__.__name__ in disp.line_.get_label() + assert disp.estimator_name == model.__class__.__name__ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py new file mode 100644 index 0000000000000000000000000000000000000000..ffead416f3ddc026a0cb45fd00e7b034b2ff6cb0 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py @@ -0,0 +1,407 @@ +from numpy.testing import ( + assert_allclose, + assert_array_equal, +) +import numpy as np +import pytest + +from sklearn.datasets import make_classification +from sklearn.compose import make_column_transformer +from sklearn.exceptions import NotFittedError +from sklearn.linear_model import LogisticRegression +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.svm import SVC, SVR + +from sklearn.metrics import ConfusionMatrixDisplay +from sklearn.metrics import confusion_matrix + + +# TODO: Remove when https://github.com/numpy/numpy/issues/14397 is resolved +pytestmark = pytest.mark.filterwarnings( + "ignore:In future, it will be an error for 'np.bool_':DeprecationWarning:" + "matplotlib.*" +) + + +def test_confusion_matrix_display_validation(pyplot): + """Check that we raise the proper error when validating parameters.""" + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=5, random_state=0 + ) + + with pytest.raises(NotFittedError): + ConfusionMatrixDisplay.from_estimator(SVC(), X, y) + + regressor = SVR().fit(X, y) + y_pred_regressor = regressor.predict(X) + y_pred_classifier = SVC().fit(X, y).predict(X) + + err_msg = "ConfusionMatrixDisplay.from_estimator only supports classifiers" + with pytest.raises(ValueError, match=err_msg): + ConfusionMatrixDisplay.from_estimator(regressor, X, y) + + err_msg = "Mix type of y not allowed, got types" + with pytest.raises(ValueError, match=err_msg): + # Force `y_true` to be seen as a regression problem + ConfusionMatrixDisplay.from_predictions(y + 0.5, y_pred_classifier) + with pytest.raises(ValueError, match=err_msg): + ConfusionMatrixDisplay.from_predictions(y, y_pred_regressor) + + err_msg = "Found input variables with inconsistent numbers of samples" + with pytest.raises(ValueError, match=err_msg): + ConfusionMatrixDisplay.from_predictions(y, y_pred_classifier[::2]) + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_confusion_matrix_display_invalid_option(pyplot, constructor_name): + """Check the error raise if an invalid parameter value is passed.""" + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=5, random_state=0 + ) + classifier = SVC().fit(X, y) + y_pred = classifier.predict(X) + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + extra_params = {"normalize": "invalid"} + + err_msg = r"normalize must be one of \{'true', 'pred', 'all', None\}" + with pytest.raises(ValueError, match=err_msg): + if constructor_name == "from_estimator": + ConfusionMatrixDisplay.from_estimator(classifier, X, y, **extra_params) + else: + ConfusionMatrixDisplay.from_predictions(y, y_pred, **extra_params) + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize("with_labels", [True, False]) +@pytest.mark.parametrize("with_display_labels", [True, False]) +def test_confusion_matrix_display_custom_labels( + pyplot, constructor_name, with_labels, with_display_labels +): + """Check the resulting plot when labels are given.""" + n_classes = 5 + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=n_classes, random_state=0 + ) + classifier = SVC().fit(X, y) + y_pred = classifier.predict(X) + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + ax = pyplot.gca() + labels = [2, 1, 0, 3, 4] if with_labels else None + display_labels = ["b", "d", "a", "e", "f"] if with_display_labels else None + + cm = confusion_matrix(y, y_pred, labels=labels) + common_kwargs = { + "ax": ax, + "display_labels": display_labels, + "labels": labels, + } + if constructor_name == "from_estimator": + disp = ConfusionMatrixDisplay.from_estimator(classifier, X, y, **common_kwargs) + else: + disp = ConfusionMatrixDisplay.from_predictions(y, y_pred, **common_kwargs) + assert_allclose(disp.confusion_matrix, cm) + + if with_display_labels: + expected_display_labels = display_labels + elif with_labels: + expected_display_labels = labels + else: + expected_display_labels = list(range(n_classes)) + + expected_display_labels_str = [str(name) for name in expected_display_labels] + + x_ticks = [tick.get_text() for tick in disp.ax_.get_xticklabels()] + y_ticks = [tick.get_text() for tick in disp.ax_.get_yticklabels()] + + assert_array_equal(disp.display_labels, expected_display_labels) + assert_array_equal(x_ticks, expected_display_labels_str) + assert_array_equal(y_ticks, expected_display_labels_str) + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize("normalize", ["true", "pred", "all", None]) +@pytest.mark.parametrize("include_values", [True, False]) +def test_confusion_matrix_display_plotting( + pyplot, + constructor_name, + normalize, + include_values, +): + """Check the overall plotting rendering.""" + n_classes = 5 + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=n_classes, random_state=0 + ) + classifier = SVC().fit(X, y) + y_pred = classifier.predict(X) + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + ax = pyplot.gca() + cmap = "plasma" + + cm = confusion_matrix(y, y_pred) + common_kwargs = { + "normalize": normalize, + "cmap": cmap, + "ax": ax, + "include_values": include_values, + } + if constructor_name == "from_estimator": + disp = ConfusionMatrixDisplay.from_estimator(classifier, X, y, **common_kwargs) + else: + disp = ConfusionMatrixDisplay.from_predictions(y, y_pred, **common_kwargs) + + assert disp.ax_ == ax + + if normalize == "true": + cm = cm / cm.sum(axis=1, keepdims=True) + elif normalize == "pred": + cm = cm / cm.sum(axis=0, keepdims=True) + elif normalize == "all": + cm = cm / cm.sum() + + assert_allclose(disp.confusion_matrix, cm) + import matplotlib as mpl + + assert isinstance(disp.im_, mpl.image.AxesImage) + assert disp.im_.get_cmap().name == cmap + assert isinstance(disp.ax_, pyplot.Axes) + assert isinstance(disp.figure_, pyplot.Figure) + + assert disp.ax_.get_ylabel() == "True label" + assert disp.ax_.get_xlabel() == "Predicted label" + + x_ticks = [tick.get_text() for tick in disp.ax_.get_xticklabels()] + y_ticks = [tick.get_text() for tick in disp.ax_.get_yticklabels()] + + expected_display_labels = list(range(n_classes)) + + expected_display_labels_str = [str(name) for name in expected_display_labels] + + assert_array_equal(disp.display_labels, expected_display_labels) + assert_array_equal(x_ticks, expected_display_labels_str) + assert_array_equal(y_ticks, expected_display_labels_str) + + image_data = disp.im_.get_array().data + assert_allclose(image_data, cm) + + if include_values: + assert disp.text_.shape == (n_classes, n_classes) + fmt = ".2g" + expected_text = np.array([format(v, fmt) for v in cm.ravel(order="C")]) + text_text = np.array([t.get_text() for t in disp.text_.ravel(order="C")]) + assert_array_equal(expected_text, text_text) + else: + assert disp.text_ is None + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_confusion_matrix_display(pyplot, constructor_name): + """Check the behaviour of the default constructor without using the class + methods.""" + n_classes = 5 + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=n_classes, random_state=0 + ) + classifier = SVC().fit(X, y) + y_pred = classifier.predict(X) + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + cm = confusion_matrix(y, y_pred) + common_kwargs = { + "normalize": None, + "include_values": True, + "cmap": "viridis", + "xticks_rotation": 45.0, + } + if constructor_name == "from_estimator": + disp = ConfusionMatrixDisplay.from_estimator(classifier, X, y, **common_kwargs) + else: + disp = ConfusionMatrixDisplay.from_predictions(y, y_pred, **common_kwargs) + + assert_allclose(disp.confusion_matrix, cm) + assert disp.text_.shape == (n_classes, n_classes) + + rotations = [tick.get_rotation() for tick in disp.ax_.get_xticklabels()] + assert_allclose(rotations, 45.0) + + image_data = disp.im_.get_array().data + assert_allclose(image_data, cm) + + disp.plot(cmap="plasma") + assert disp.im_.get_cmap().name == "plasma" + + disp.plot(include_values=False) + assert disp.text_ is None + + disp.plot(xticks_rotation=90.0) + rotations = [tick.get_rotation() for tick in disp.ax_.get_xticklabels()] + assert_allclose(rotations, 90.0) + + disp.plot(values_format="e") + expected_text = np.array([format(v, "e") for v in cm.ravel(order="C")]) + text_text = np.array([t.get_text() for t in disp.text_.ravel(order="C")]) + assert_array_equal(expected_text, text_text) + + +def test_confusion_matrix_contrast(pyplot): + """Check that the text color is appropriate depending on background.""" + + cm = np.eye(2) / 2 + disp = ConfusionMatrixDisplay(cm, display_labels=[0, 1]) + + disp.plot(cmap=pyplot.cm.gray) + # diagonal text is black + assert_allclose(disp.text_[0, 0].get_color(), [0.0, 0.0, 0.0, 1.0]) + assert_allclose(disp.text_[1, 1].get_color(), [0.0, 0.0, 0.0, 1.0]) + + # off-diagonal text is white + assert_allclose(disp.text_[0, 1].get_color(), [1.0, 1.0, 1.0, 1.0]) + assert_allclose(disp.text_[1, 0].get_color(), [1.0, 1.0, 1.0, 1.0]) + + disp.plot(cmap=pyplot.cm.gray_r) + # diagonal text is white + assert_allclose(disp.text_[0, 1].get_color(), [0.0, 0.0, 0.0, 1.0]) + assert_allclose(disp.text_[1, 0].get_color(), [0.0, 0.0, 0.0, 1.0]) + + # off-diagonal text is black + assert_allclose(disp.text_[0, 0].get_color(), [1.0, 1.0, 1.0, 1.0]) + assert_allclose(disp.text_[1, 1].get_color(), [1.0, 1.0, 1.0, 1.0]) + + # Regression test for #15920 + cm = np.array([[19, 34], [32, 58]]) + disp = ConfusionMatrixDisplay(cm, display_labels=[0, 1]) + + disp.plot(cmap=pyplot.cm.Blues) + min_color = pyplot.cm.Blues(0) + max_color = pyplot.cm.Blues(255) + assert_allclose(disp.text_[0, 0].get_color(), max_color) + assert_allclose(disp.text_[0, 1].get_color(), max_color) + assert_allclose(disp.text_[1, 0].get_color(), max_color) + assert_allclose(disp.text_[1, 1].get_color(), min_color) + + +@pytest.mark.parametrize( + "clf", + [ + LogisticRegression(), + make_pipeline(StandardScaler(), LogisticRegression()), + make_pipeline( + make_column_transformer((StandardScaler(), [0, 1])), + LogisticRegression(), + ), + ], + ids=["clf", "pipeline-clf", "pipeline-column_transformer-clf"], +) +def test_confusion_matrix_pipeline(pyplot, clf): + """Check the behaviour of the plotting with more complex pipeline.""" + n_classes = 5 + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=n_classes, random_state=0 + ) + with pytest.raises(NotFittedError): + ConfusionMatrixDisplay.from_estimator(clf, X, y) + clf.fit(X, y) + y_pred = clf.predict(X) + + disp = ConfusionMatrixDisplay.from_estimator(clf, X, y) + cm = confusion_matrix(y, y_pred) + + assert_allclose(disp.confusion_matrix, cm) + assert disp.text_.shape == (n_classes, n_classes) + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_confusion_matrix_with_unknown_labels(pyplot, constructor_name): + """Check that when labels=None, the unique values in `y_pred` and `y_true` + will be used. + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/pull/18405 + """ + n_classes = 5 + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=n_classes, random_state=0 + ) + classifier = SVC().fit(X, y) + y_pred = classifier.predict(X) + # create unseen labels in `y_true` not seen during fitting and not present + # in 'classifier.classes_' + y = y + 1 + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + common_kwargs = {"labels": None} + if constructor_name == "from_estimator": + disp = ConfusionMatrixDisplay.from_estimator(classifier, X, y, **common_kwargs) + else: + disp = ConfusionMatrixDisplay.from_predictions(y, y_pred, **common_kwargs) + + display_labels = [tick.get_text() for tick in disp.ax_.get_xticklabels()] + expected_labels = [str(i) for i in range(n_classes + 1)] + assert_array_equal(expected_labels, display_labels) + + +def test_colormap_max(pyplot): + """Check that the max color is used for the color of the text.""" + + from matplotlib import cm + + gray = cm.get_cmap("gray", 1024) + confusion_matrix = np.array([[1.0, 0.0], [0.0, 1.0]]) + + disp = ConfusionMatrixDisplay(confusion_matrix) + disp.plot(cmap=gray) + + color = disp.text_[1, 0].get_color() + assert_allclose(color, [1.0, 1.0, 1.0, 1.0]) + + +def test_im_kw_adjust_vmin_vmax(pyplot): + """Check that im_kw passes kwargs to imshow""" + + confusion_matrix = np.array([[0.48, 0.04], [0.08, 0.4]]) + disp = ConfusionMatrixDisplay(confusion_matrix) + disp.plot(im_kw=dict(vmin=0.0, vmax=0.8)) + + clim = disp.im_.get_clim() + assert clim[0] == pytest.approx(0.0) + assert clim[1] == pytest.approx(0.8) + + +def test_confusion_matrix_text_kw(pyplot): + """Check that text_kw is passed to the text call.""" + font_size = 15.0 + X, y = make_classification(random_state=0) + classifier = SVC().fit(X, y) + + # from_estimator passes the font size + disp = ConfusionMatrixDisplay.from_estimator( + classifier, X, y, text_kw={"fontsize": font_size} + ) + for text in disp.text_.reshape(-1): + assert text.get_fontsize() == font_size + + # plot adjusts plot to new font size + new_font_size = 20.0 + disp.plot(text_kw={"fontsize": new_font_size}) + for text in disp.text_.reshape(-1): + assert text.get_fontsize() == new_font_size + + # from_predictions passes the font size + y_pred = classifier.predict(X) + disp = ConfusionMatrixDisplay.from_predictions( + y, y_pred, text_kw={"fontsize": font_size} + ) + for text in disp.text_.reshape(-1): + assert text.get_fontsize() == font_size diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_precision_recall_display.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_precision_recall_display.py new file mode 100644 index 0000000000000000000000000000000000000000..4d514fa1f32b3988bd7cfd6de078132274dcad50 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_precision_recall_display.py @@ -0,0 +1,292 @@ +import numpy as np +import pytest + +from sklearn.compose import make_column_transformer +from sklearn.datasets import load_breast_cancer, make_classification +from sklearn.exceptions import NotFittedError +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import average_precision_score, precision_recall_curve +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.svm import SVC, SVR +from sklearn.utils import shuffle + +from sklearn.metrics import PrecisionRecallDisplay + +# TODO: Remove when https://github.com/numpy/numpy/issues/14397 is resolved +pytestmark = pytest.mark.filterwarnings( + "ignore:In future, it will be an error for 'np.bool_':DeprecationWarning:" + "matplotlib.*" +) + + +def test_precision_recall_display_validation(pyplot): + """Check that we raise the proper error when validating parameters.""" + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=5, random_state=0 + ) + + with pytest.raises(NotFittedError): + PrecisionRecallDisplay.from_estimator(SVC(), X, y) + + regressor = SVR().fit(X, y) + y_pred_regressor = regressor.predict(X) + classifier = SVC(probability=True).fit(X, y) + y_pred_classifier = classifier.predict_proba(X)[:, -1] + + err_msg = "PrecisionRecallDisplay.from_estimator only supports classifiers" + with pytest.raises(ValueError, match=err_msg): + PrecisionRecallDisplay.from_estimator(regressor, X, y) + + err_msg = "Expected 'estimator' to be a binary classifier, but got SVC" + with pytest.raises(ValueError, match=err_msg): + PrecisionRecallDisplay.from_estimator(classifier, X, y) + + err_msg = "{} format is not supported" + with pytest.raises(ValueError, match=err_msg.format("continuous")): + # Force `y_true` to be seen as a regression problem + PrecisionRecallDisplay.from_predictions(y + 0.5, y_pred_classifier, pos_label=1) + with pytest.raises(ValueError, match=err_msg.format("multiclass")): + PrecisionRecallDisplay.from_predictions(y, y_pred_regressor, pos_label=1) + + err_msg = "Found input variables with inconsistent numbers of samples" + with pytest.raises(ValueError, match=err_msg): + PrecisionRecallDisplay.from_predictions(y, y_pred_classifier[::2]) + + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + y += 10 + classifier.fit(X, y) + y_pred_classifier = classifier.predict_proba(X)[:, -1] + err_msg = r"y_true takes value in {10, 11} and pos_label is not specified" + with pytest.raises(ValueError, match=err_msg): + PrecisionRecallDisplay.from_predictions(y, y_pred_classifier) + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) +def test_precision_recall_display_plotting(pyplot, constructor_name, response_method): + """Check the overall plotting rendering.""" + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + pos_label = 1 + + classifier = LogisticRegression().fit(X, y) + classifier.fit(X, y) + + y_pred = getattr(classifier, response_method)(X) + y_pred = y_pred if y_pred.ndim == 1 else y_pred[:, pos_label] + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator( + classifier, X, y, response_method=response_method + ) + else: + display = PrecisionRecallDisplay.from_predictions( + y, y_pred, pos_label=pos_label + ) + + precision, recall, _ = precision_recall_curve(y, y_pred, pos_label=pos_label) + average_precision = average_precision_score(y, y_pred, pos_label=pos_label) + + np.testing.assert_allclose(display.precision, precision) + np.testing.assert_allclose(display.recall, recall) + assert display.average_precision == pytest.approx(average_precision) + + import matplotlib as mpl + + assert isinstance(display.line_, mpl.lines.Line2D) + assert isinstance(display.ax_, mpl.axes.Axes) + assert isinstance(display.figure_, mpl.figure.Figure) + + assert display.ax_.get_xlabel() == "Recall (Positive label: 1)" + assert display.ax_.get_ylabel() == "Precision (Positive label: 1)" + + # plotting passing some new parameters + display.plot(alpha=0.8, name="MySpecialEstimator") + expected_label = f"MySpecialEstimator (AP = {average_precision:0.2f})" + assert display.line_.get_label() == expected_label + assert display.line_.get_alpha() == pytest.approx(0.8) + + +@pytest.mark.parametrize( + "constructor_name, default_label", + [ + ("from_estimator", "LogisticRegression (AP = {:.2f})"), + ("from_predictions", "Classifier (AP = {:.2f})"), + ], +) +def test_precision_recall_display_name(pyplot, constructor_name, default_label): + """Check the behaviour of the name parameters""" + X, y = make_classification(n_classes=2, n_samples=100, random_state=0) + pos_label = 1 + + classifier = LogisticRegression().fit(X, y) + classifier.fit(X, y) + + y_pred = classifier.predict_proba(X)[:, pos_label] + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator(classifier, X, y) + else: + display = PrecisionRecallDisplay.from_predictions( + y, y_pred, pos_label=pos_label + ) + + average_precision = average_precision_score(y, y_pred, pos_label=pos_label) + + # check that the default name is used + assert display.line_.get_label() == default_label.format(average_precision) + + # check that the name can be set + display.plot(name="MySpecialEstimator") + assert ( + display.line_.get_label() + == f"MySpecialEstimator (AP = {average_precision:.2f})" + ) + + +@pytest.mark.parametrize( + "clf", + [ + make_pipeline(StandardScaler(), LogisticRegression()), + make_pipeline( + make_column_transformer((StandardScaler(), [0, 1])), LogisticRegression() + ), + ], +) +def test_precision_recall_display_pipeline(pyplot, clf): + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + with pytest.raises(NotFittedError): + PrecisionRecallDisplay.from_estimator(clf, X, y) + clf.fit(X, y) + display = PrecisionRecallDisplay.from_estimator(clf, X, y) + assert display.estimator_name == clf.__class__.__name__ + + +def test_precision_recall_display_string_labels(pyplot): + # regression test #15738 + cancer = load_breast_cancer() + X, y = cancer.data, cancer.target_names[cancer.target] + + lr = make_pipeline(StandardScaler(), LogisticRegression()) + lr.fit(X, y) + for klass in cancer.target_names: + assert klass in lr.classes_ + display = PrecisionRecallDisplay.from_estimator(lr, X, y) + + y_pred = lr.predict_proba(X)[:, 1] + avg_prec = average_precision_score(y, y_pred, pos_label=lr.classes_[1]) + + assert display.average_precision == pytest.approx(avg_prec) + assert display.estimator_name == lr.__class__.__name__ + + err_msg = r"y_true takes value in {'benign', 'malignant'}" + with pytest.raises(ValueError, match=err_msg): + PrecisionRecallDisplay.from_predictions(y, y_pred) + + display = PrecisionRecallDisplay.from_predictions( + y, y_pred, pos_label=lr.classes_[1] + ) + assert display.average_precision == pytest.approx(avg_prec) + + +@pytest.mark.parametrize( + "average_precision, estimator_name, expected_label", + [ + (0.9, None, "AP = 0.90"), + (None, "my_est", "my_est"), + (0.8, "my_est2", "my_est2 (AP = 0.80)"), + ], +) +def test_default_labels(pyplot, average_precision, estimator_name, expected_label): + """Check the default labels used in the display.""" + precision = np.array([1, 0.5, 0]) + recall = np.array([0, 0.5, 1]) + display = PrecisionRecallDisplay( + precision, + recall, + average_precision=average_precision, + estimator_name=estimator_name, + ) + display.plot() + assert display.line_.get_label() == expected_label + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) +def test_plot_precision_recall_pos_label(pyplot, constructor_name, response_method): + # check that we can provide the positive label and display the proper + # statistics + X, y = load_breast_cancer(return_X_y=True) + # create an highly imbalanced version of the breast cancer dataset + 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() + classifier.fit(X_train, y_train) + + # sanity check to be sure the positive class is classes_[0] and that we + # are betrayed by the class imbalance + assert classifier.classes_.tolist() == ["cancer", "not cancer"] + + y_pred = getattr(classifier, response_method)(X_test) + # we select the corresponding probability columns or reverse the decision + # function otherwise + y_pred_cancer = -1 * y_pred if y_pred.ndim == 1 else y_pred[:, 0] + y_pred_not_cancer = y_pred if y_pred.ndim == 1 else y_pred[:, 1] + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator( + classifier, + X_test, + y_test, + pos_label="cancer", + response_method=response_method, + ) + else: + display = PrecisionRecallDisplay.from_predictions( + y_test, + y_pred_cancer, + pos_label="cancer", + ) + # we should obtain the statistics of the "cancer" class + avg_prec_limit = 0.65 + assert display.average_precision < avg_prec_limit + assert -np.trapz(display.precision, display.recall) < avg_prec_limit + + # otherwise we should obtain the statistics of the "not cancer" class + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator( + classifier, + X_test, + y_test, + response_method=response_method, + pos_label="not cancer", + ) + else: + display = PrecisionRecallDisplay.from_predictions( + y_test, + y_pred_not_cancer, + pos_label="not cancer", + ) + avg_prec_limit = 0.95 + assert display.average_precision > avg_prec_limit + assert -np.trapz(display.precision, display.recall) > avg_prec_limit diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_predict_error_display.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_predict_error_display.py new file mode 100644 index 0000000000000000000000000000000000000000..3d3833d825360a4e06f532276d21c29bfd86c7e1 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_predict_error_display.py @@ -0,0 +1,163 @@ +import pytest + +from numpy.testing import assert_allclose + +from sklearn.datasets import load_diabetes +from sklearn.exceptions import NotFittedError +from sklearn.linear_model import Ridge + +from sklearn.metrics import PredictionErrorDisplay + +X, y = load_diabetes(return_X_y=True) + + +@pytest.fixture +def regressor_fitted(): + return Ridge().fit(X, y) + + +@pytest.mark.parametrize( + "regressor, params, err_type, err_msg", + [ + ( + Ridge().fit(X, y), + {"subsample": -1}, + ValueError, + "When an integer, subsample=-1 should be", + ), + ( + Ridge().fit(X, y), + {"subsample": 20.0}, + ValueError, + "When a floating-point, subsample=20.0 should be", + ), + ( + Ridge().fit(X, y), + {"subsample": -20.0}, + ValueError, + "When a floating-point, subsample=-20.0 should be", + ), + ( + Ridge().fit(X, y), + {"kind": "xxx"}, + ValueError, + "`kind` must be one of", + ), + ], +) +@pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"]) +def test_prediction_error_display_raise_error( + pyplot, class_method, regressor, params, err_type, err_msg +): + """Check that we raise the proper error when making the parameters + # validation.""" + with pytest.raises(err_type, match=err_msg): + if class_method == "from_estimator": + PredictionErrorDisplay.from_estimator(regressor, X, y, **params) + else: + y_pred = regressor.predict(X) + PredictionErrorDisplay.from_predictions(y_true=y, y_pred=y_pred, **params) + + +def test_from_estimator_not_fitted(pyplot): + """Check that we raise a `NotFittedError` when the passed regressor is not + fit.""" + regressor = Ridge() + with pytest.raises(NotFittedError, match="is not fitted yet."): + PredictionErrorDisplay.from_estimator(regressor, X, y) + + +@pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize("kind", ["actual_vs_predicted", "residual_vs_predicted"]) +def test_prediction_error_display(pyplot, regressor_fitted, class_method, kind): + """Check the default behaviour of the display.""" + if class_method == "from_estimator": + display = PredictionErrorDisplay.from_estimator( + regressor_fitted, X, y, kind=kind + ) + else: + y_pred = regressor_fitted.predict(X) + display = PredictionErrorDisplay.from_predictions( + y_true=y, y_pred=y_pred, kind=kind + ) + + if kind == "actual_vs_predicted": + assert_allclose(display.line_.get_xdata(), display.line_.get_ydata()) + assert display.ax_.get_xlabel() == "Predicted values" + assert display.ax_.get_ylabel() == "Actual values" + assert display.line_ is not None + else: + assert display.ax_.get_xlabel() == "Predicted values" + assert display.ax_.get_ylabel() == "Residuals (actual - predicted)" + assert display.line_ is not None + + assert display.ax_.get_legend() is None + + +@pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize( + "subsample, expected_size", + [(5, 5), (0.1, int(X.shape[0] * 0.1)), (None, X.shape[0])], +) +def test_plot_prediction_error_subsample( + pyplot, regressor_fitted, class_method, subsample, expected_size +): + """Check the behaviour of `subsample`.""" + if class_method == "from_estimator": + display = PredictionErrorDisplay.from_estimator( + regressor_fitted, X, y, subsample=subsample + ) + else: + y_pred = regressor_fitted.predict(X) + display = PredictionErrorDisplay.from_predictions( + y_true=y, y_pred=y_pred, subsample=subsample + ) + assert len(display.scatter_.get_offsets()) == expected_size + + +@pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"]) +def test_plot_prediction_error_ax(pyplot, regressor_fitted, class_method): + """Check that we can pass an axis to the display.""" + _, ax = pyplot.subplots() + if class_method == "from_estimator": + display = PredictionErrorDisplay.from_estimator(regressor_fitted, X, y, ax=ax) + else: + y_pred = regressor_fitted.predict(X) + display = PredictionErrorDisplay.from_predictions( + y_true=y, y_pred=y_pred, ax=ax + ) + assert display.ax_ is ax + + +@pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"]) +def test_prediction_error_custom_artist(pyplot, regressor_fitted, class_method): + """Check that we can tune the style of the lines.""" + extra_params = { + "kind": "actual_vs_predicted", + "scatter_kwargs": {"color": "red"}, + "line_kwargs": {"color": "black"}, + } + if class_method == "from_estimator": + display = PredictionErrorDisplay.from_estimator( + regressor_fitted, X, y, **extra_params + ) + else: + y_pred = regressor_fitted.predict(X) + display = PredictionErrorDisplay.from_predictions( + y_true=y, y_pred=y_pred, **extra_params + ) + + assert display.line_.get_color() == "black" + assert_allclose(display.scatter_.get_edgecolor(), [[1.0, 0.0, 0.0, 0.8]]) + + # create a display with the default values + if class_method == "from_estimator": + display = PredictionErrorDisplay.from_estimator(regressor_fitted, X, y) + else: + y_pred = regressor_fitted.predict(X) + display = PredictionErrorDisplay.from_predictions(y_true=y, y_pred=y_pred) + pyplot.close("all") + + display.plot(**extra_params) + assert display.line_.get_color() == "black" + assert_allclose(display.scatter_.get_edgecolor(), [[1.0, 0.0, 0.0, 0.8]]) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_regression.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..05d424c7b7cf2a38f2c531389798506bdad21469 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_regression.py @@ -0,0 +1,1497 @@ +"""Metrics to assess performance on regression task. + +Functions named as ``*_score`` return a scalar value to maximize: the higher +the better. + +Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: +the lower the better. +""" + +# Authors: Alexandre Gramfort +# Mathieu Blondel +# Olivier Grisel +# Arnaud Joly +# Jochen Wersdorfer +# Lars Buitinck +# Joel Nothman +# Karan Desai +# Noel Dawe +# Manoj Kumar +# Michael Eickenberg +# Konstantin Shmelkov +# Christian Lorentzen +# Ashutosh Hathidara +# Uttam kumar +# Sylvain Marie +# Ohad Michel +# License: BSD 3 clause + +import numbers +import warnings + +import numpy as np +from scipy.special import xlogy + +from ..exceptions import UndefinedMetricWarning +from ..utils.validation import ( + check_array, + check_consistent_length, + check_scalar, + _num_samples, + column_or_1d, + _check_sample_weight, +) +from ..utils.stats import _weighted_percentile + + +__ALL__ = [ + "max_error", + "mean_absolute_error", + "mean_squared_error", + "mean_squared_log_error", + "median_absolute_error", + "mean_absolute_percentage_error", + "mean_pinball_loss", + "r2_score", + "explained_variance_score", + "mean_tweedie_deviance", + "mean_poisson_deviance", + "mean_gamma_deviance", + "d2_tweedie_score", + "d2_pinball_score", + "d2_absolute_error_score", +] + + +def _check_reg_targets(y_true, y_pred, multioutput, dtype="numeric"): + """Check that y_true and y_pred belong to the same regression task. + + Parameters + ---------- + y_true : array-like + + y_pred : array-like + + multioutput : array-like or string in ['raw_values', uniform_average', + 'variance_weighted'] or None + None is accepted due to backward compatibility of r2_score(). + + dtype : str or list, default="numeric" + the dtype argument passed to check_array. + + Returns + ------- + type_true : one of {'continuous', continuous-multioutput'} + The type of the true target data, as output by + 'utils.multiclass.type_of_target'. + + y_true : array-like of shape (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples, n_outputs) + Estimated target values. + + multioutput : array-like of shape (n_outputs) or string in ['raw_values', + uniform_average', 'variance_weighted'] or None + Custom output weights if ``multioutput`` is array-like or + just the corresponding argument if ``multioutput`` is a + correct keyword. + """ + check_consistent_length(y_true, y_pred) + y_true = check_array(y_true, ensure_2d=False, dtype=dtype) + y_pred = check_array(y_pred, ensure_2d=False, dtype=dtype) + + if y_true.ndim == 1: + y_true = y_true.reshape((-1, 1)) + + if y_pred.ndim == 1: + y_pred = y_pred.reshape((-1, 1)) + + if y_true.shape[1] != y_pred.shape[1]: + raise ValueError( + "y_true and y_pred have different number of output ({0}!={1})".format( + y_true.shape[1], y_pred.shape[1] + ) + ) + + n_outputs = y_true.shape[1] + allowed_multioutput_str = ("raw_values", "uniform_average", "variance_weighted") + if isinstance(multioutput, str): + if multioutput not in allowed_multioutput_str: + raise ValueError( + "Allowed 'multioutput' string values are {}. " + "You provided multioutput={!r}".format( + allowed_multioutput_str, multioutput + ) + ) + elif multioutput is not None: + multioutput = check_array(multioutput, ensure_2d=False) + if n_outputs == 1: + raise ValueError("Custom weights are useful only in multi-output cases.") + elif n_outputs != len(multioutput): + raise ValueError( + "There must be equally many custom weights (%d) as outputs (%d)." + % (len(multioutput), n_outputs) + ) + y_type = "continuous" if n_outputs == 1 else "continuous-multioutput" + + return y_type, y_true, y_pred, multioutput + + +def mean_absolute_error( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """Mean absolute error regression loss. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or ndarray of floats + If multioutput is 'raw_values', then mean absolute error is returned + for each output separately. + If multioutput is 'uniform_average' or an ndarray of weights, then the + weighted average of all output errors is returned. + + MAE output is non-negative floating point. The best value is 0.0. + + Examples + -------- + >>> from sklearn.metrics import mean_absolute_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_absolute_error(y_true, y_pred) + 0.5 + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> mean_absolute_error(y_true, y_pred) + 0.75 + >>> mean_absolute_error(y_true, y_pred, multioutput='raw_values') + array([0.5, 1. ]) + >>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.85... + """ + y_type, y_true, y_pred, multioutput = _check_reg_targets( + y_true, y_pred, multioutput + ) + check_consistent_length(y_true, y_pred, sample_weight) + output_errors = np.average(np.abs(y_pred - y_true), weights=sample_weight, axis=0) + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to np.average: uniform mean + multioutput = None + + return np.average(output_errors, weights=multioutput) + + +def mean_pinball_loss( + y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput="uniform_average" +): + """Pinball loss for quantile regression. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + alpha : float, slope of the pinball loss, default=0.5, + This loss is equivalent to :ref:`mean_absolute_error` when `alpha=0.5`, + `alpha=0.95` is minimized by estimators of the 95th percentile. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or ndarray of floats + If multioutput is 'raw_values', then mean absolute error is returned + for each output separately. + If multioutput is 'uniform_average' or an ndarray of weights, then the + weighted average of all output errors is returned. + + The pinball loss output is a non-negative floating point. The best + value is 0.0. + + Examples + -------- + >>> from sklearn.metrics import mean_pinball_loss + >>> y_true = [1, 2, 3] + >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1) + 0.03... + >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1) + 0.3... + >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9) + 0.3... + >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9) + 0.03... + >>> mean_pinball_loss(y_true, y_true, alpha=0.1) + 0.0 + >>> mean_pinball_loss(y_true, y_true, alpha=0.9) + 0.0 + """ + y_type, y_true, y_pred, multioutput = _check_reg_targets( + y_true, y_pred, multioutput + ) + check_consistent_length(y_true, y_pred, sample_weight) + diff = y_true - y_pred + sign = (diff >= 0).astype(diff.dtype) + loss = alpha * sign * diff - (1 - alpha) * (1 - sign) * diff + output_errors = np.average(loss, weights=sample_weight, axis=0) + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to np.average: uniform mean + multioutput = None + else: + raise ValueError( + "multioutput is expected to be 'raw_values' " + "or 'uniform_average' but we got %r" + " instead." % multioutput + ) + + return np.average(output_errors, weights=multioutput) + + +def mean_absolute_percentage_error( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """Mean absolute percentage error (MAPE) regression loss. + + Note here that the output is not a percentage in the range [0, 100] + and a value of 100 does not mean 100% but 1e2. Furthermore, the output + can be arbitrarily high when `y_true` is small (which is specific to the + metric) or when `abs(y_true - y_pred)` is large (which is common for most + regression metrics). Read more in the + :ref:`User Guide `. + + .. versionadded:: 0.24 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + If input is list then the shape must be (n_outputs,). + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or ndarray of floats + If multioutput is 'raw_values', then mean absolute percentage error + is returned for each output separately. + If multioutput is 'uniform_average' or an ndarray of weights, then the + weighted average of all output errors is returned. + + MAPE output is non-negative floating point. The best value is 0.0. + But note that bad predictions can lead to arbitrarily large + MAPE values, especially if some `y_true` values are very close to zero. + Note that we return a large value instead of `inf` when `y_true` is zero. + + Examples + -------- + >>> from sklearn.metrics import mean_absolute_percentage_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_absolute_percentage_error(y_true, y_pred) + 0.3273... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> mean_absolute_percentage_error(y_true, y_pred) + 0.5515... + >>> mean_absolute_percentage_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.6198... + >>> # the value when some element of the y_true is zero is arbitrarily high because + >>> # of the division by epsilon + >>> y_true = [1., 0., 2.4, 7.] + >>> y_pred = [1.2, 0.1, 2.4, 8.] + >>> mean_absolute_percentage_error(y_true, y_pred) + 112589990684262.48 + """ + y_type, y_true, y_pred, multioutput = _check_reg_targets( + y_true, y_pred, multioutput + ) + check_consistent_length(y_true, y_pred, sample_weight) + epsilon = np.finfo(np.float64).eps + mape = np.abs(y_pred - y_true) / np.maximum(np.abs(y_true), epsilon) + output_errors = np.average(mape, weights=sample_weight, axis=0) + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to np.average: uniform mean + multioutput = None + + return np.average(output_errors, weights=multioutput) + + +def mean_squared_error( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average", squared=True +): + """Mean squared error regression loss. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + squared : bool, default=True + If True returns MSE value, if False returns RMSE value. + + Returns + ------- + loss : float or ndarray of floats + A non-negative floating point value (the best value is 0.0), or an + array of floating point values, one for each individual target. + + Examples + -------- + >>> from sklearn.metrics import mean_squared_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_squared_error(y_true, y_pred) + 0.375 + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_squared_error(y_true, y_pred, squared=False) + 0.612... + >>> y_true = [[0.5, 1],[-1, 1],[7, -6]] + >>> y_pred = [[0, 2],[-1, 2],[8, -5]] + >>> mean_squared_error(y_true, y_pred) + 0.708... + >>> mean_squared_error(y_true, y_pred, squared=False) + 0.822... + >>> mean_squared_error(y_true, y_pred, multioutput='raw_values') + array([0.41666667, 1. ]) + >>> mean_squared_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.825... + """ + y_type, y_true, y_pred, multioutput = _check_reg_targets( + y_true, y_pred, multioutput + ) + check_consistent_length(y_true, y_pred, sample_weight) + output_errors = np.average((y_true - y_pred) ** 2, axis=0, weights=sample_weight) + + if not squared: + output_errors = np.sqrt(output_errors) + + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to np.average: uniform mean + multioutput = None + + return np.average(output_errors, weights=multioutput) + + +def mean_squared_log_error( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average", squared=True +): + """Mean squared logarithmic error regression loss. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors when the input is of multioutput + format. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + squared : bool, default=True + If True returns MSLE (mean squared log error) value. + If False returns RMSLE (root mean squared log error) value. + + Returns + ------- + loss : float or ndarray of floats + A non-negative floating point value (the best value is 0.0), or an + array of floating point values, one for each individual target. + + Examples + -------- + >>> from sklearn.metrics import mean_squared_log_error + >>> y_true = [3, 5, 2.5, 7] + >>> y_pred = [2.5, 5, 4, 8] + >>> mean_squared_log_error(y_true, y_pred) + 0.039... + >>> mean_squared_log_error(y_true, y_pred, squared=False) + 0.199... + >>> y_true = [[0.5, 1], [1, 2], [7, 6]] + >>> y_pred = [[0.5, 2], [1, 2.5], [8, 8]] + >>> mean_squared_log_error(y_true, y_pred) + 0.044... + >>> mean_squared_log_error(y_true, y_pred, multioutput='raw_values') + array([0.00462428, 0.08377444]) + >>> mean_squared_log_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.060... + """ + y_type, y_true, y_pred, multioutput = _check_reg_targets( + y_true, y_pred, multioutput + ) + check_consistent_length(y_true, y_pred, sample_weight) + + if (y_true < 0).any() or (y_pred < 0).any(): + raise ValueError( + "Mean Squared Logarithmic Error cannot be used when " + "targets contain negative values." + ) + + return mean_squared_error( + np.log1p(y_true), + np.log1p(y_pred), + sample_weight=sample_weight, + multioutput=multioutput, + squared=squared, + ) + + +def median_absolute_error( + y_true, y_pred, *, multioutput="uniform_average", sample_weight=None +): + """Median absolute error regression loss. + + Median absolute error output is non-negative floating point. The best value + is 0.0. Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape = (n_samples) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape = (n_samples) or (n_samples, n_outputs) + Estimated target values. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. Array-like value defines + weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 0.24 + + Returns + ------- + loss : float or ndarray of floats + If multioutput is 'raw_values', then mean absolute error is returned + for each output separately. + If multioutput is 'uniform_average' or an ndarray of weights, then the + weighted average of all output errors is returned. + + Examples + -------- + >>> from sklearn.metrics import median_absolute_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> median_absolute_error(y_true, y_pred) + 0.5 + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> median_absolute_error(y_true, y_pred) + 0.75 + >>> median_absolute_error(y_true, y_pred, multioutput='raw_values') + array([0.5, 1. ]) + >>> median_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.85 + """ + y_type, y_true, y_pred, multioutput = _check_reg_targets( + y_true, y_pred, multioutput + ) + if sample_weight is None: + output_errors = np.median(np.abs(y_pred - y_true), axis=0) + else: + sample_weight = _check_sample_weight(sample_weight, y_pred) + output_errors = _weighted_percentile( + np.abs(y_pred - y_true), sample_weight=sample_weight + ) + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to np.average: uniform mean + multioutput = None + + return np.average(output_errors, weights=multioutput) + + +def _assemble_r2_explained_variance( + numerator, denominator, n_outputs, multioutput, force_finite +): + """Common part used by explained variance score and :math:`R^2` score.""" + + nonzero_denominator = denominator != 0 + + if not force_finite: + # Standard formula, that may lead to NaN or -Inf + output_scores = 1 - (numerator / denominator) + else: + nonzero_numerator = numerator != 0 + # Default = Zero Numerator = perfect predictions. Set to 1.0 + # (note: even if denominator is zero, thus avoiding NaN scores) + output_scores = np.ones([n_outputs]) + # Non-zero Numerator and Non-zero Denominator: use the formula + valid_score = nonzero_denominator & nonzero_numerator + output_scores[valid_score] = 1 - ( + numerator[valid_score] / denominator[valid_score] + ) + # Non-zero Numerator and Zero Denominator: + # arbitrary set to 0.0 to avoid -inf scores + output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 + + if isinstance(multioutput, str): + if multioutput == "raw_values": + # return scores individually + return output_scores + elif multioutput == "uniform_average": + # Passing None as weights to np.average results is uniform mean + avg_weights = None + elif multioutput == "variance_weighted": + avg_weights = denominator + if not np.any(nonzero_denominator): + # All weights are zero, np.average would raise a ZeroDiv error. + # This only happens when all y are constant (or 1-element long) + # Since weights are all equal, fall back to uniform weights. + avg_weights = None + else: + avg_weights = multioutput + + return np.average(output_scores, weights=avg_weights) + + +def explained_variance_score( + y_true, + y_pred, + *, + sample_weight=None, + multioutput="uniform_average", + force_finite=True, +): + """Explained variance regression score function. + + Best possible score is 1.0, lower values are worse. + + In the particular case when ``y_true`` is constant, the explained variance + score is not finite: it is either ``NaN`` (perfect predictions) or + ``-Inf`` (imperfect predictions). To prevent such non-finite numbers to + pollute higher-level experiments such as a grid search cross-validation, + by default these cases are replaced with 1.0 (perfect predictions) or 0.0 + (imperfect predictions) respectively. If ``force_finite`` + is set to ``False``, this score falls back on the original :math:`R^2` + definition. + + .. note:: + The Explained Variance score is similar to the + :func:`R^2 score `, with the notable difference that it + does not account for systematic offsets in the prediction. Most often + the :func:`R^2 score ` should be preferred. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average', 'variance_weighted'} or \ + array-like of shape (n_outputs,), default='uniform_average' + Defines aggregating of multiple output scores. + Array-like value defines weights used to average scores. + + 'raw_values' : + Returns a full set of scores in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + 'variance_weighted' : + Scores of all outputs are averaged, weighted by the variances + of each individual output. + + force_finite : bool, default=True + Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant + data should be replaced with real numbers (``1.0`` if prediction is + perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting + for hyperparameters' search procedures (e.g. grid search + cross-validation). + + .. versionadded:: 1.1 + + Returns + ------- + score : float or ndarray of floats + The explained variance or ndarray if 'multioutput' is 'raw_values'. + + See Also + -------- + r2_score : + Similar metric, but accounting for systematic offsets in + prediction. + + Notes + ----- + This is not a symmetric function. + + Examples + -------- + >>> from sklearn.metrics import explained_variance_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> explained_variance_score(y_true, y_pred) + 0.957... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> explained_variance_score(y_true, y_pred, multioutput='uniform_average') + 0.983... + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2] + >>> explained_variance_score(y_true, y_pred) + 1.0 + >>> explained_variance_score(y_true, y_pred, force_finite=False) + nan + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2 + 1e-8] + >>> explained_variance_score(y_true, y_pred) + 0.0 + >>> explained_variance_score(y_true, y_pred, force_finite=False) + -inf + """ + y_type, y_true, y_pred, multioutput = _check_reg_targets( + y_true, y_pred, multioutput + ) + check_consistent_length(y_true, y_pred, sample_weight) + + y_diff_avg = np.average(y_true - y_pred, weights=sample_weight, axis=0) + numerator = np.average( + (y_true - y_pred - y_diff_avg) ** 2, weights=sample_weight, axis=0 + ) + + y_true_avg = np.average(y_true, weights=sample_weight, axis=0) + denominator = np.average((y_true - y_true_avg) ** 2, weights=sample_weight, axis=0) + + return _assemble_r2_explained_variance( + numerator=numerator, + denominator=denominator, + n_outputs=y_true.shape[1], + multioutput=multioutput, + force_finite=force_finite, + ) + + +def r2_score( + y_true, + y_pred, + *, + sample_weight=None, + multioutput="uniform_average", + force_finite=True, +): + """:math:`R^2` (coefficient of determination) regression score function. + + Best possible score is 1.0 and it can be negative (because the + model can be arbitrarily worse). In the general case when the true y is + non-constant, a constant model that always predicts the average y + disregarding the input features would get a :math:`R^2` score of 0.0. + + In the particular case when ``y_true`` is constant, the :math:`R^2` score + is not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` + (imperfect predictions). To prevent such non-finite numbers to pollute + higher-level experiments such as a grid search cross-validation, by default + these cases are replaced with 1.0 (perfect predictions) or 0.0 (imperfect + predictions) respectively. You can set ``force_finite`` to ``False`` to + prevent this fix from happening. + + Note: when the prediction residuals have zero mean, the :math:`R^2` score + is identical to the + :func:`Explained Variance score `. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average', 'variance_weighted'}, \ + array-like of shape (n_outputs,) or None, default='uniform_average' + + Defines aggregating of multiple output scores. + Array-like value defines weights used to average scores. + Default is "uniform_average". + + 'raw_values' : + Returns a full set of scores in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + 'variance_weighted' : + Scores of all outputs are averaged, weighted by the variances + of each individual output. + + .. versionchanged:: 0.19 + Default value of multioutput is 'uniform_average'. + + force_finite : bool, default=True + Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant + data should be replaced with real numbers (``1.0`` if prediction is + perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting + for hyperparameters' search procedures (e.g. grid search + cross-validation). + + .. versionadded:: 1.1 + + Returns + ------- + z : float or ndarray of floats + The :math:`R^2` score or ndarray of scores if 'multioutput' is + 'raw_values'. + + Notes + ----- + This is not a symmetric function. + + Unlike most other scores, :math:`R^2` score may be negative (it need not + actually be the square of a quantity R). + + This metric is not well-defined for single samples and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] `Wikipedia entry on the Coefficient of determination + `_ + + Examples + -------- + >>> from sklearn.metrics import r2_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> r2_score(y_true, y_pred) + 0.948... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> r2_score(y_true, y_pred, + ... multioutput='variance_weighted') + 0.938... + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 2, 3] + >>> r2_score(y_true, y_pred) + 1.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [2, 2, 2] + >>> r2_score(y_true, y_pred) + 0.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [3, 2, 1] + >>> r2_score(y_true, y_pred) + -3.0 + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2] + >>> r2_score(y_true, y_pred) + 1.0 + >>> r2_score(y_true, y_pred, force_finite=False) + nan + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2 + 1e-8] + >>> r2_score(y_true, y_pred) + 0.0 + >>> r2_score(y_true, y_pred, force_finite=False) + -inf + """ + y_type, y_true, y_pred, multioutput = _check_reg_targets( + y_true, y_pred, multioutput + ) + check_consistent_length(y_true, y_pred, sample_weight) + + if _num_samples(y_pred) < 2: + msg = "R^2 score is not well-defined with less than two samples." + warnings.warn(msg, UndefinedMetricWarning) + return float("nan") + + if sample_weight is not None: + sample_weight = column_or_1d(sample_weight) + weight = sample_weight[:, np.newaxis] + else: + weight = 1.0 + + numerator = (weight * (y_true - y_pred) ** 2).sum(axis=0, dtype=np.float64) + denominator = ( + weight * (y_true - np.average(y_true, axis=0, weights=sample_weight)) ** 2 + ).sum(axis=0, dtype=np.float64) + + return _assemble_r2_explained_variance( + numerator=numerator, + denominator=denominator, + n_outputs=y_true.shape[1], + multioutput=multioutput, + force_finite=force_finite, + ) + + +def max_error(y_true, y_pred): + """ + The max_error metric calculates the maximum residual error. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated target values. + + Returns + ------- + max_error : float + A positive floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import max_error + >>> y_true = [3, 2, 7, 1] + >>> y_pred = [4, 2, 7, 1] + >>> max_error(y_true, y_pred) + 1 + """ + y_type, y_true, y_pred, _ = _check_reg_targets(y_true, y_pred, None) + if y_type == "continuous-multioutput": + raise ValueError("Multioutput not supported in max_error") + return np.max(np.abs(y_true - y_pred)) + + +def _mean_tweedie_deviance(y_true, y_pred, sample_weight, power): + """Mean Tweedie deviance regression loss.""" + p = power + if p < 0: + # 'Extreme stable', y any real number, y_pred > 0 + dev = 2 * ( + np.power(np.maximum(y_true, 0), 2 - p) / ((1 - p) * (2 - p)) + - y_true * np.power(y_pred, 1 - p) / (1 - p) + + np.power(y_pred, 2 - p) / (2 - p) + ) + elif p == 0: + # Normal distribution, y and y_pred any real number + dev = (y_true - y_pred) ** 2 + elif p == 1: + # Poisson distribution + dev = 2 * (xlogy(y_true, y_true / y_pred) - y_true + y_pred) + elif p == 2: + # Gamma distribution + dev = 2 * (np.log(y_pred / y_true) + y_true / y_pred - 1) + else: + dev = 2 * ( + np.power(y_true, 2 - p) / ((1 - p) * (2 - p)) + - y_true * np.power(y_pred, 1 - p) / (1 - p) + + np.power(y_pred, 2 - p) / (2 - p) + ) + + return np.average(dev, weights=sample_weight) + + +def mean_tweedie_deviance(y_true, y_pred, *, sample_weight=None, power=0): + """Mean Tweedie deviance regression loss. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + power : float, default=0 + Tweedie power parameter. Either power <= 0 or power >= 1. + + The higher `p` the less weight is given to extreme + deviations between true and predicted targets. + + - power < 0: Extreme stable distribution. Requires: y_pred > 0. + - power = 0 : Normal distribution, output corresponds to + mean_squared_error. y_true and y_pred can be any real numbers. + - power = 1 : Poisson distribution. Requires: y_true >= 0 and + y_pred > 0. + - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0 + and y_pred > 0. + - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0. + - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0 + and y_pred > 0. + - otherwise : Positive stable distribution. Requires: y_true > 0 + and y_pred > 0. + + Returns + ------- + loss : float + A non-negative floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import mean_tweedie_deviance + >>> y_true = [2, 0, 1, 4] + >>> y_pred = [0.5, 0.5, 2., 2.] + >>> mean_tweedie_deviance(y_true, y_pred, power=1) + 1.4260... + """ + y_type, y_true, y_pred, _ = _check_reg_targets( + y_true, y_pred, None, dtype=[np.float64, np.float32] + ) + if y_type == "continuous-multioutput": + raise ValueError("Multioutput not supported in mean_tweedie_deviance") + check_consistent_length(y_true, y_pred, sample_weight) + + if sample_weight is not None: + sample_weight = column_or_1d(sample_weight) + sample_weight = sample_weight[:, np.newaxis] + + p = check_scalar( + power, + name="power", + target_type=numbers.Real, + ) + + message = f"Mean Tweedie deviance error with power={p} can only be used on " + if p < 0: + # 'Extreme stable', y any real number, y_pred > 0 + if (y_pred <= 0).any(): + raise ValueError(message + "strictly positive y_pred.") + elif p == 0: + # Normal, y and y_pred can be any real number + pass + elif 0 < p < 1: + raise ValueError("Tweedie deviance is only defined for power<=0 and power>=1.") + elif 1 <= p < 2: + # Poisson and compound Poisson distribution, y >= 0, y_pred > 0 + if (y_true < 0).any() or (y_pred <= 0).any(): + raise ValueError(message + "non-negative y and strictly positive y_pred.") + elif p >= 2: + # Gamma and Extreme stable distribution, y and y_pred > 0 + if (y_true <= 0).any() or (y_pred <= 0).any(): + raise ValueError(message + "strictly positive y and y_pred.") + else: # pragma: nocover + # Unreachable statement + raise ValueError + + return _mean_tweedie_deviance( + y_true, y_pred, sample_weight=sample_weight, power=power + ) + + +def mean_poisson_deviance(y_true, y_pred, *, sample_weight=None): + """Mean Poisson deviance regression loss. + + Poisson deviance is equivalent to the Tweedie deviance with + the power parameter `power=1`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. Requires y_true >= 0. + + y_pred : array-like of shape (n_samples,) + Estimated target values. Requires y_pred > 0. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + loss : float + A non-negative floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import mean_poisson_deviance + >>> y_true = [2, 0, 1, 4] + >>> y_pred = [0.5, 0.5, 2., 2.] + >>> mean_poisson_deviance(y_true, y_pred) + 1.4260... + """ + return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=1) + + +def mean_gamma_deviance(y_true, y_pred, *, sample_weight=None): + """Mean Gamma deviance regression loss. + + Gamma deviance is equivalent to the Tweedie deviance with + the power parameter `power=2`. It is invariant to scaling of + the target variable, and measures relative errors. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. Requires y_true > 0. + + y_pred : array-like of shape (n_samples,) + Estimated target values. Requires y_pred > 0. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + loss : float + A non-negative floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import mean_gamma_deviance + >>> y_true = [2, 0.5, 1, 4] + >>> y_pred = [0.5, 0.5, 2., 2.] + >>> mean_gamma_deviance(y_true, y_pred) + 1.0568... + """ + return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=2) + + +def d2_tweedie_score(y_true, y_pred, *, sample_weight=None, power=0): + """D^2 regression score function, fraction of Tweedie deviance explained. + + Best possible score is 1.0 and it can be negative (because the model can be + arbitrarily worse). A model that always uses the empirical mean of `y_true` as + constant prediction, disregarding the input features, gets a D^2 score of 0.0. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), optional + Sample weights. + + power : float, default=0 + Tweedie power parameter. Either power <= 0 or power >= 1. + + The higher `p` the less weight is given to extreme + deviations between true and predicted targets. + + - power < 0: Extreme stable distribution. Requires: y_pred > 0. + - power = 0 : Normal distribution, output corresponds to r2_score. + y_true and y_pred can be any real numbers. + - power = 1 : Poisson distribution. Requires: y_true >= 0 and + y_pred > 0. + - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0 + and y_pred > 0. + - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0. + - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0 + and y_pred > 0. + - otherwise : Positive stable distribution. Requires: y_true > 0 + and y_pred > 0. + + Returns + ------- + z : float or ndarray of floats + The D^2 score. + + Notes + ----- + This is not a symmetric function. + + Like R^2, D^2 score may be negative (it need not actually be the square of + a quantity D). + + This metric is not well-defined for single samples and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. + Wainwright. "Statistical Learning with Sparsity: The Lasso and + Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ + + Examples + -------- + >>> from sklearn.metrics import d2_tweedie_score + >>> y_true = [0.5, 1, 2.5, 7] + >>> y_pred = [1, 1, 5, 3.5] + >>> d2_tweedie_score(y_true, y_pred) + 0.285... + >>> d2_tweedie_score(y_true, y_pred, power=1) + 0.487... + >>> d2_tweedie_score(y_true, y_pred, power=2) + 0.630... + >>> d2_tweedie_score(y_true, y_true, power=2) + 1.0 + """ + y_type, y_true, y_pred, _ = _check_reg_targets( + y_true, y_pred, None, dtype=[np.float64, np.float32] + ) + if y_type == "continuous-multioutput": + raise ValueError("Multioutput not supported in d2_tweedie_score") + + if _num_samples(y_pred) < 2: + msg = "D^2 score is not well-defined with less than two samples." + warnings.warn(msg, UndefinedMetricWarning) + return float("nan") + + y_true, y_pred = np.squeeze(y_true), np.squeeze(y_pred) + numerator = mean_tweedie_deviance( + y_true, y_pred, sample_weight=sample_weight, power=power + ) + + y_avg = np.average(y_true, weights=sample_weight) + denominator = _mean_tweedie_deviance( + y_true, y_avg, sample_weight=sample_weight, power=power + ) + + return 1 - numerator / denominator + + +def d2_pinball_score( + y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput="uniform_average" +): + """ + :math:`D^2` regression score function, fraction of pinball loss explained. + + Best possible score is 1.0 and it can be negative (because the model can be + arbitrarily worse). A model that always uses the empirical alpha-quantile of + `y_true` as constant prediction, disregarding the input features, + gets a :math:`D^2` score of 0.0. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.1 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), optional + Sample weights. + + alpha : float, default=0.5 + Slope of the pinball deviance. It determines the quantile level alpha + for which the pinball deviance and also D2 are optimal. + The default `alpha=0.5` is equivalent to `d2_absolute_error_score`. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average scores. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + Returns + ------- + score : float or ndarray of floats + The :math:`D^2` score with a pinball deviance + or ndarray of scores if `multioutput='raw_values'`. + + Notes + ----- + Like :math:`R^2`, :math:`D^2` score may be negative + (it need not actually be the square of a quantity D). + + This metric is not well-defined for a single point and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] Eq. (7) of `Koenker, Roger; Machado, José A. F. (1999). + "Goodness of Fit and Related Inference Processes for Quantile Regression" + `_ + .. [2] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. + Wainwright. "Statistical Learning with Sparsity: The Lasso and + Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ + + Examples + -------- + >>> from sklearn.metrics import d2_pinball_score + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 3, 3] + >>> d2_pinball_score(y_true, y_pred) + 0.5 + >>> d2_pinball_score(y_true, y_pred, alpha=0.9) + 0.772... + >>> d2_pinball_score(y_true, y_pred, alpha=0.1) + -1.045... + >>> d2_pinball_score(y_true, y_true, alpha=0.1) + 1.0 + """ + y_type, y_true, y_pred, multioutput = _check_reg_targets( + y_true, y_pred, multioutput + ) + check_consistent_length(y_true, y_pred, sample_weight) + + if _num_samples(y_pred) < 2: + msg = "D^2 score is not well-defined with less than two samples." + warnings.warn(msg, UndefinedMetricWarning) + return float("nan") + + numerator = mean_pinball_loss( + y_true, + y_pred, + sample_weight=sample_weight, + alpha=alpha, + multioutput="raw_values", + ) + + if sample_weight is None: + y_quantile = np.tile( + np.percentile(y_true, q=alpha * 100, axis=0), (len(y_true), 1) + ) + else: + sample_weight = _check_sample_weight(sample_weight, y_true) + y_quantile = np.tile( + _weighted_percentile( + y_true, sample_weight=sample_weight, percentile=alpha * 100 + ), + (len(y_true), 1), + ) + + denominator = mean_pinball_loss( + y_true, + y_quantile, + sample_weight=sample_weight, + alpha=alpha, + multioutput="raw_values", + ) + + nonzero_numerator = numerator != 0 + nonzero_denominator = denominator != 0 + valid_score = nonzero_numerator & nonzero_denominator + output_scores = np.ones(y_true.shape[1]) + + output_scores[valid_score] = 1 - (numerator[valid_score] / denominator[valid_score]) + output_scores[nonzero_numerator & ~nonzero_denominator] = 0.0 + + if isinstance(multioutput, str): + if multioutput == "raw_values": + # return scores individually + return output_scores + elif multioutput == "uniform_average": + # passing None as weights to np.average results in uniform mean + avg_weights = None + else: + raise ValueError( + "multioutput is expected to be 'raw_values' " + "or 'uniform_average' but we got %r" + " instead." % multioutput + ) + else: + avg_weights = multioutput + + return np.average(output_scores, weights=avg_weights) + + +def d2_absolute_error_score( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """ + :math:`D^2` regression score function, \ + fraction of absolute error explained. + + Best possible score is 1.0 and it can be negative (because the model can be + arbitrarily worse). A model that always uses the empirical median of `y_true` + as constant prediction, disregarding the input features, + gets a :math:`D^2` score of 0.0. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.1 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), optional + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average scores. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + Returns + ------- + score : float or ndarray of floats + The :math:`D^2` score with an absolute error deviance + or ndarray of scores if 'multioutput' is 'raw_values'. + + Notes + ----- + Like :math:`R^2`, :math:`D^2` score may be negative + (it need not actually be the square of a quantity D). + + This metric is not well-defined for single samples and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. + Wainwright. "Statistical Learning with Sparsity: The Lasso and + Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ + + Examples + -------- + >>> from sklearn.metrics import d2_absolute_error_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> d2_absolute_error_score(y_true, y_pred) + 0.764... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> d2_absolute_error_score(y_true, y_pred, multioutput='uniform_average') + 0.691... + >>> d2_absolute_error_score(y_true, y_pred, multioutput='raw_values') + array([0.8125 , 0.57142857]) + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 2, 3] + >>> d2_absolute_error_score(y_true, y_pred) + 1.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [2, 2, 2] + >>> d2_absolute_error_score(y_true, y_pred) + 0.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [3, 2, 1] + >>> d2_absolute_error_score(y_true, y_pred) + -1.0 + """ + return d2_pinball_score( + y_true, y_pred, sample_weight=sample_weight, alpha=0.5, multioutput=multioutput + ) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_scorer.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_scorer.py new file mode 100644 index 0000000000000000000000000000000000000000..a414818f497d2e996a7557a8779e7492a33935f8 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_scorer.py @@ -0,0 +1,867 @@ +""" +The :mod:`sklearn.metrics.scorer` submodule implements a flexible +interface for model selection and evaluation using +arbitrary score functions. + +A scorer object is a callable that can be passed to +:class:`~sklearn.model_selection.GridSearchCV` or +:func:`sklearn.model_selection.cross_val_score` as the ``scoring`` +parameter, to specify how a model should be evaluated. + +The signature of the call is ``(estimator, X, y)`` where ``estimator`` +is the model to be evaluated, ``X`` is the test data and ``y`` is the +ground truth labeling (or ``None`` in the case of unsupervised models). +""" + +# Authors: Andreas Mueller +# Lars Buitinck +# Arnaud Joly +# License: Simplified BSD + +from collections.abc import Iterable +from functools import partial +from collections import Counter +from traceback import format_exc + +import numpy as np +import copy +import warnings + +from . import ( + r2_score, + median_absolute_error, + max_error, + mean_absolute_error, + mean_squared_error, + mean_squared_log_error, + mean_poisson_deviance, + mean_gamma_deviance, + accuracy_score, + top_k_accuracy_score, + f1_score, + roc_auc_score, + average_precision_score, + precision_score, + recall_score, + log_loss, + balanced_accuracy_score, + explained_variance_score, + brier_score_loss, + jaccard_score, + mean_absolute_percentage_error, + matthews_corrcoef, + class_likelihood_ratios, +) + +from .cluster import adjusted_rand_score +from .cluster import rand_score +from .cluster import homogeneity_score +from .cluster import completeness_score +from .cluster import v_measure_score +from .cluster import mutual_info_score +from .cluster import adjusted_mutual_info_score +from .cluster import normalized_mutual_info_score +from .cluster import fowlkes_mallows_score + +from ..utils.multiclass import type_of_target +from ..base import is_regressor + + +def _cached_call(cache, estimator, method, *args, **kwargs): + """Call estimator with method and args and kwargs.""" + if cache is None: + return getattr(estimator, method)(*args, **kwargs) + + try: + return cache[method] + except KeyError: + result = getattr(estimator, method)(*args, **kwargs) + cache[method] = result + return result + + +class _MultimetricScorer: + """Callable for multimetric scoring used to avoid repeated calls + to `predict_proba`, `predict`, and `decision_function`. + + `_MultimetricScorer` will return a dictionary of scores corresponding to + the scorers in the dictionary. Note that `_MultimetricScorer` can be + created with a dictionary with one key (i.e. only one actual scorer). + + Parameters + ---------- + scorers : dict + Dictionary mapping names to callable scorers. + + raise_exc : bool, default=True + Whether to raise the exception in `__call__` or not. If set to `False` + a formatted string of the exception details is passed as result of + the failing scorer. + """ + + def __init__(self, *, scorers, raise_exc=True): + self._scorers = scorers + self._raise_exc = raise_exc + + def __call__(self, estimator, *args, **kwargs): + """Evaluate predicted target values.""" + scores = {} + cache = {} if self._use_cache(estimator) else None + cached_call = partial(_cached_call, cache) + + for name, scorer in self._scorers.items(): + try: + if isinstance(scorer, _BaseScorer): + score = scorer._score(cached_call, estimator, *args, **kwargs) + else: + score = scorer(estimator, *args, **kwargs) + scores[name] = score + except Exception as e: + if self._raise_exc: + raise e + else: + scores[name] = format_exc() + + return scores + + def _use_cache(self, estimator): + """Return True if using a cache is beneficial. + + Caching may be beneficial when one of these conditions holds: + - `_ProbaScorer` will be called twice. + - `_PredictScorer` will be called twice. + - `_ThresholdScorer` will be called twice. + - `_ThresholdScorer` and `_PredictScorer` are called and + estimator is a regressor. + - `_ThresholdScorer` and `_ProbaScorer` are called and + estimator does not have a `decision_function` attribute. + + """ + if len(self._scorers) == 1: # Only one scorer + return False + + counter = Counter([type(v) for v in self._scorers.values()]) + + if any( + counter[known_type] > 1 + for known_type in [_PredictScorer, _ProbaScorer, _ThresholdScorer] + ): + return True + + if counter[_ThresholdScorer]: + if is_regressor(estimator) and counter[_PredictScorer]: + return True + elif counter[_ProbaScorer] and not hasattr(estimator, "decision_function"): + return True + return False + + +class _BaseScorer: + def __init__(self, score_func, sign, kwargs): + self._kwargs = kwargs + self._score_func = score_func + self._sign = sign + + @staticmethod + def _check_pos_label(pos_label, classes): + if pos_label not in list(classes): + raise ValueError(f"pos_label={pos_label} is not a valid label: {classes}") + + def _select_proba_binary(self, y_pred, classes): + """Select the column of the positive label in `y_pred` when + probabilities are provided. + + Parameters + ---------- + y_pred : ndarray of shape (n_samples, n_classes) + The prediction given by `predict_proba`. + + classes : ndarray of shape (n_classes,) + The class labels for the estimator. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Probability predictions of the positive class. + """ + if y_pred.shape[1] == 2: + pos_label = self._kwargs.get("pos_label", classes[1]) + self._check_pos_label(pos_label, classes) + col_idx = np.flatnonzero(classes == pos_label)[0] + return y_pred[:, col_idx] + + err_msg = ( + f"Got predict_proba of shape {y_pred.shape}, but need " + f"classifier with two classes for {self._score_func.__name__} " + "scoring" + ) + raise ValueError(err_msg) + + def __repr__(self): + kwargs_string = "".join( + [", %s=%s" % (str(k), str(v)) for k, v in self._kwargs.items()] + ) + return "make_scorer(%s%s%s%s)" % ( + self._score_func.__name__, + "" if self._sign > 0 else ", greater_is_better=False", + self._factory_args(), + kwargs_string, + ) + + def __call__(self, estimator, X, y_true, sample_weight=None): + """Evaluate predicted target values for X relative to y_true. + + Parameters + ---------- + estimator : object + Trained estimator to use for scoring. Must have a predict_proba + method; the output of that is used to compute the score. + + X : {array-like, sparse matrix} + Test data that will be fed to estimator.predict. + + y_true : array-like + Gold standard target values for X. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + score : float + Score function applied to prediction of estimator on X. + """ + return self._score( + partial(_cached_call, None), + estimator, + X, + y_true, + sample_weight=sample_weight, + ) + + def _factory_args(self): + """Return non-default make_scorer arguments for repr.""" + return "" + + +class _PredictScorer(_BaseScorer): + def _score(self, method_caller, estimator, X, y_true, sample_weight=None): + """Evaluate predicted target values for X relative to y_true. + + Parameters + ---------- + method_caller : callable + Returns predictions given an estimator, method name, and other + arguments, potentially caching results. + + estimator : object + Trained estimator to use for scoring. Must have a `predict` + method; the output of that is used to compute the score. + + X : {array-like, sparse matrix} + Test data that will be fed to estimator.predict. + + y_true : array-like + Gold standard target values for X. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + score : float + Score function applied to prediction of estimator on X. + """ + + y_pred = method_caller(estimator, "predict", X) + if sample_weight is not None: + return self._sign * self._score_func( + y_true, y_pred, sample_weight=sample_weight, **self._kwargs + ) + else: + return self._sign * self._score_func(y_true, y_pred, **self._kwargs) + + +class _ProbaScorer(_BaseScorer): + def _score(self, method_caller, clf, X, y, sample_weight=None): + """Evaluate predicted probabilities for X relative to y_true. + + Parameters + ---------- + method_caller : callable + Returns predictions given an estimator, method name, and other + arguments, potentially caching results. + + clf : object + Trained classifier to use for scoring. Must have a `predict_proba` + method; the output of that is used to compute the score. + + X : {array-like, sparse matrix} + Test data that will be fed to clf.predict_proba. + + y : array-like + Gold standard target values for X. These must be class labels, + not probabilities. + + sample_weight : array-like, default=None + Sample weights. + + Returns + ------- + score : float + Score function applied to prediction of estimator on X. + """ + + y_type = type_of_target(y) + y_pred = method_caller(clf, "predict_proba", X) + if y_type == "binary" and y_pred.shape[1] <= 2: + # `y_type` could be equal to "binary" even in a multi-class + # problem: (when only 2 class are given to `y_true` during scoring) + # Thus, we need to check for the shape of `y_pred`. + y_pred = self._select_proba_binary(y_pred, clf.classes_) + if sample_weight is not None: + return self._sign * self._score_func( + y, y_pred, sample_weight=sample_weight, **self._kwargs + ) + else: + return self._sign * self._score_func(y, y_pred, **self._kwargs) + + def _factory_args(self): + return ", needs_proba=True" + + +class _ThresholdScorer(_BaseScorer): + def _score(self, method_caller, clf, X, y, sample_weight=None): + """Evaluate decision function output for X relative to y_true. + + Parameters + ---------- + method_caller : callable + Returns predictions given an estimator, method name, and other + arguments, potentially caching results. + + clf : object + Trained classifier to use for scoring. Must have either a + decision_function method or a predict_proba method; the output of + that is used to compute the score. + + X : {array-like, sparse matrix} + Test data that will be fed to clf.decision_function or + clf.predict_proba. + + y : array-like + Gold standard target values for X. These must be class labels, + not decision function values. + + sample_weight : array-like, default=None + Sample weights. + + Returns + ------- + score : float + Score function applied to prediction of estimator on X. + """ + + y_type = type_of_target(y) + if y_type not in ("binary", "multilabel-indicator"): + raise ValueError("{0} format is not supported".format(y_type)) + + if is_regressor(clf): + y_pred = method_caller(clf, "predict", X) + else: + try: + y_pred = method_caller(clf, "decision_function", X) + + if isinstance(y_pred, list): + # For multi-output multi-class estimator + y_pred = np.vstack([p for p in y_pred]).T + elif y_type == "binary" and "pos_label" in self._kwargs: + self._check_pos_label(self._kwargs["pos_label"], clf.classes_) + if self._kwargs["pos_label"] == clf.classes_[0]: + # The implicit positive class of the binary classifier + # does not match `pos_label`: we need to invert the + # predictions + y_pred *= -1 + + except (NotImplementedError, AttributeError): + y_pred = method_caller(clf, "predict_proba", X) + + if y_type == "binary": + y_pred = self._select_proba_binary(y_pred, clf.classes_) + elif isinstance(y_pred, list): + y_pred = np.vstack([p[:, -1] for p in y_pred]).T + + if sample_weight is not None: + return self._sign * self._score_func( + y, y_pred, sample_weight=sample_weight, **self._kwargs + ) + else: + return self._sign * self._score_func(y, y_pred, **self._kwargs) + + def _factory_args(self): + return ", needs_threshold=True" + + +def get_scorer(scoring): + """Get a scorer from string. + + Read more in the :ref:`User Guide `. + :func:`~sklearn.metrics.get_scorer_names` can be used to retrieve the names + of all available scorers. + + Parameters + ---------- + scoring : str or callable + Scoring method as string. If callable it is returned as is. + + Returns + ------- + scorer : callable + The scorer. + + Notes + ----- + When passed a string, this function always returns a copy of the scorer + object. Calling `get_scorer` twice for the same scorer results in two + separate scorer objects. + """ + if isinstance(scoring, str): + try: + scorer = copy.deepcopy(_SCORERS[scoring]) + except KeyError: + raise ValueError( + "%r is not a valid scoring value. " + "Use sklearn.metrics.get_scorer_names() " + "to get valid options." % scoring + ) + else: + scorer = scoring + return scorer + + +def _passthrough_scorer(estimator, *args, **kwargs): + """Function that wraps estimator.score""" + return estimator.score(*args, **kwargs) + + +def check_scoring(estimator, scoring=None, *, allow_none=False): + """Determine scorer from user options. + + A TypeError will be thrown if the estimator cannot be scored. + + Parameters + ---------- + estimator : estimator object implementing 'fit' + The object to use to fit the data. + + scoring : str or callable, default=None + A string (see model evaluation documentation) or + a scorer callable object / function with signature + ``scorer(estimator, X, y)``. + If None, the provided estimator object's `score` method is used. + + allow_none : bool, default=False + If no scoring is specified and the estimator has no score function, we + can either return None or raise an exception. + + Returns + ------- + scoring : callable + A scorer callable object / function with signature + ``scorer(estimator, X, y)``. + """ + if not hasattr(estimator, "fit"): + raise TypeError( + "estimator should be an estimator implementing 'fit' method, %r was passed" + % estimator + ) + if isinstance(scoring, str): + return get_scorer(scoring) + elif callable(scoring): + # Heuristic to ensure user has not passed a metric + module = getattr(scoring, "__module__", None) + if ( + hasattr(module, "startswith") + and module.startswith("sklearn.metrics.") + and not module.startswith("sklearn.metrics._scorer") + and not module.startswith("sklearn.metrics.tests.") + ): + raise ValueError( + "scoring value %r looks like it is a metric " + "function rather than a scorer. A scorer should " + "require an estimator as its first parameter. " + "Please use `make_scorer` to convert a metric " + "to a scorer." % scoring + ) + return get_scorer(scoring) + elif scoring is None: + if hasattr(estimator, "score"): + return _passthrough_scorer + elif allow_none: + return None + else: + raise TypeError( + "If no scoring is specified, the estimator passed should " + "have a 'score' method. The estimator %r does not." % estimator + ) + elif isinstance(scoring, Iterable): + raise ValueError( + "For evaluating multiple scores, use " + "sklearn.model_selection.cross_validate instead. " + "{0} was passed.".format(scoring) + ) + else: + raise ValueError( + "scoring value should either be a callable, string or None. %r was passed" + % scoring + ) + + +def _check_multimetric_scoring(estimator, scoring): + """Check the scoring parameter in cases when multiple metrics are allowed. + + Parameters + ---------- + estimator : sklearn estimator instance + The estimator for which the scoring will be applied. + + scoring : list, tuple or dict + Strategy to evaluate the performance of the cross-validated model on + the test set. + + The possibilities are: + + - a list or tuple of unique strings; + - a callable returning a dictionary where they keys are the metric + names and the values are the metric scores; + - a dictionary with metric names as keys and callables a values. + + See :ref:`multimetric_grid_search` for an example. + + Returns + ------- + scorers_dict : dict + A dict mapping each scorer name to its validated scorer. + """ + err_msg_generic = ( + f"scoring is invalid (got {scoring!r}). Refer to the " + "scoring glossary for details: " + "https://scikit-learn.org/stable/glossary.html#term-scoring" + ) + + if isinstance(scoring, (list, tuple, set)): + err_msg = ( + "The list/tuple elements must be unique strings of predefined scorers. " + ) + try: + keys = set(scoring) + except TypeError as e: + raise ValueError(err_msg) from e + + if len(keys) != len(scoring): + raise ValueError( + f"{err_msg} Duplicate elements were found in" + f" the given list. {scoring!r}" + ) + elif len(keys) > 0: + if not all(isinstance(k, str) for k in keys): + if any(callable(k) for k in keys): + raise ValueError( + f"{err_msg} One or more of the elements " + "were callables. Use a dict of score " + "name mapped to the scorer callable. " + f"Got {scoring!r}" + ) + else: + raise ValueError( + f"{err_msg} Non-string types were found " + f"in the given list. Got {scoring!r}" + ) + scorers = { + scorer: check_scoring(estimator, scoring=scorer) for scorer in scoring + } + else: + raise ValueError(f"{err_msg} Empty list was given. {scoring!r}") + + elif isinstance(scoring, dict): + keys = set(scoring) + if not all(isinstance(k, str) for k in keys): + raise ValueError( + "Non-string types were found in the keys of " + f"the given dict. scoring={scoring!r}" + ) + if len(keys) == 0: + raise ValueError(f"An empty dict was passed. {scoring!r}") + scorers = { + key: check_scoring(estimator, scoring=scorer) + for key, scorer in scoring.items() + } + else: + raise ValueError(err_msg_generic) + return scorers + + +def make_scorer( + score_func, + *, + greater_is_better=True, + needs_proba=False, + needs_threshold=False, + **kwargs, +): + """Make a scorer from a performance metric or loss function. + + This factory function wraps scoring functions for use in + :class:`~sklearn.model_selection.GridSearchCV` and + :func:`~sklearn.model_selection.cross_val_score`. + It takes a score function, such as :func:`~sklearn.metrics.accuracy_score`, + :func:`~sklearn.metrics.mean_squared_error`, + :func:`~sklearn.metrics.adjusted_rand_score` or + :func:`~sklearn.metrics.average_precision_score` + and returns a callable that scores an estimator's output. + The signature of the call is `(estimator, X, y)` where `estimator` + is the model to be evaluated, `X` is the data and `y` is the + ground truth labeling (or `None` in the case of unsupervised models). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable + Score function (or loss function) with signature + `score_func(y, y_pred, **kwargs)`. + + greater_is_better : bool, default=True + Whether `score_func` is a score function (default), meaning high is + good, or a loss function, meaning low is good. In the latter case, the + scorer object will sign-flip the outcome of the `score_func`. + + needs_proba : bool, default=False + Whether `score_func` requires `predict_proba` to get probability + estimates out of a classifier. + + If True, for binary `y_true`, the score function is supposed to accept + a 1D `y_pred` (i.e., probability of the positive class, shape + `(n_samples,)`). + + needs_threshold : bool, default=False + Whether `score_func` takes a continuous decision certainty. + This only works for binary classification using estimators that + have either a `decision_function` or `predict_proba` method. + + If True, for binary `y_true`, the score function is supposed to accept + a 1D `y_pred` (i.e., probability of the positive class or the decision + function, shape `(n_samples,)`). + + For example `average_precision` or the area under the roc curve + can not be computed using discrete predictions alone. + + **kwargs : additional arguments + Additional parameters to be passed to `score_func`. + + Returns + ------- + scorer : callable + Callable object that returns a scalar score; greater is better. + + Notes + ----- + If `needs_proba=False` and `needs_threshold=False`, the score + function is supposed to accept the output of :term:`predict`. If + `needs_proba=True`, the score function is supposed to accept the + output of :term:`predict_proba` (For binary `y_true`, the score function is + supposed to accept probability of the positive class). If + `needs_threshold=True`, the score function is supposed to accept the + output of :term:`decision_function` or :term:`predict_proba` when + :term:`decision_function` is not present. + + Examples + -------- + >>> from sklearn.metrics import fbeta_score, make_scorer + >>> ftwo_scorer = make_scorer(fbeta_score, beta=2) + >>> ftwo_scorer + make_scorer(fbeta_score, beta=2) + >>> from sklearn.model_selection import GridSearchCV + >>> from sklearn.svm import LinearSVC + >>> grid = GridSearchCV(LinearSVC(), param_grid={'C': [1, 10]}, + ... scoring=ftwo_scorer) + """ + sign = 1 if greater_is_better else -1 + if needs_proba and needs_threshold: + raise ValueError( + "Set either needs_proba or needs_threshold to True, but not both." + ) + if needs_proba: + cls = _ProbaScorer + elif needs_threshold: + cls = _ThresholdScorer + else: + cls = _PredictScorer + return cls(score_func, sign, kwargs) + + +# Standard regression scores +explained_variance_scorer = make_scorer(explained_variance_score) +r2_scorer = make_scorer(r2_score) +max_error_scorer = make_scorer(max_error, greater_is_better=False) +neg_mean_squared_error_scorer = make_scorer(mean_squared_error, greater_is_better=False) +neg_mean_squared_log_error_scorer = make_scorer( + mean_squared_log_error, greater_is_better=False +) +neg_mean_absolute_error_scorer = make_scorer( + mean_absolute_error, greater_is_better=False +) +neg_mean_absolute_percentage_error_scorer = make_scorer( + mean_absolute_percentage_error, greater_is_better=False +) +neg_median_absolute_error_scorer = make_scorer( + median_absolute_error, greater_is_better=False +) +neg_root_mean_squared_error_scorer = make_scorer( + mean_squared_error, greater_is_better=False, squared=False +) +neg_mean_poisson_deviance_scorer = make_scorer( + mean_poisson_deviance, greater_is_better=False +) + +neg_mean_gamma_deviance_scorer = make_scorer( + mean_gamma_deviance, greater_is_better=False +) + +# Standard Classification Scores +accuracy_scorer = make_scorer(accuracy_score) +balanced_accuracy_scorer = make_scorer(balanced_accuracy_score) +matthews_corrcoef_scorer = make_scorer(matthews_corrcoef) + + +def positive_likelihood_ratio(y_true, y_pred): + return class_likelihood_ratios(y_true, y_pred)[0] + + +def negative_likelihood_ratio(y_true, y_pred): + return class_likelihood_ratios(y_true, y_pred)[1] + + +positive_likelihood_ratio_scorer = make_scorer(positive_likelihood_ratio) +neg_negative_likelihood_ratio_scorer = make_scorer( + negative_likelihood_ratio, greater_is_better=False +) + +# Score functions that need decision values +top_k_accuracy_scorer = make_scorer( + top_k_accuracy_score, greater_is_better=True, needs_threshold=True +) +roc_auc_scorer = make_scorer( + roc_auc_score, greater_is_better=True, needs_threshold=True +) +average_precision_scorer = make_scorer(average_precision_score, needs_threshold=True) +roc_auc_ovo_scorer = make_scorer(roc_auc_score, needs_proba=True, multi_class="ovo") +roc_auc_ovo_weighted_scorer = make_scorer( + roc_auc_score, needs_proba=True, multi_class="ovo", average="weighted" +) +roc_auc_ovr_scorer = make_scorer(roc_auc_score, needs_proba=True, multi_class="ovr") +roc_auc_ovr_weighted_scorer = make_scorer( + roc_auc_score, needs_proba=True, multi_class="ovr", average="weighted" +) + +# Score function for probabilistic classification +neg_log_loss_scorer = make_scorer(log_loss, greater_is_better=False, needs_proba=True) +neg_brier_score_scorer = make_scorer( + brier_score_loss, greater_is_better=False, needs_proba=True +) +brier_score_loss_scorer = make_scorer( + brier_score_loss, greater_is_better=False, needs_proba=True +) + + +# Clustering scores +adjusted_rand_scorer = make_scorer(adjusted_rand_score) +rand_scorer = make_scorer(rand_score) +homogeneity_scorer = make_scorer(homogeneity_score) +completeness_scorer = make_scorer(completeness_score) +v_measure_scorer = make_scorer(v_measure_score) +mutual_info_scorer = make_scorer(mutual_info_score) +adjusted_mutual_info_scorer = make_scorer(adjusted_mutual_info_score) +normalized_mutual_info_scorer = make_scorer(normalized_mutual_info_score) +fowlkes_mallows_scorer = make_scorer(fowlkes_mallows_score) + + +# TODO(1.3) Remove +class _DeprecatedScorers(dict): + """A temporary class to deprecate SCORERS.""" + + def __getitem__(self, item): + warnings.warn( + "sklearn.metrics.SCORERS is deprecated and will be removed in v1.3. " + "Please use sklearn.metrics.get_scorer_names to get a list of available " + "scorers and sklearn.metrics.get_metric to get scorer.", + FutureWarning, + ) + return super().__getitem__(item) + + +_SCORERS = dict( + explained_variance=explained_variance_scorer, + r2=r2_scorer, + max_error=max_error_scorer, + matthews_corrcoef=matthews_corrcoef_scorer, + neg_median_absolute_error=neg_median_absolute_error_scorer, + neg_mean_absolute_error=neg_mean_absolute_error_scorer, + neg_mean_absolute_percentage_error=neg_mean_absolute_percentage_error_scorer, # noqa + neg_mean_squared_error=neg_mean_squared_error_scorer, + neg_mean_squared_log_error=neg_mean_squared_log_error_scorer, + neg_root_mean_squared_error=neg_root_mean_squared_error_scorer, + neg_mean_poisson_deviance=neg_mean_poisson_deviance_scorer, + neg_mean_gamma_deviance=neg_mean_gamma_deviance_scorer, + accuracy=accuracy_scorer, + top_k_accuracy=top_k_accuracy_scorer, + roc_auc=roc_auc_scorer, + roc_auc_ovr=roc_auc_ovr_scorer, + roc_auc_ovo=roc_auc_ovo_scorer, + roc_auc_ovr_weighted=roc_auc_ovr_weighted_scorer, + roc_auc_ovo_weighted=roc_auc_ovo_weighted_scorer, + balanced_accuracy=balanced_accuracy_scorer, + average_precision=average_precision_scorer, + neg_log_loss=neg_log_loss_scorer, + neg_brier_score=neg_brier_score_scorer, + positive_likelihood_ratio=positive_likelihood_ratio_scorer, + neg_negative_likelihood_ratio=neg_negative_likelihood_ratio_scorer, + # Cluster metrics that use supervised evaluation + adjusted_rand_score=adjusted_rand_scorer, + rand_score=rand_scorer, + homogeneity_score=homogeneity_scorer, + completeness_score=completeness_scorer, + v_measure_score=v_measure_scorer, + mutual_info_score=mutual_info_scorer, + adjusted_mutual_info_score=adjusted_mutual_info_scorer, + normalized_mutual_info_score=normalized_mutual_info_scorer, + fowlkes_mallows_score=fowlkes_mallows_scorer, +) + + +def get_scorer_names(): + """Get the names of all available scorers. + + These names can be passed to :func:`~sklearn.metrics.get_scorer` to + retrieve the scorer object. + + Returns + ------- + list of str + Names of all available scorers. + """ + return sorted(_SCORERS.keys()) + + +for name, metric in [ + ("precision", precision_score), + ("recall", recall_score), + ("f1", f1_score), + ("jaccard", jaccard_score), +]: + _SCORERS[name] = make_scorer(metric, average="binary") + for average in ["macro", "micro", "samples", "weighted"]: + qualified_name = "{0}_{1}".format(name, average) + _SCORERS[qualified_name] = make_scorer(metric, pos_label=None, average=average) + +SCORERS = _DeprecatedScorers(_SCORERS) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/pairwise.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/pairwise.py new file mode 100644 index 0000000000000000000000000000000000000000..3d01d5eeaf12d790cf60d20eb9b1f037a263c73b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/pairwise.py @@ -0,0 +1,2205 @@ +# Authors: Alexandre Gramfort +# Mathieu Blondel +# Robert Layton +# Andreas Mueller +# Philippe Gervais +# Lars Buitinck +# Joel Nothman +# License: BSD 3 clause + +import itertools +from functools import partial +import warnings + +import numpy as np +from scipy.spatial import distance +from scipy.sparse import csr_matrix +from scipy.sparse import issparse +from joblib import effective_n_jobs + +from .. import config_context +from ..utils.validation import _num_samples +from ..utils.validation import check_non_negative +from ..utils import check_array +from ..utils import gen_even_slices +from ..utils import gen_batches, get_chunk_n_rows +from ..utils import is_scalar_nan +from ..utils.extmath import row_norms, safe_sparse_dot +from ..preprocessing import normalize +from ..utils._mask import _get_mask +from ..utils.parallel import delayed, Parallel +from ..utils.fixes import sp_version, parse_version + +from ._pairwise_distances_reduction import ArgKmin +from ._pairwise_fast import _chi2_kernel_fast, _sparse_manhattan +from ..exceptions import DataConversionWarning + + +# Utility Functions +def _return_float_dtype(X, Y): + """ + 1. If dtype of X and Y is float32, then dtype float32 is returned. + 2. Else dtype float is returned. + """ + if not issparse(X) and not isinstance(X, np.ndarray): + X = np.asarray(X) + + if Y is None: + Y_dtype = X.dtype + elif not issparse(Y) and not isinstance(Y, np.ndarray): + Y = np.asarray(Y) + Y_dtype = Y.dtype + else: + Y_dtype = Y.dtype + + if X.dtype == Y_dtype == np.float32: + dtype = np.float32 + else: + dtype = float + + return X, Y, dtype + + +def check_pairwise_arrays( + X, + Y, + *, + precomputed=False, + dtype=None, + accept_sparse="csr", + force_all_finite=True, + copy=False, +): + """Set X and Y appropriately and checks inputs. + + If Y is None, it is set as a pointer to X (i.e. not a copy). + If Y is given, this does not happen. + All distance metrics should use this function first to assert that the + given parameters are correct and safe to use. + + Specifically, this function first ensures that both X and Y are arrays, + then checks that they are at least two dimensional while ensuring that + their elements are floats (or dtype if provided). Finally, the function + checks that the size of the second dimension of the two arrays is equal, or + the equivalent check for a precomputed distance matrix. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) + + precomputed : bool, default=False + True if X is to be treated as precomputed distances to the samples in + Y. + + dtype : str, type, list of type, default=None + Data type required for X and Y. If None, the dtype will be an + appropriate float type selected by _return_float_dtype. + + .. versionadded:: 0.18 + + accept_sparse : str, bool or list/tuple of str, default='csr' + String[s] representing allowed sparse matrix formats, such as 'csc', + 'csr', etc. If the input is sparse but not in the allowed format, + it will be converted to the first listed format. True allows the input + to be any format. False means that a sparse matrix input will + raise an error. + + force_all_finite : bool or 'allow-nan', default=True + Whether to raise an error on np.inf, np.nan, pd.NA in array. The + possibilities are: + + - True: Force all values of array to be finite. + - False: accepts np.inf, np.nan, pd.NA in array. + - 'allow-nan': accepts only np.nan and pd.NA values in array. Values + cannot be infinite. + + .. versionadded:: 0.22 + ``force_all_finite`` accepts the string ``'allow-nan'``. + + .. versionchanged:: 0.23 + Accepts `pd.NA` and converts it into `np.nan`. + + copy : bool, default=False + Whether a forced copy will be triggered. If copy=False, a copy might + be triggered by a conversion. + + .. versionadded:: 0.22 + + Returns + ------- + safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + An array equal to X, guaranteed to be a numpy array. + + safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) + An array equal to Y if Y was not None, guaranteed to be a numpy array. + If Y was None, safe_Y will be a pointer to X. + """ + X, Y, dtype_float = _return_float_dtype(X, Y) + + estimator = "check_pairwise_arrays" + if dtype is None: + dtype = dtype_float + + if Y is X or Y is None: + X = Y = check_array( + X, + accept_sparse=accept_sparse, + dtype=dtype, + copy=copy, + force_all_finite=force_all_finite, + estimator=estimator, + ) + else: + X = check_array( + X, + accept_sparse=accept_sparse, + dtype=dtype, + copy=copy, + force_all_finite=force_all_finite, + estimator=estimator, + ) + Y = check_array( + Y, + accept_sparse=accept_sparse, + dtype=dtype, + copy=copy, + force_all_finite=force_all_finite, + estimator=estimator, + ) + + if precomputed: + if X.shape[1] != Y.shape[0]: + raise ValueError( + "Precomputed metric requires shape " + "(n_queries, n_indexed). Got (%d, %d) " + "for %d indexed." % (X.shape[0], X.shape[1], Y.shape[0]) + ) + elif X.shape[1] != Y.shape[1]: + raise ValueError( + "Incompatible dimension for X and Y matrices: " + "X.shape[1] == %d while Y.shape[1] == %d" % (X.shape[1], Y.shape[1]) + ) + + return X, Y + + +def check_paired_arrays(X, Y): + """Set X and Y appropriately and checks inputs for paired distances. + + All paired distance metrics should use this function first to assert that + the given parameters are correct and safe to use. + + Specifically, this function first ensures that both X and Y are arrays, + then checks that they are at least two dimensional while ensuring that + their elements are floats. Finally, the function checks that the size + of the dimensions of the two arrays are equal. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) + + Returns + ------- + safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + An array equal to X, guaranteed to be a numpy array. + + safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) + An array equal to Y if Y was not None, guaranteed to be a numpy array. + If Y was None, safe_Y will be a pointer to X. + """ + X, Y = check_pairwise_arrays(X, Y) + if X.shape != Y.shape: + raise ValueError( + "X and Y should be of same shape. They were respectively %r and %r long." + % (X.shape, Y.shape) + ) + return X, Y + + +# Pairwise distances +def euclidean_distances( + X, Y=None, *, Y_norm_squared=None, squared=False, X_norm_squared=None +): + """ + Compute the distance matrix between each pair from a vector array X and Y. + + For efficiency reasons, the euclidean distance between a pair of row + vector x and y is computed as:: + + dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y)) + + This formulation has two advantages over other ways of computing distances. + First, it is computationally efficient when dealing with sparse data. + Second, if one argument varies but the other remains unchanged, then + `dot(x, x)` and/or `dot(y, y)` can be pre-computed. + + However, this is not the most precise way of doing this computation, + because this equation potentially suffers from "catastrophic cancellation". + Also, the distance matrix returned by this function may not be exactly + symmetric as required by, e.g., ``scipy.spatial.distance`` functions. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + An array where each row is a sample and each column is a feature. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), \ + default=None + An array where each row is a sample and each column is a feature. + If `None`, method uses `Y=X`. + + Y_norm_squared : array-like of shape (n_samples_Y,) or (n_samples_Y, 1) \ + or (1, n_samples_Y), default=None + Pre-computed dot-products of vectors in Y (e.g., + ``(Y**2).sum(axis=1)``) + May be ignored in some cases, see the note below. + + squared : bool, default=False + Return squared Euclidean distances. + + X_norm_squared : array-like of shape (n_samples_X,) or (n_samples_X, 1) \ + or (1, n_samples_X), default=None + Pre-computed dot-products of vectors in X (e.g., + ``(X**2).sum(axis=1)``) + May be ignored in some cases, see the note below. + + Returns + ------- + distances : ndarray of shape (n_samples_X, n_samples_Y) + Returns the distances between the row vectors of `X` + and the row vectors of `Y`. + + See Also + -------- + paired_distances : Distances between pairs of elements of X and Y. + + Notes + ----- + To achieve a better accuracy, `X_norm_squared` and `Y_norm_squared` may be + unused if they are passed as `np.float32`. + + Examples + -------- + >>> from sklearn.metrics.pairwise import euclidean_distances + >>> X = [[0, 1], [1, 1]] + >>> # distance between rows of X + >>> euclidean_distances(X, X) + array([[0., 1.], + [1., 0.]]) + >>> # get distance to origin + >>> euclidean_distances(X, [[0, 0]]) + array([[1. ], + [1.41421356]]) + """ + X, Y = check_pairwise_arrays(X, Y) + + if X_norm_squared is not None: + X_norm_squared = check_array(X_norm_squared, ensure_2d=False) + original_shape = X_norm_squared.shape + if X_norm_squared.shape == (X.shape[0],): + X_norm_squared = X_norm_squared.reshape(-1, 1) + if X_norm_squared.shape == (1, X.shape[0]): + X_norm_squared = X_norm_squared.T + if X_norm_squared.shape != (X.shape[0], 1): + raise ValueError( + f"Incompatible dimensions for X of shape {X.shape} and " + f"X_norm_squared of shape {original_shape}." + ) + + if Y_norm_squared is not None: + Y_norm_squared = check_array(Y_norm_squared, ensure_2d=False) + original_shape = Y_norm_squared.shape + if Y_norm_squared.shape == (Y.shape[0],): + Y_norm_squared = Y_norm_squared.reshape(1, -1) + if Y_norm_squared.shape == (Y.shape[0], 1): + Y_norm_squared = Y_norm_squared.T + if Y_norm_squared.shape != (1, Y.shape[0]): + raise ValueError( + f"Incompatible dimensions for Y of shape {Y.shape} and " + f"Y_norm_squared of shape {original_shape}." + ) + + return _euclidean_distances(X, Y, X_norm_squared, Y_norm_squared, squared) + + +def _euclidean_distances(X, Y, X_norm_squared=None, Y_norm_squared=None, squared=False): + """Computational part of euclidean_distances + + Assumes inputs are already checked. + + If norms are passed as float32, they are unused. If arrays are passed as + float32, norms needs to be recomputed on upcast chunks. + TODO: use a float64 accumulator in row_norms to avoid the latter. + """ + if X_norm_squared is not None: + if X_norm_squared.dtype == np.float32: + XX = None + else: + XX = X_norm_squared.reshape(-1, 1) + elif X.dtype == np.float32: + XX = None + else: + XX = row_norms(X, squared=True)[:, np.newaxis] + + if Y is X: + YY = None if XX is None else XX.T + else: + if Y_norm_squared is not None: + if Y_norm_squared.dtype == np.float32: + YY = None + else: + YY = Y_norm_squared.reshape(1, -1) + elif Y.dtype == np.float32: + YY = None + else: + YY = row_norms(Y, squared=True)[np.newaxis, :] + + if X.dtype == np.float32: + # To minimize precision issues with float32, we compute the distance + # matrix on chunks of X and Y upcast to float64 + distances = _euclidean_distances_upcast(X, XX, Y, YY) + else: + # if dtype is already float64, no need to chunk and upcast + distances = -2 * safe_sparse_dot(X, Y.T, dense_output=True) + distances += XX + distances += YY + np.maximum(distances, 0, out=distances) + + # Ensure that distances between vectors and themselves are set to 0.0. + # This may not be the case due to floating point rounding errors. + if X is Y: + np.fill_diagonal(distances, 0) + + return distances if squared else np.sqrt(distances, out=distances) + + +def nan_euclidean_distances( + X, Y=None, *, squared=False, missing_values=np.nan, copy=True +): + """Calculate the euclidean distances in the presence of missing values. + + Compute the euclidean distance between each pair of samples in X and Y, + where Y=X is assumed if Y=None. When calculating the distance between a + pair of samples, this formulation ignores feature coordinates with a + missing value in either sample and scales up the weight of the remaining + coordinates: + + dist(x,y) = sqrt(weight * sq. distance from present coordinates) + where, + weight = Total # of coordinates / # of present coordinates + + For example, the distance between ``[3, na, na, 6]`` and ``[1, na, 4, 5]`` + is: + + .. math:: + \\sqrt{\\frac{4}{2}((3-1)^2 + (6-5)^2)} + + If all the coordinates are missing or if there are no common present + coordinates then NaN is returned for that pair. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.22 + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) + An array where each row is a sample and each column is a feature. + + Y : array-like of shape (n_samples_Y, n_features), default=None + An array where each row is a sample and each column is a feature. + If `None`, method uses `Y=X`. + + squared : bool, default=False + Return squared Euclidean distances. + + missing_values : np.nan or int, default=np.nan + Representation of missing value. + + copy : bool, default=True + Make and use a deep copy of X and Y (if Y exists). + + Returns + ------- + distances : ndarray of shape (n_samples_X, n_samples_Y) + Returns the distances between the row vectors of `X` + and the row vectors of `Y`. + + See Also + -------- + paired_distances : Distances between pairs of elements of X and Y. + + References + ---------- + * John K. Dixon, "Pattern Recognition with Partly Missing Data", + IEEE Transactions on Systems, Man, and Cybernetics, Volume: 9, Issue: + 10, pp. 617 - 621, Oct. 1979. + http://ieeexplore.ieee.org/abstract/document/4310090/ + + Examples + -------- + >>> from sklearn.metrics.pairwise import nan_euclidean_distances + >>> nan = float("NaN") + >>> X = [[0, 1], [1, nan]] + >>> nan_euclidean_distances(X, X) # distance between rows of X + array([[0. , 1.41421356], + [1.41421356, 0. ]]) + + >>> # get distance to origin + >>> nan_euclidean_distances(X, [[0, 0]]) + array([[1. ], + [1.41421356]]) + """ + + force_all_finite = "allow-nan" if is_scalar_nan(missing_values) else True + X, Y = check_pairwise_arrays( + X, Y, accept_sparse=False, force_all_finite=force_all_finite, copy=copy + ) + # Get missing mask for X + missing_X = _get_mask(X, missing_values) + + # Get missing mask for Y + missing_Y = missing_X if Y is X else _get_mask(Y, missing_values) + + # set missing values to zero + X[missing_X] = 0 + Y[missing_Y] = 0 + + distances = euclidean_distances(X, Y, squared=True) + + # Adjust distances for missing values + XX = X * X + YY = Y * Y + distances -= np.dot(XX, missing_Y.T) + distances -= np.dot(missing_X, YY.T) + + np.clip(distances, 0, None, out=distances) + + if X is Y: + # Ensure that distances between vectors and themselves are set to 0.0. + # This may not be the case due to floating point rounding errors. + np.fill_diagonal(distances, 0.0) + + present_X = 1 - missing_X + present_Y = present_X if Y is X else ~missing_Y + present_count = np.dot(present_X, present_Y.T) + distances[present_count == 0] = np.nan + # avoid divide by zero + np.maximum(1, present_count, out=present_count) + distances /= present_count + distances *= X.shape[1] + + if not squared: + np.sqrt(distances, out=distances) + + return distances + + +def _euclidean_distances_upcast(X, XX=None, Y=None, YY=None, batch_size=None): + """Euclidean distances between X and Y. + + Assumes X and Y have float32 dtype. + Assumes XX and YY have float64 dtype or are None. + + X and Y are upcast to float64 by chunks, which size is chosen to limit + memory increase by approximately 10% (at least 10MiB). + """ + n_samples_X = X.shape[0] + n_samples_Y = Y.shape[0] + n_features = X.shape[1] + + distances = np.empty((n_samples_X, n_samples_Y), dtype=np.float32) + + if batch_size is None: + x_density = X.nnz / np.prod(X.shape) if issparse(X) else 1 + y_density = Y.nnz / np.prod(Y.shape) if issparse(Y) else 1 + + # Allow 10% more memory than X, Y and the distance matrix take (at + # least 10MiB) + maxmem = max( + ( + (x_density * n_samples_X + y_density * n_samples_Y) * n_features + + (x_density * n_samples_X * y_density * n_samples_Y) + ) + / 10, + 10 * 2**17, + ) + + # The increase amount of memory in 8-byte blocks is: + # - x_density * batch_size * n_features (copy of chunk of X) + # - y_density * batch_size * n_features (copy of chunk of Y) + # - batch_size * batch_size (chunk of distance matrix) + # Hence x² + (xd+yd)kx = M, where x=batch_size, k=n_features, M=maxmem + # xd=x_density and yd=y_density + tmp = (x_density + y_density) * n_features + batch_size = (-tmp + np.sqrt(tmp**2 + 4 * maxmem)) / 2 + batch_size = max(int(batch_size), 1) + + x_batches = gen_batches(n_samples_X, batch_size) + + for i, x_slice in enumerate(x_batches): + X_chunk = X[x_slice].astype(np.float64) + if XX is None: + XX_chunk = row_norms(X_chunk, squared=True)[:, np.newaxis] + else: + XX_chunk = XX[x_slice] + + y_batches = gen_batches(n_samples_Y, batch_size) + + for j, y_slice in enumerate(y_batches): + if X is Y and j < i: + # when X is Y the distance matrix is symmetric so we only need + # to compute half of it. + d = distances[y_slice, x_slice].T + + else: + Y_chunk = Y[y_slice].astype(np.float64) + if YY is None: + YY_chunk = row_norms(Y_chunk, squared=True)[np.newaxis, :] + else: + YY_chunk = YY[:, y_slice] + + d = -2 * safe_sparse_dot(X_chunk, Y_chunk.T, dense_output=True) + d += XX_chunk + d += YY_chunk + + distances[x_slice, y_slice] = d.astype(np.float32, copy=False) + + return distances + + +def _argmin_min_reduce(dist, start): + # `start` is specified in the signature but not used. This is because the higher + # order `pairwise_distances_chunked` function needs reduction functions that are + # passed as argument to have a two arguments signature. + indices = dist.argmin(axis=1) + values = dist[np.arange(dist.shape[0]), indices] + return indices, values + + +def _argmin_reduce(dist, start): + # `start` is specified in the signature but not used. This is because the higher + # order `pairwise_distances_chunked` function needs reduction functions that are + # passed as argument to have a two arguments signature. + return dist.argmin(axis=1) + + +def pairwise_distances_argmin_min( + X, Y, *, axis=1, metric="euclidean", metric_kwargs=None +): + """Compute minimum distances between one point and a set of points. + + This function computes for each row in X, the index of the row of Y which + is closest (according to the specified distance). The minimal distances are + also returned. + + This is mostly equivalent to calling: + + (pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis), + pairwise_distances(X, Y=Y, metric=metric).min(axis=axis)) + + but uses much less memory, and is faster for large arrays. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + Array containing points. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) + Array containing points. + + axis : int, default=1 + Axis along which the argmin and distances are to be computed. + + metric : str or callable, default='euclidean' + Metric to use for distance computation. Any metric from scikit-learn + or scipy.spatial.distance can be used. + + If metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays as input and return one value indicating the + distance between them. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. + + Distance matrices are not supported. + + Valid values for metric are: + + - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan'] + + - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', + 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', + 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', + 'yule'] + + See the documentation for scipy.spatial.distance for details on these + metrics. + + metric_kwargs : dict, default=None + Keyword arguments to pass to specified metric function. + + Returns + ------- + argmin : ndarray + Y[argmin[i], :] is the row in Y that is closest to X[i, :]. + + distances : ndarray + The array of minimum distances. `distances[i]` is the distance between + the i-th row in X and the argmin[i]-th row in Y. + + See Also + -------- + pairwise_distances : Distances between every pair of samples of X and Y. + pairwise_distances_argmin : Same as `pairwise_distances_argmin_min` but only + returns the argmins. + """ + X, Y = check_pairwise_arrays(X, Y) + + if axis == 0: + X, Y = Y, X + + if metric_kwargs is None: + metric_kwargs = {} + + if ArgKmin.is_usable_for(X, Y, metric): + # This is an adaptor for one "sqeuclidean" specification. + # For this backend, we can directly use "sqeuclidean". + if metric_kwargs.get("squared", False) and metric == "euclidean": + metric = "sqeuclidean" + metric_kwargs = {} + + values, indices = ArgKmin.compute( + X=X, + Y=Y, + k=1, + metric=metric, + metric_kwargs=metric_kwargs, + strategy="auto", + return_distance=True, + ) + values = values.flatten() + indices = indices.flatten() + else: + # Joblib-based backend, which is used when user-defined callable + # are passed for metric. + + # This won't be used in the future once PairwiseDistancesReductions support: + # - DistanceMetrics which work on supposedly binary data + # - CSR-dense and dense-CSR case if 'euclidean' in metric. + + # Turn off check for finiteness because this is costly and because arrays + # have already been validated. + with config_context(assume_finite=True): + indices, values = zip( + *pairwise_distances_chunked( + X, Y, reduce_func=_argmin_min_reduce, metric=metric, **metric_kwargs + ) + ) + indices = np.concatenate(indices) + values = np.concatenate(values) + + return indices, values + + +def pairwise_distances_argmin(X, Y, *, axis=1, metric="euclidean", metric_kwargs=None): + """Compute minimum distances between one point and a set of points. + + This function computes for each row in X, the index of the row of Y which + is closest (according to the specified distance). + + This is mostly equivalent to calling: + + pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis) + + but uses much less memory, and is faster for large arrays. + + This function works with dense 2D arrays only. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + Array containing points. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) + Arrays containing points. + + axis : int, default=1 + Axis along which the argmin and distances are to be computed. + + metric : str or callable, default="euclidean" + Metric to use for distance computation. Any metric from scikit-learn + or scipy.spatial.distance can be used. + + If metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays as input and return one value indicating the + distance between them. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. + + Distance matrices are not supported. + + Valid values for metric are: + + - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan'] + + - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', + 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', + 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', + 'yule'] + + See the documentation for scipy.spatial.distance for details on these + metrics. + + metric_kwargs : dict, default=None + Keyword arguments to pass to specified metric function. + + Returns + ------- + argmin : numpy.ndarray + Y[argmin[i], :] is the row in Y that is closest to X[i, :]. + + See Also + -------- + pairwise_distances : Distances between every pair of samples of X and Y. + pairwise_distances_argmin_min : Same as `pairwise_distances_argmin` but also + returns the distances. + """ + if metric_kwargs is None: + metric_kwargs = {} + + X, Y = check_pairwise_arrays(X, Y) + + if axis == 0: + X, Y = Y, X + + if metric_kwargs is None: + metric_kwargs = {} + + if ArgKmin.is_usable_for(X, Y, metric): + # This is an adaptor for one "sqeuclidean" specification. + # For this backend, we can directly use "sqeuclidean". + if metric_kwargs.get("squared", False) and metric == "euclidean": + metric = "sqeuclidean" + metric_kwargs = {} + + indices = ArgKmin.compute( + X=X, + Y=Y, + k=1, + metric=metric, + metric_kwargs=metric_kwargs, + strategy="auto", + return_distance=False, + ) + indices = indices.flatten() + else: + # Joblib-based backend, which is used when user-defined callable + # are passed for metric. + + # This won't be used in the future once PairwiseDistancesReductions support: + # - DistanceMetrics which work on supposedly binary data + # - CSR-dense and dense-CSR case if 'euclidean' in metric. + + # Turn off check for finiteness because this is costly and because arrays + # have already been validated. + with config_context(assume_finite=True): + indices = np.concatenate( + list( + # This returns a np.ndarray generator whose arrays we need + # to flatten into one. + pairwise_distances_chunked( + X, Y, reduce_func=_argmin_reduce, metric=metric, **metric_kwargs + ) + ) + ) + + return indices + + +def haversine_distances(X, Y=None): + """Compute the Haversine distance between samples in X and Y. + + The Haversine (or great circle) distance is the angular distance between + two points on the surface of a sphere. The first coordinate of each point + is assumed to be the latitude, the second is the longitude, given + in radians. The dimension of the data must be 2. + + .. math:: + D(x, y) = 2\\arcsin[\\sqrt{\\sin^2((x1 - y1) / 2) + + \\cos(x1)\\cos(y1)\\sin^2((x2 - y2) / 2)}] + + Parameters + ---------- + X : array-like of shape (n_samples_X, 2) + A feature array. + + Y : array-like of shape (n_samples_Y, 2), default=None + An optional second feature array. If `None`, uses `Y=X`. + + Returns + ------- + distance : ndarray of shape (n_samples_X, n_samples_Y) + The distance matrix. + + Notes + ----- + As the Earth is nearly spherical, the haversine formula provides a good + approximation of the distance between two points of the Earth surface, with + a less than 1% error on average. + + Examples + -------- + We want to calculate the distance between the Ezeiza Airport + (Buenos Aires, Argentina) and the Charles de Gaulle Airport (Paris, + France). + + >>> from sklearn.metrics.pairwise import haversine_distances + >>> from math import radians + >>> bsas = [-34.83333, -58.5166646] + >>> paris = [49.0083899664, 2.53844117956] + >>> bsas_in_radians = [radians(_) for _ in bsas] + >>> paris_in_radians = [radians(_) for _ in paris] + >>> result = haversine_distances([bsas_in_radians, paris_in_radians]) + >>> result * 6371000/1000 # multiply by Earth radius to get kilometers + array([[ 0. , 11099.54035582], + [11099.54035582, 0. ]]) + """ + from ..metrics import DistanceMetric + + return DistanceMetric.get_metric("haversine").pairwise(X, Y) + + +def manhattan_distances(X, Y=None, *, sum_over_features="deprecated"): + """Compute the L1 distances between the vectors in X and Y. + + With sum_over_features equal to False it returns the componentwise + distances. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) + An array where each row is a sample and each column is a feature. + + Y : array-like of shape (n_samples_Y, n_features), default=None + An array where each row is a sample and each column is a feature. + If `None`, method uses `Y=X`. + + sum_over_features : bool, default=True + If True the function returns the pairwise distance matrix + else it returns the componentwise L1 pairwise-distances. + Not supported for sparse matrix inputs. + + .. deprecated:: 1.2 + ``sum_over_features`` was deprecated in version 1.2 and will be removed in + 1.4. + + Returns + ------- + D : ndarray of shape (n_samples_X * n_samples_Y, n_features) or \ + (n_samples_X, n_samples_Y) + If sum_over_features is False shape is + (n_samples_X * n_samples_Y, n_features) and D contains the + componentwise L1 pairwise-distances (ie. absolute difference), + else shape is (n_samples_X, n_samples_Y) and D contains + the pairwise L1 distances. + + Notes + ----- + When X and/or Y are CSR sparse matrices and they are not already + in canonical format, this function modifies them in-place to + make them canonical. + + Examples + -------- + >>> from sklearn.metrics.pairwise import manhattan_distances + >>> manhattan_distances([[3]], [[3]]) + array([[0.]]) + >>> manhattan_distances([[3]], [[2]]) + array([[1.]]) + >>> manhattan_distances([[2]], [[3]]) + array([[1.]]) + >>> manhattan_distances([[1, 2], [3, 4]],\ + [[1, 2], [0, 3]]) + array([[0., 2.], + [4., 4.]]) + """ + # TODO(1.4): remove sum_over_features + if sum_over_features != "deprecated": + warnings.warn( + "`sum_over_features` is deprecated in version 1.2 and will be" + " removed in version 1.4.", + FutureWarning, + ) + else: + sum_over_features = True + + X, Y = check_pairwise_arrays(X, Y) + + if issparse(X) or issparse(Y): + if not sum_over_features: + raise TypeError( + "sum_over_features=%r not supported for sparse matrices" + % sum_over_features + ) + + X = csr_matrix(X, copy=False) + Y = csr_matrix(Y, copy=False) + X.sum_duplicates() # this also sorts indices in-place + Y.sum_duplicates() + D = np.zeros((X.shape[0], Y.shape[0])) + _sparse_manhattan(X.data, X.indices, X.indptr, Y.data, Y.indices, Y.indptr, D) + return D + + if sum_over_features: + return distance.cdist(X, Y, "cityblock") + + D = X[:, np.newaxis, :] - Y[np.newaxis, :, :] + D = np.abs(D, D) + return D.reshape((-1, X.shape[1])) + + +def cosine_distances(X, Y=None): + """Compute cosine distance between samples in X and Y. + + Cosine distance is defined as 1.0 minus the cosine similarity. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + Matrix `X`. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), \ + default=None + Matrix `Y`. + + Returns + ------- + distance matrix : ndarray of shape (n_samples_X, n_samples_Y) + Returns the cosine distance between samples in X and Y. + + See Also + -------- + cosine_similarity : Compute cosine similarity between samples in X and Y. + scipy.spatial.distance.cosine : Dense matrices only. + """ + # 1.0 - cosine_similarity(X, Y) without copy + S = cosine_similarity(X, Y) + S *= -1 + S += 1 + np.clip(S, 0, 2, out=S) + if X is Y or Y is None: + # Ensure that distances between vectors and themselves are set to 0.0. + # This may not be the case due to floating point rounding errors. + S[np.diag_indices_from(S)] = 0.0 + return S + + +# Paired distances +def paired_euclidean_distances(X, Y): + """Compute the paired euclidean distances between X and Y. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Input array/matrix X. + + Y : array-like of shape (n_samples, n_features) + Input array/matrix Y. + + Returns + ------- + distances : ndarray of shape (n_samples,) + Output array/matrix containing the calculated paired euclidean + distances. + """ + X, Y = check_paired_arrays(X, Y) + return row_norms(X - Y) + + +def paired_manhattan_distances(X, Y): + """Compute the paired L1 distances between X and Y. + + Distances are calculated between (X[0], Y[0]), (X[1], Y[1]), ..., + (X[n_samples], Y[n_samples]). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + An array-like where each row is a sample and each column is a feature. + + Y : array-like of shape (n_samples, n_features) + An array-like where each row is a sample and each column is a feature. + + Returns + ------- + distances : ndarray of shape (n_samples,) + L1 paired distances between the row vectors of `X` + and the row vectors of `Y`. + + Examples + -------- + >>> from sklearn.metrics.pairwise import paired_manhattan_distances + >>> import numpy as np + >>> X = np.array([[1, 1, 0], [0, 1, 0], [0, 0, 1]]) + >>> Y = np.array([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) + >>> paired_manhattan_distances(X, Y) + array([1., 2., 1.]) + """ + X, Y = check_paired_arrays(X, Y) + diff = X - Y + if issparse(diff): + diff.data = np.abs(diff.data) + return np.squeeze(np.array(diff.sum(axis=1))) + else: + return np.abs(diff).sum(axis=-1) + + +def paired_cosine_distances(X, Y): + """ + Compute the paired cosine distances between X and Y. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + An array where each row is a sample and each column is a feature. + + Y : array-like of shape (n_samples, n_features) + An array where each row is a sample and each column is a feature. + + Returns + ------- + distances : ndarray of shape (n_samples,) + Returns the distances between the row vectors of `X` + and the row vectors of `Y`, where `distances[i]` is the + distance between `X[i]` and `Y[i]`. + + Notes + ----- + The cosine distance is equivalent to the half the squared + euclidean distance if each sample is normalized to unit norm. + """ + X, Y = check_paired_arrays(X, Y) + return 0.5 * row_norms(normalize(X) - normalize(Y), squared=True) + + +PAIRED_DISTANCES = { + "cosine": paired_cosine_distances, + "euclidean": paired_euclidean_distances, + "l2": paired_euclidean_distances, + "l1": paired_manhattan_distances, + "manhattan": paired_manhattan_distances, + "cityblock": paired_manhattan_distances, +} + + +def paired_distances(X, Y, *, metric="euclidean", **kwds): + """ + Compute the paired distances between X and Y. + + Compute the distances between (X[0], Y[0]), (X[1], Y[1]), etc... + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Array 1 for distance computation. + + Y : ndarray of shape (n_samples, n_features) + Array 2 for distance computation. + + 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 + specified in PAIRED_DISTANCES, including "euclidean", + "manhattan", or "cosine". + Alternatively, if metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays from `X` as input and return a value indicating + the distance between them. + + **kwds : dict + Unused parameters. + + Returns + ------- + distances : ndarray of shape (n_samples,) + Returns the distances between the row vectors of `X` + and the row vectors of `Y`. + + See Also + -------- + pairwise_distances : Computes the distance between every pair of samples. + + Examples + -------- + >>> from sklearn.metrics.pairwise import paired_distances + >>> X = [[0, 1], [1, 1]] + >>> Y = [[0, 1], [2, 1]] + >>> paired_distances(X, Y) + array([0., 1.]) + """ + + if metric in PAIRED_DISTANCES: + func = PAIRED_DISTANCES[metric] + return func(X, Y) + elif callable(metric): + # Check the matrix first (it is usually done by the metric) + X, Y = check_paired_arrays(X, Y) + distances = np.zeros(len(X)) + for i in range(len(X)): + distances[i] = metric(X[i], Y[i]) + return distances + else: + raise ValueError("Unknown distance %s" % metric) + + +# Kernels +def linear_kernel(X, Y=None, dense_output=True): + """ + Compute the linear kernel between X and Y. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + A feature array. + + Y : ndarray of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + dense_output : bool, default=True + Whether to return dense output even when the input is sparse. If + ``False``, the output is sparse if both input arrays are sparse. + + .. versionadded:: 0.20 + + Returns + ------- + Gram matrix : ndarray of shape (n_samples_X, n_samples_Y) + The Gram matrix of the linear kernel, i.e. `X @ Y.T`. + """ + X, Y = check_pairwise_arrays(X, Y) + return safe_sparse_dot(X, Y.T, dense_output=dense_output) + + +def polynomial_kernel(X, Y=None, degree=3, gamma=None, coef0=1): + """ + Compute the polynomial kernel between X and Y. + + :math:`K(X, Y) = (gamma + coef0)^{degree}` + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + A feature array. + + Y : ndarray of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + degree : int, default=3 + Kernel degree. + + gamma : float, default=None + Coefficient of the vector inner product. If None, defaults to 1.0 / n_features. + + coef0 : float, default=1 + Constant offset added to scaled inner product. + + Returns + ------- + Gram matrix : ndarray of shape (n_samples_X, n_samples_Y) + The polynomial kernel. + """ + X, Y = check_pairwise_arrays(X, Y) + if gamma is None: + gamma = 1.0 / X.shape[1] + + K = safe_sparse_dot(X, Y.T, dense_output=True) + K *= gamma + K += coef0 + K **= degree + return K + + +def sigmoid_kernel(X, Y=None, gamma=None, coef0=1): + """Compute the sigmoid kernel between X and Y. + + K(X, Y) = tanh(gamma + coef0) + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + A feature array. + + Y : ndarray of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + gamma : float, default=None + Coefficient of the vector inner product. If None, defaults to 1.0 / n_features. + + coef0 : float, default=1 + Constant offset added to scaled inner product. + + Returns + ------- + Gram matrix : ndarray of shape (n_samples_X, n_samples_Y) + Sigmoid kernel between two arrays. + """ + X, Y = check_pairwise_arrays(X, Y) + if gamma is None: + gamma = 1.0 / X.shape[1] + + K = safe_sparse_dot(X, Y.T, dense_output=True) + K *= gamma + K += coef0 + np.tanh(K, K) # compute tanh in-place + return K + + +def rbf_kernel(X, Y=None, gamma=None): + """Compute the rbf (gaussian) kernel between X and Y. + + K(x, y) = exp(-gamma ||x-y||^2) + + for each pair of rows x in X and y in Y. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + A feature array. + + Y : ndarray of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + gamma : float, default=None + If None, defaults to 1.0 / n_features. + + Returns + ------- + kernel_matrix : ndarray of shape (n_samples_X, n_samples_Y) + The RBF kernel. + """ + X, Y = check_pairwise_arrays(X, Y) + if gamma is None: + gamma = 1.0 / X.shape[1] + + K = euclidean_distances(X, Y, squared=True) + K *= -gamma + np.exp(K, K) # exponentiate K in-place + return K + + +def laplacian_kernel(X, Y=None, gamma=None): + """Compute the laplacian kernel between X and Y. + + The laplacian kernel is defined as:: + + K(x, y) = exp(-gamma ||x-y||_1) + + for each pair of rows x in X and y in Y. + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.17 + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + A feature array. + + Y : ndarray of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + gamma : float, default=None + If None, defaults to 1.0 / n_features. + + Returns + ------- + kernel_matrix : ndarray of shape (n_samples_X, n_samples_Y) + The kernel matrix. + """ + X, Y = check_pairwise_arrays(X, Y) + if gamma is None: + gamma = 1.0 / X.shape[1] + + K = -gamma * manhattan_distances(X, Y) + np.exp(K, K) # exponentiate K in-place + return K + + +def cosine_similarity(X, Y=None, dense_output=True): + """Compute cosine similarity between samples in X and Y. + + Cosine similarity, or the cosine kernel, computes similarity as the + normalized dot product of X and Y: + + K(X, Y) = / (||X||*||Y||) + + On L2-normalized data, this function is equivalent to linear_kernel. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples_X, n_features) + Input data. + + Y : {ndarray, sparse matrix} of shape (n_samples_Y, n_features), \ + default=None + Input data. If ``None``, the output will be the pairwise + similarities between all samples in ``X``. + + dense_output : bool, default=True + Whether to return dense output even when the input is sparse. If + ``False``, the output is sparse if both input arrays are sparse. + + .. versionadded:: 0.17 + parameter ``dense_output`` for dense output. + + Returns + ------- + kernel matrix : ndarray of shape (n_samples_X, n_samples_Y) + Returns the cosine similarity between samples in X and Y. + """ + # to avoid recursive import + + X, Y = check_pairwise_arrays(X, Y) + + X_normalized = normalize(X, copy=True) + if X is Y: + Y_normalized = X_normalized + else: + Y_normalized = normalize(Y, copy=True) + + K = safe_sparse_dot(X_normalized, Y_normalized.T, dense_output=dense_output) + + return K + + +def additive_chi2_kernel(X, Y=None): + """Compute the additive chi-squared kernel between observations in X and Y. + + The chi-squared kernel is computed between each pair of rows in X and Y. X + and Y have to be non-negative. This kernel is most commonly applied to + histograms. + + The chi-squared kernel is given by:: + + k(x, y) = -Sum [(x - y)^2 / (x + y)] + + It can be interpreted as a weighted difference per entry. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) + A feature array. + + Y : ndarray of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + Returns + ------- + kernel_matrix : ndarray of shape (n_samples_X, n_samples_Y) + The kernel matrix. + + See Also + -------- + chi2_kernel : The exponentiated version of the kernel, which is usually + preferable. + sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation + to this kernel. + + Notes + ----- + As the negative of a distance, this kernel is only conditionally positive + definite. + + References + ---------- + * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. + Local features and kernels for classification of texture and object + categories: A comprehensive study + International Journal of Computer Vision 2007 + https://hal.archives-ouvertes.fr/hal-00171412/document + """ + if issparse(X) or issparse(Y): + raise ValueError("additive_chi2 does not support sparse matrices.") + X, Y = check_pairwise_arrays(X, Y) + if (X < 0).any(): + raise ValueError("X contains negative values.") + if Y is not X and (Y < 0).any(): + raise ValueError("Y contains negative values.") + + result = np.zeros((X.shape[0], Y.shape[0]), dtype=X.dtype) + _chi2_kernel_fast(X, Y, result) + return result + + +def chi2_kernel(X, Y=None, gamma=1.0): + """Compute the exponential chi-squared kernel between X and Y. + + The chi-squared kernel is computed between each pair of rows in X and Y. X + and Y have to be non-negative. This kernel is most commonly applied to + histograms. + + The chi-squared kernel is given by:: + + k(x, y) = exp(-gamma Sum [(x - y)^2 / (x + y)]) + + It can be interpreted as a weighted difference per entry. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) + A feature array. + + Y : ndarray of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + gamma : float, default=1 + Scaling parameter of the chi2 kernel. + + Returns + ------- + kernel_matrix : ndarray of shape (n_samples_X, n_samples_Y) + The kernel matrix. + + See Also + -------- + additive_chi2_kernel : The additive version of this kernel. + sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation + to the additive version of this kernel. + + References + ---------- + * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. + Local features and kernels for classification of texture and object + categories: A comprehensive study + International Journal of Computer Vision 2007 + https://hal.archives-ouvertes.fr/hal-00171412/document + """ + K = additive_chi2_kernel(X, Y) + K *= gamma + return np.exp(K, K) + + +# Helper functions - distance +PAIRWISE_DISTANCE_FUNCTIONS = { + # If updating this dictionary, update the doc in both distance_metrics() + # and also in pairwise_distances()! + "cityblock": manhattan_distances, + "cosine": cosine_distances, + "euclidean": euclidean_distances, + "haversine": haversine_distances, + "l2": euclidean_distances, + "l1": manhattan_distances, + "manhattan": manhattan_distances, + "precomputed": None, # HACK: precomputed is always allowed, never called + "nan_euclidean": nan_euclidean_distances, +} + + +def distance_metrics(): + """Valid metrics for pairwise_distances. + + This function simply returns the valid pairwise distance metrics. + It exists to allow for a description of the mapping for + each of the valid strings. + + The valid distance metrics, and the function they map to, are: + + =============== ======================================== + metric Function + =============== ======================================== + 'cityblock' metrics.pairwise.manhattan_distances + 'cosine' metrics.pairwise.cosine_distances + 'euclidean' metrics.pairwise.euclidean_distances + 'haversine' metrics.pairwise.haversine_distances + 'l1' metrics.pairwise.manhattan_distances + 'l2' metrics.pairwise.euclidean_distances + 'manhattan' metrics.pairwise.manhattan_distances + 'nan_euclidean' metrics.pairwise.nan_euclidean_distances + =============== ======================================== + + Read more in the :ref:`User Guide `. + + Returns + ------- + distance_metrics : dict + Returns valid metrics for pairwise_distances. + """ + return PAIRWISE_DISTANCE_FUNCTIONS + + +def _dist_wrapper(dist_func, dist_matrix, slice_, *args, **kwargs): + """Write in-place to a slice of a distance matrix.""" + dist_matrix[:, slice_] = dist_func(*args, **kwargs) + + +def _parallel_pairwise(X, Y, func, n_jobs, **kwds): + """Break the pairwise matrix in n_jobs even slices + and compute them in parallel.""" + + if Y is None: + Y = X + X, Y, dtype = _return_float_dtype(X, Y) + + if effective_n_jobs(n_jobs) == 1: + return func(X, Y, **kwds) + + # enforce a threading backend to prevent data communication overhead + fd = delayed(_dist_wrapper) + ret = np.empty((X.shape[0], Y.shape[0]), dtype=dtype, order="F") + Parallel(backend="threading", n_jobs=n_jobs)( + fd(func, ret, s, X, Y[s], **kwds) + for s in gen_even_slices(_num_samples(Y), effective_n_jobs(n_jobs)) + ) + + if (X is Y or Y is None) and func is euclidean_distances: + # zeroing diagonal for euclidean norm. + # TODO: do it also for other norms. + np.fill_diagonal(ret, 0) + + return ret + + +def _pairwise_callable(X, Y, metric, force_all_finite=True, **kwds): + """Handle the callable case for pairwise_{distances,kernels}.""" + X, Y = check_pairwise_arrays(X, Y, force_all_finite=force_all_finite) + + if X is Y: + # Only calculate metric for upper triangle + out = np.zeros((X.shape[0], Y.shape[0]), dtype="float") + iterator = itertools.combinations(range(X.shape[0]), 2) + for i, j in iterator: + out[i, j] = metric(X[i], Y[j], **kwds) + + # Make symmetric + # NB: out += out.T will produce incorrect results + out = out + out.T + + # Calculate diagonal + # NB: nonzero diagonals are allowed for both metrics and kernels + for i in range(X.shape[0]): + x = X[i] + out[i, i] = metric(x, x, **kwds) + + else: + # Calculate all cells + out = np.empty((X.shape[0], Y.shape[0]), dtype="float") + iterator = itertools.product(range(X.shape[0]), range(Y.shape[0])) + for i, j in iterator: + out[i, j] = metric(X[i], Y[j], **kwds) + + return out + + +_VALID_METRICS = [ + "euclidean", + "l2", + "l1", + "manhattan", + "cityblock", + "braycurtis", + "canberra", + "chebyshev", + "correlation", + "cosine", + "dice", + "hamming", + "jaccard", + "kulsinski", + "mahalanobis", + "matching", + "minkowski", + "rogerstanimoto", + "russellrao", + "seuclidean", + "sokalmichener", + "sokalsneath", + "sqeuclidean", + "yule", + "wminkowski", + "nan_euclidean", + "haversine", +] + +_NAN_METRICS = ["nan_euclidean"] + + +def _check_chunk_size(reduced, chunk_size): + """Checks chunk is a sequence of expected size or a tuple of same.""" + if reduced is None: + return + is_tuple = isinstance(reduced, tuple) + if not is_tuple: + reduced = (reduced,) + if any(isinstance(r, tuple) or not hasattr(r, "__iter__") for r in reduced): + raise TypeError( + "reduce_func returned %r. Expected sequence(s) of length %d." + % (reduced if is_tuple else reduced[0], chunk_size) + ) + if any(_num_samples(r) != chunk_size for r in reduced): + actual_size = tuple(_num_samples(r) for r in reduced) + raise ValueError( + "reduce_func returned object of length %s. " + "Expected same length as input: %d." + % (actual_size if is_tuple else actual_size[0], chunk_size) + ) + + +def _precompute_metric_params(X, Y, metric=None, **kwds): + """Precompute data-derived metric parameters if not provided.""" + if metric == "seuclidean" and "V" not in kwds: + # There is a bug in scipy < 1.5 that will cause a crash if + # X.dtype != np.double (float64). See PR #15730 + dtype = np.float64 if sp_version < parse_version("1.5") else None + if X is Y: + V = np.var(X, axis=0, ddof=1, dtype=dtype) + else: + raise ValueError( + "The 'V' parameter is required for the seuclidean metric " + "when Y is passed." + ) + return {"V": V} + if metric == "mahalanobis" and "VI" not in kwds: + if X is Y: + VI = np.linalg.inv(np.cov(X.T)).T + else: + raise ValueError( + "The 'VI' parameter is required for the mahalanobis metric " + "when Y is passed." + ) + return {"VI": VI} + return {} + + +def pairwise_distances_chunked( + X, + Y=None, + *, + reduce_func=None, + metric="euclidean", + n_jobs=None, + working_memory=None, + **kwds, +): + """Generate a distance matrix chunk by chunk with optional reduction. + + In cases where not all of a pairwise distance matrix needs to be + stored at once, this is used to calculate pairwise distances in + ``working_memory``-sized chunks. If ``reduce_func`` is given, it is + run on each chunk and its return values are concatenated into lists, + arrays or sparse matrices. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_samples_X) or \ + (n_samples_X, n_features) + Array of pairwise distances between samples, or a feature array. + The shape the array should be (n_samples_X, n_samples_X) if + metric='precomputed' and (n_samples_X, n_features) otherwise. + + Y : ndarray of shape (n_samples_Y, n_features), default=None + An optional second feature array. Only allowed if + metric != "precomputed". + + reduce_func : callable, default=None + The function which is applied on each chunk of the distance matrix, + reducing it to needed values. ``reduce_func(D_chunk, start)`` + is called repeatedly, where ``D_chunk`` is a contiguous vertical + slice of the pairwise distance matrix, starting at row ``start``. + It should return one of: None; an array, a list, or a sparse matrix + of length ``D_chunk.shape[0]``; or a tuple of such objects. + Returning None is useful for in-place operations, rather than + reductions. + + If None, pairwise_distances_chunked returns a generator of vertical + chunks of the distance matrix. + + 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 scipy.spatial.distance.pdist for its metric parameter, + or a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS. + If metric is "precomputed", X is assumed to be a distance matrix. + Alternatively, if metric is a callable function, it is called on + each pair of instances (rows) and the resulting value recorded. + The callable should take two arrays from X as input and return a + value indicating the distance between them. + + n_jobs : int, default=None + The number of jobs to use for the computation. This works by + breaking down the pairwise matrix into n_jobs even slices and + computing them in parallel. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + working_memory : int, default=None + The sought maximum memory for temporary distance matrix chunks. + When None (default), the value of + ``sklearn.get_config()['working_memory']`` is used. + + **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. + + Yields + ------ + D_chunk : {ndarray, sparse matrix} + A contiguous slice of distance matrix, optionally processed by + ``reduce_func``. + + Examples + -------- + Without reduce_func: + + >>> import numpy as np + >>> from sklearn.metrics import pairwise_distances_chunked + >>> X = np.random.RandomState(0).rand(5, 3) + >>> D_chunk = next(pairwise_distances_chunked(X)) + >>> D_chunk + array([[0. ..., 0.29..., 0.41..., 0.19..., 0.57...], + [0.29..., 0. ..., 0.57..., 0.41..., 0.76...], + [0.41..., 0.57..., 0. ..., 0.44..., 0.90...], + [0.19..., 0.41..., 0.44..., 0. ..., 0.51...], + [0.57..., 0.76..., 0.90..., 0.51..., 0. ...]]) + + Retrieve all neighbors and average distance within radius r: + + >>> r = .2 + >>> def reduce_func(D_chunk, start): + ... neigh = [np.flatnonzero(d < r) for d in D_chunk] + ... avg_dist = (D_chunk * (D_chunk < r)).mean(axis=1) + ... return neigh, avg_dist + >>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func) + >>> neigh, avg_dist = next(gen) + >>> neigh + [array([0, 3]), array([1]), array([2]), array([0, 3]), array([4])] + >>> avg_dist + array([0.039..., 0. , 0. , 0.039..., 0. ]) + + Where r is defined per sample, we need to make use of ``start``: + + >>> r = [.2, .4, .4, .3, .1] + >>> def reduce_func(D_chunk, start): + ... neigh = [np.flatnonzero(d < r[i]) + ... for i, d in enumerate(D_chunk, start)] + ... return neigh + >>> neigh = next(pairwise_distances_chunked(X, reduce_func=reduce_func)) + >>> neigh + [array([0, 3]), array([0, 1]), array([2]), array([0, 3]), array([4])] + + Force row-by-row generation by reducing ``working_memory``: + + >>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func, + ... working_memory=0) + >>> next(gen) + [array([0, 3])] + >>> next(gen) + [array([0, 1])] + """ + n_samples_X = _num_samples(X) + if metric == "precomputed": + slices = (slice(0, n_samples_X),) + else: + if Y is None: + Y = X + # We get as many rows as possible within our working_memory budget to + # store len(Y) distances in each row of output. + # + # Note: + # - this will get at least 1 row, even if 1 row of distances will + # exceed working_memory. + # - this does not account for any temporary memory usage while + # calculating distances (e.g. difference of vectors in manhattan + # distance. + chunk_n_rows = get_chunk_n_rows( + row_bytes=8 * _num_samples(Y), + max_n_rows=n_samples_X, + working_memory=working_memory, + ) + slices = gen_batches(n_samples_X, chunk_n_rows) + + # precompute data-derived metric params + params = _precompute_metric_params(X, Y, metric=metric, **kwds) + kwds.update(**params) + + for sl in slices: + if sl.start == 0 and sl.stop == n_samples_X: + X_chunk = X # enable optimised paths for X is Y + else: + X_chunk = X[sl] + D_chunk = pairwise_distances(X_chunk, Y, metric=metric, n_jobs=n_jobs, **kwds) + if (X is Y or Y is None) and PAIRWISE_DISTANCE_FUNCTIONS.get( + metric, None + ) is euclidean_distances: + # zeroing diagonal, taking care of aliases of "euclidean", + # i.e. "l2" + D_chunk.flat[sl.start :: _num_samples(X) + 1] = 0 + if reduce_func is not None: + chunk_size = D_chunk.shape[0] + D_chunk = reduce_func(D_chunk, sl.start) + _check_chunk_size(D_chunk, chunk_size) + yield D_chunk + + +def pairwise_distances( + X, Y=None, metric="euclidean", *, n_jobs=None, force_all_finite=True, **kwds +): + """Compute the distance matrix from a vector array X and optional Y. + + This method takes either a vector array or a distance matrix, and returns + a distance matrix. If the input is a vector array, the distances are + computed. If the input is a distances matrix, it is returned instead. + + This method provides a safe way to take a distance matrix as input, while + preserving compatibility with many other algorithms that take a vector + array. + + If Y is given (default is None), then the returned matrix is the pairwise + distance between the arrays from both X and Y. + + Valid values for metric are: + + - From scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan']. These metrics support sparse matrix + inputs. + ['nan_euclidean'] but it does not yet support sparse matrices. + + - From scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', + 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', + 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'] + See the documentation for scipy.spatial.distance for details on these + metrics. These metrics do not support sparse matrix inputs. + + Note that in the case of 'cityblock', 'cosine' and 'euclidean' (which are + valid scipy.spatial.distance metrics), the scikit-learn implementation + will be used, which is faster and has support for sparse matrices (except + for 'cityblock'). For a verbose description of the metrics from + scikit-learn, see :func:`sklearn.metrics.pairwise.distance_metrics` + function. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_samples_X) or \ + (n_samples_X, n_features) + Array of pairwise distances between samples, or a feature array. + The shape of the array should be (n_samples_X, n_samples_X) if + metric == "precomputed" and (n_samples_X, n_features) otherwise. + + Y : ndarray of shape (n_samples_Y, n_features), default=None + An optional second feature array. Only allowed if + metric != "precomputed". + + 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 scipy.spatial.distance.pdist for its metric parameter, or + a metric listed in ``pairwise.PAIRWISE_DISTANCE_FUNCTIONS``. + If metric is "precomputed", X is assumed to be a distance matrix. + Alternatively, if metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays from X as input and return a value indicating + the distance between them. + + n_jobs : int, default=None + The number of jobs to use for the computation. This works by breaking + down the pairwise matrix into n_jobs even slices and computing them in + parallel. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + force_all_finite : bool or 'allow-nan', default=True + Whether to raise an error on np.inf, np.nan, pd.NA in array. Ignored + for a metric listed in ``pairwise.PAIRWISE_DISTANCE_FUNCTIONS``. The + possibilities are: + + - True: Force all values of array to be finite. + - False: accepts np.inf, np.nan, pd.NA in array. + - 'allow-nan': accepts only np.nan and pd.NA values in array. Values + cannot be infinite. + + .. versionadded:: 0.22 + ``force_all_finite`` accepts the string ``'allow-nan'``. + + .. versionchanged:: 0.23 + Accepts `pd.NA` and converts it into `np.nan`. + + **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 + ------- + D : ndarray of shape (n_samples_X, n_samples_X) or \ + (n_samples_X, n_samples_Y) + A distance matrix D such that D_{i, j} is the distance between the + ith and jth vectors of the given matrix X, if Y is None. + If Y is not None, then D_{i, j} is the distance between the ith array + from X and the jth array from Y. + + See Also + -------- + pairwise_distances_chunked : Performs the same calculation as this + function, but returns a generator of chunks of the distance matrix, in + order to limit memory usage. + paired_distances : Computes the distances between corresponding elements + of two arrays. + """ + if ( + metric not in _VALID_METRICS + and not callable(metric) + and metric != "precomputed" + ): + raise ValueError( + "Unknown metric %s. Valid metrics are %s, or 'precomputed', or a callable" + % (metric, _VALID_METRICS) + ) + + if metric == "precomputed": + X, _ = check_pairwise_arrays( + X, Y, precomputed=True, force_all_finite=force_all_finite + ) + + whom = ( + "`pairwise_distances`. Precomputed distance " + " need to have non-negative values." + ) + check_non_negative(X, whom=whom) + return X + elif metric in PAIRWISE_DISTANCE_FUNCTIONS: + func = PAIRWISE_DISTANCE_FUNCTIONS[metric] + elif callable(metric): + func = partial( + _pairwise_callable, metric=metric, force_all_finite=force_all_finite, **kwds + ) + else: + if issparse(X) or issparse(Y): + raise TypeError("scipy distance metrics do not support sparse matrices.") + + dtype = bool if metric in PAIRWISE_BOOLEAN_FUNCTIONS else None + + if dtype == bool and (X.dtype != bool or (Y is not None and Y.dtype != bool)): + msg = "Data was converted to boolean for metric %s" % metric + warnings.warn(msg, DataConversionWarning) + + X, Y = check_pairwise_arrays( + X, Y, dtype=dtype, force_all_finite=force_all_finite + ) + + # precompute data-derived metric params + params = _precompute_metric_params(X, Y, metric=metric, **kwds) + kwds.update(**params) + + if effective_n_jobs(n_jobs) == 1 and X is Y: + return distance.squareform(distance.pdist(X, metric=metric, **kwds)) + func = partial(distance.cdist, metric=metric, **kwds) + + return _parallel_pairwise(X, Y, func, n_jobs, **kwds) + + +# These distances require boolean arrays, when using scipy.spatial.distance +PAIRWISE_BOOLEAN_FUNCTIONS = [ + "dice", + "jaccard", + "kulsinski", + "matching", + "rogerstanimoto", + "russellrao", + "sokalmichener", + "sokalsneath", + "yule", +] + +# Helper functions - distance +PAIRWISE_KERNEL_FUNCTIONS = { + # If updating this dictionary, update the doc in both distance_metrics() + # and also in pairwise_distances()! + "additive_chi2": additive_chi2_kernel, + "chi2": chi2_kernel, + "linear": linear_kernel, + "polynomial": polynomial_kernel, + "poly": polynomial_kernel, + "rbf": rbf_kernel, + "laplacian": laplacian_kernel, + "sigmoid": sigmoid_kernel, + "cosine": cosine_similarity, +} + + +def kernel_metrics(): + """Valid metrics for pairwise_kernels. + + This function simply returns the valid pairwise distance metrics. + It exists, however, to allow for a verbose description of the mapping for + each of the valid strings. + + The valid distance metrics, and the function they map to, are: + =============== ======================================== + metric Function + =============== ======================================== + 'additive_chi2' sklearn.pairwise.additive_chi2_kernel + 'chi2' sklearn.pairwise.chi2_kernel + 'linear' sklearn.pairwise.linear_kernel + 'poly' sklearn.pairwise.polynomial_kernel + 'polynomial' sklearn.pairwise.polynomial_kernel + 'rbf' sklearn.pairwise.rbf_kernel + 'laplacian' sklearn.pairwise.laplacian_kernel + 'sigmoid' sklearn.pairwise.sigmoid_kernel + 'cosine' sklearn.pairwise.cosine_similarity + =============== ======================================== + + Read more in the :ref:`User Guide `. + + Returns + ------- + kernal_metrics : dict + Returns valid metrics for pairwise_kernels. + """ + return PAIRWISE_KERNEL_FUNCTIONS + + +KERNEL_PARAMS = { + "additive_chi2": (), + "chi2": frozenset(["gamma"]), + "cosine": (), + "linear": (), + "poly": frozenset(["gamma", "degree", "coef0"]), + "polynomial": frozenset(["gamma", "degree", "coef0"]), + "rbf": frozenset(["gamma"]), + "laplacian": frozenset(["gamma"]), + "sigmoid": frozenset(["gamma", "coef0"]), +} + + +def pairwise_kernels( + X, Y=None, metric="linear", *, filter_params=False, n_jobs=None, **kwds +): + """Compute the kernel between arrays X and optional array Y. + + This method takes either a vector array or a kernel matrix, and returns + a kernel matrix. If the input is a vector array, the kernels are + computed. If the input is a kernel matrix, it is returned instead. + + This method provides a safe way to take a kernel matrix as input, while + preserving compatibility with many other algorithms that take a vector + array. + + If Y is given (default is None), then the returned matrix is the pairwise + kernel between the arrays from both X and Y. + + Valid values for metric are: + ['additive_chi2', 'chi2', 'linear', 'poly', 'polynomial', 'rbf', + 'laplacian', 'sigmoid', 'cosine'] + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_samples_X) or (n_samples_X, n_features) + Array of pairwise kernels between samples, or a feature array. + The shape of the array should be (n_samples_X, n_samples_X) if + metric == "precomputed" and (n_samples_X, n_features) otherwise. + + Y : ndarray of shape (n_samples_Y, n_features), default=None + A second feature array only if X has shape (n_samples_X, n_features). + + metric : str or callable, default="linear" + The metric to use when calculating kernel between instances in a + feature array. If metric is a string, it must be one of the metrics + in pairwise.PAIRWISE_KERNEL_FUNCTIONS. + If metric is "precomputed", X is assumed to be a kernel matrix. + Alternatively, if metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two rows from X as input and return the corresponding + kernel value as a single number. This means that callables from + :mod:`sklearn.metrics.pairwise` are not allowed, as they operate on + matrices, not single samples. Use the string identifying the kernel + instead. + + filter_params : bool, default=False + Whether to filter invalid parameters or not. + + n_jobs : int, default=None + The number of jobs to use for the computation. This works by breaking + down the pairwise matrix into n_jobs even slices and computing them in + parallel. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + **kwds : optional keyword parameters + Any further parameters are passed directly to the kernel function. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_X) or (n_samples_X, n_samples_Y) + A kernel matrix K such that K_{i, j} is the kernel between the + ith and jth vectors of the given matrix X, if Y is None. + If Y is not None, then K_{i, j} is the kernel between the ith array + from X and the jth array from Y. + + Notes + ----- + If metric is 'precomputed', Y is ignored and X is returned. + """ + # import GPKernel locally to prevent circular imports + from ..gaussian_process.kernels import Kernel as GPKernel + + if metric == "precomputed": + X, _ = check_pairwise_arrays(X, Y, precomputed=True) + return X + elif isinstance(metric, GPKernel): + func = metric.__call__ + elif metric in PAIRWISE_KERNEL_FUNCTIONS: + if filter_params: + kwds = {k: kwds[k] for k in kwds if k in KERNEL_PARAMS[metric]} + func = PAIRWISE_KERNEL_FUNCTIONS[metric] + elif callable(metric): + func = partial(_pairwise_callable, metric=metric, **kwds) + else: + raise ValueError("Unknown kernel %r" % metric) + + return _parallel_pairwise(X, Y, func, n_jobs, **kwds) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e43163badd3b4a18315cd489a6d2125ac030ad6f Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_arpack.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_arpack.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b54ca65b8a7b2115b30c9ee8c0203b0e1d3c471 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_arpack.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_array_api.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_array_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f63adcad8d2768bb50a66f7183481cbea3491e80 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_array_api.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_bunch.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_bunch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd64d5b65200913683d338ddcc2b9ef9b1aa0037 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_bunch.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_estimator_html_repr.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_estimator_html_repr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f80a94665e103bd89dc1b6c8146e074cf96e36d Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_estimator_html_repr.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_joblib.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_joblib.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d785a6ebd32b64c331400788797d93c086c1ac4 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_joblib.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_param_validation.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_param_validation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb7000c8e7cab0fa2fa7a079d2a898074e868e8c Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_param_validation.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_pprint.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_pprint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78193829f7d99c85abe91fb7ff117d4119875d4f Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_pprint.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/class_weight.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/class_weight.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..591d63a4ad9850410ae290aaf012eb2200d707d9 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/class_weight.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/discovery.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/discovery.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a927c18bc3168ad6c2c34f88244fdc96d08edc5a Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/discovery.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/metaestimators.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/metaestimators.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05bfa3f55307b565099577744d4c7cb8a7f5124e Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/metaestimators.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/parallel.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/parallel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58c224e3ec357bf46454c3691297ba26ae27c857 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/parallel.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/random.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/random.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ba3a60e15a914bb34186247f76c0fd94bb36fea Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/random.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/sparsefuncs.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/sparsefuncs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..833c0818ed037de66ab8caefe50abb8e7b6fc3ec Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/sparsefuncs.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_assert_async_cpu_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_assert_async_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b86572c7e28bec53883a61bff7a17acbd65d1191 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_assert_async_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 void _assert_async(const at::Tensor & self); +TORCH_API void _assert_async(const at::Tensor & self, c10::string_view assert_msg); + +} // namespace cpu +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Char_compositeimplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Char_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..65388193206ff3e2c9425335637b62c8f8a0effe --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cast_Char_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 _cast_Char(const at::Tensor & self, bool non_blocking=false); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_copy_from_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_copy_from_native.h new file mode 100644 index 0000000000000000000000000000000000000000..4471cf73f2b7d1c21d91ca164f8baf7818fa829c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_copy_from_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 & _copy_from_out(const at::Tensor & self, const at::Tensor & dst, bool non_blocking, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..a5cd2aff65e7acbd45dae7c7e5e6e291493d17ce --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_embedding_bag_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 _embedding_bag { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, bool, int64_t, bool, const ::std::optional &, bool, 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") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1) -> (Tensor, Tensor, Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional & per_sample_weights, bool include_last_offset, int64_t padding_idx); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional & per_sample_weights, bool include_last_offset, int64_t padding_idx); +}; + +struct TORCH_API _embedding_bag_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, const at::Tensor &, bool, int64_t, bool, const ::std::optional &, bool, int64_t, at::Tensor &, at::Tensor &, 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::_embedding_bag") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_embedding_bag.out(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!))") + static ::std::tuple call(const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional & per_sample_weights, bool include_last_offset, int64_t padding_idx, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq, int64_t mode, bool sparse, const ::std::optional & per_sample_weights, bool include_last_offset, int64_t padding_idx, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_tanh_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_tanh_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..6b261fc131cb71b27ac2448fac375de2f33c6c06 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_tanh_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 _foreach_tanh { + using schema = ::std::vector (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_tanh") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_tanh(Tensor[] self) -> Tensor[]") + static ::std::vector call(at::TensorList self); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_tanh_ { + using schema = void (at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_tanh_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_tanh_(Tensor(a!)[] self) -> ()") + static void call(at::TensorList self); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self); +}; + +struct TORCH_API _foreach_tanh_out { + using schema = void (at::TensorList, at::TensorList); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_foreach_tanh") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_tanh.out(Tensor[] self, *, Tensor(a!)[] out) -> ()") + static void call(at::TensorList self, at::TensorList out); + static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sobol_engine_draw_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sobol_engine_draw_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c9e03ba718199a5ee9fd6c1c1a87dc241d62481b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sobol_engine_draw_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 _sobol_engine_draw { + using schema = ::std::tuple (const at::Tensor &, int64_t, const at::Tensor &, int64_t, int64_t, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sobol_engine_draw") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sobol_engine_draw(Tensor quasi, int n, Tensor sobolstate, int dimension, int num_generated, ScalarType? dtype) -> (Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & quasi, int64_t n, const at::Tensor & sobolstate, int64_t dimension, int64_t num_generated, ::std::optional dtype); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & quasi, int64_t n, const at::Tensor & sobolstate, int64_t dimension, int64_t num_generated, ::std::optional dtype); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_semi_structured_tile_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_semi_structured_tile_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..0a76c27fbf4bbdc0f6a922c556630456d520462e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_semi_structured_tile_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 _sparse_semi_structured_tile { + using schema = ::std::tuple (const at::Tensor &, c10::string_view, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_semi_structured_tile") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_semi_structured_tile(Tensor input, str algorithm=\"\", bool use_cutlass=True) -> (Tensor, Tensor, Tensor, Tensor, Tensor)") + static ::std::tuple call(const at::Tensor & input, c10::string_view algorithm, bool use_cutlass); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, c10::string_view algorithm, bool use_cutlass); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..e06b2dc1c25f8656c0ef3c69188493c613b65a34 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell_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 _thnn_fused_lstm_cell(const at::Tensor & input_gates, const at::Tensor & hidden_gates, const at::Tensor & cx, const ::std::optional & input_bias={}, const ::std::optional & hidden_bias={}); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/arccosh_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/arccosh_native.h new file mode 100644 index 0000000000000000000000000000000000000000..2e648a299bcdc2f9476bfee79099c46b9487d9be --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/arccosh_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 + + +namespace at { +namespace native { +TORCH_API at::Tensor arccosh(const at::Tensor & self); +TORCH_API at::Tensor & arccosh_out(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & arccosh_(at::Tensor & self); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/batch_norm_update_stats.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/batch_norm_update_stats.h new file mode 100644 index 0000000000000000000000000000000000000000..da735da08a7d199bf8239ad04a5ad2a386029dc8 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/batch_norm_update_stats.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::batch_norm_update_stats(Tensor input, Tensor? running_mean, Tensor? running_var, float momentum) -> (Tensor, Tensor) +inline ::std::tuple batch_norm_update_stats(const at::Tensor & input, const ::std::optional & running_mean, const ::std::optional & running_var, double momentum) { + return at::_ops::batch_norm_update_stats::call(input, running_mean, running_var, momentum); +} + +// aten::batch_norm_update_stats.out(Tensor input, Tensor? running_mean, Tensor? running_var, float momentum, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple batch_norm_update_stats_out(at::Tensor & out0, at::Tensor & out1, const at::Tensor & input, const ::std::optional & running_mean, const ::std::optional & running_var, double momentum) { + return at::_ops::batch_norm_update_stats_out::call(input, running_mean, running_var, momentum, out0, out1); +} +// aten::batch_norm_update_stats.out(Tensor input, Tensor? running_mean, Tensor? running_var, float momentum, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple batch_norm_update_stats_outf(const at::Tensor & input, const ::std::optional & running_mean, const ::std::optional & running_var, double momentum, at::Tensor & out0, at::Tensor & out1) { + return at::_ops::batch_norm_update_stats_out::call(input, running_mean, running_var, momentum, out0, out1); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy_with_logits_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy_with_logits_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..8f844c84e66b4b82970cade33e371c6e5176c228 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy_with_logits_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 binary_cross_entropy_with_logits(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, const ::std::optional & pos_weight={}, int64_t reduction=at::Reduction::Mean); +TORCH_API at::Tensor & binary_cross_entropy_with_logits_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, const ::std::optional & pos_weight={}, int64_t reduction=at::Reduction::Mean); +TORCH_API at::Tensor & binary_cross_entropy_with_logits_outf(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, const ::std::optional & pos_weight, int64_t reduction, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/conv_transpose3d_compositeimplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/conv_transpose3d_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..5a2490e5d71a419e39c96de04de0fb4cbda373a1 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/conv_transpose3d_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 conv_transpose3d(const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, int64_t groups=1, at::IntArrayRef dilation=1); +TORCH_API at::Tensor conv_transpose3d_symint(const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymInt groups=1, c10::SymIntArrayRef dilation=c10::SymInt(1)); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/corrcoef_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/corrcoef_native.h new file mode 100644 index 0000000000000000000000000000000000000000..20b6127377beb61089a37539b23e1644903ff85f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/corrcoef_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 corrcoef(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_convolution_add_relu.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_convolution_add_relu.h new file mode 100644 index 0000000000000000000000000000000000000000..bdca8ddcd64942021d532163ee301fa92ba3ca5d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_convolution_add_relu.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::cudnn_convolution_add_relu(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor +inline at::Tensor cudnn_convolution_add_relu(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional & alpha, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups) { + return at::_ops::cudnn_convolution_add_relu::call(self, weight, z, alpha, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups); +} +namespace symint { + template ::value>> + at::Tensor cudnn_convolution_add_relu(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional & alpha, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups) { + return at::_ops::cudnn_convolution_add_relu::call(self, weight, z, alpha, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups); + } +} + +// aten::cudnn_convolution_add_relu(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups) -> Tensor +inline at::Tensor cudnn_convolution_add_relu_symint(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional & alpha, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups) { + return at::_ops::cudnn_convolution_add_relu::call(self, weight, z, alpha, bias, stride, padding, dilation, groups); +} +namespace symint { + template ::value>> + at::Tensor cudnn_convolution_add_relu(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional & alpha, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups) { + return at::_ops::cudnn_convolution_add_relu::call(self, weight, z, alpha, bias, stride, padding, dilation, groups); + } +} + +// aten::cudnn_convolution_add_relu.out(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & cudnn_convolution_add_relu_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional & alpha, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups) { + return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups, out); +} +namespace symint { + template ::value>> + at::Tensor & cudnn_convolution_add_relu_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional & alpha, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups) { + return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups, out); + } +} + +// aten::cudnn_convolution_add_relu.out(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & cudnn_convolution_add_relu_outf(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional & alpha, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups, at::Tensor & out) { + return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups, out); +} +namespace symint { + template ::value>> + at::Tensor & cudnn_convolution_add_relu_outf(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional & alpha, const ::std::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, int64_t groups, at::Tensor & out) { + return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(dilation), groups, out); + } +} + +// aten::cudnn_convolution_add_relu.out(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & cudnn_convolution_add_relu_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional & alpha, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups) { + return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, stride, padding, dilation, groups, out); +} +namespace symint { + template ::value>> + at::Tensor & cudnn_convolution_add_relu_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional & alpha, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups) { + return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, stride, padding, dilation, groups, out); + } +} + +// aten::cudnn_convolution_add_relu.out(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, SymInt[] stride, SymInt[] padding, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & cudnn_convolution_add_relu_symint_outf(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional & alpha, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups, at::Tensor & out) { + return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, stride, padding, dilation, groups, out); +} +namespace symint { + template ::value>> + at::Tensor & cudnn_convolution_add_relu_outf(const at::Tensor & self, const at::Tensor & weight, const at::Tensor & z, const ::std::optional & alpha, const ::std::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef dilation, c10::SymInt groups, at::Tensor & out) { + return at::_ops::cudnn_convolution_add_relu_out::call(self, weight, z, alpha, bias, stride, padding, dilation, groups, out); + } +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/deg2rad.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/deg2rad.h new file mode 100644 index 0000000000000000000000000000000000000000..e284f242c36cfcb15af3379845f10a8ba3b77cee --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/deg2rad.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::deg2rad(Tensor self) -> Tensor +inline at::Tensor deg2rad(const at::Tensor & self) { + return at::_ops::deg2rad::call(self); +} + +// aten::deg2rad_(Tensor(a!) self) -> Tensor(a!) +inline at::Tensor & deg2rad_(at::Tensor & self) { + return at::_ops::deg2rad_::call(self); +} + +// aten::deg2rad.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & deg2rad_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::deg2rad_out::call(self, out); +} +// aten::deg2rad.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & deg2rad_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::deg2rad_out::call(self, out); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/einsum_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/einsum_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..bf977c9dd59ec4817ff74c2fcdb128f5430b77d8 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/einsum_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 einsum { + using schema = at::Tensor (c10::string_view, at::TensorList, at::OptionalIntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::einsum") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "einsum(str equation, Tensor[] tensors, *, int[]? path=None) -> Tensor") + static at::Tensor call(c10::string_view equation, at::TensorList tensors, at::OptionalIntArrayRef path); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, c10::string_view equation, at::TensorList tensors, at::OptionalIntArrayRef path); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/elu_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/elu_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..1b203e9f8301a85ad072e8c4709e598010436cf9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/elu_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_elu : public TensorIteratorBase { + + + void meta(const at::Tensor & self, const at::Scalar & alpha, const at::Scalar & scale, const at::Scalar & input_scale); +}; + +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fft_fft2.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fft_fft2.h new file mode 100644 index 0000000000000000000000000000000000000000..ac43cc0ca2bb379c08519b3ca933a90dd9cc0d82 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fft_fft2.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::fft_fft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor +inline at::Tensor fft_fft2(const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_fft2::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm); +} +namespace symint { + template ::value>> + at::Tensor fft_fft2(const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_fft2::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm); + } +} + +// aten::fft_fft2(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor +inline at::Tensor fft_fft2_symint(const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_fft2::call(self, s, dim, norm); +} +namespace symint { + template ::value>> + at::Tensor fft_fft2(const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_fft2::call(self, s, dim, norm); + } +} + +// aten::fft_fft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_fft2_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_fft2_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out); +} +namespace symint { + template ::value>> + at::Tensor & fft_fft2_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_fft2_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out); + } +} + +// aten::fft_fft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_fft2_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::IntArrayRef dim, ::std::optional norm, at::Tensor & out) { + return at::_ops::fft_fft2_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out); +} +namespace symint { + template ::value>> + at::Tensor & fft_fft2_outf(const at::Tensor & self, at::OptionalIntArrayRef s, at::IntArrayRef dim, ::std::optional norm, at::Tensor & out) { + return at::_ops::fft_fft2_out::call(self, s.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*s)) : ::std::nullopt, dim, norm, out); + } +} + +// aten::fft_fft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_fft2_symint_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_fft2_out::call(self, s, dim, norm, out); +} +namespace symint { + template ::value>> + at::Tensor & fft_fft2_out(at::Tensor & out, const at::Tensor & self, at::OptionalSymIntArrayRef s=::std::nullopt, at::IntArrayRef dim={-2,-1}, ::std::optional norm=::std::nullopt) { + return at::_ops::fft_fft2_out::call(self, s, dim, norm, out); + } +} + +// aten::fft_fft2.out(Tensor self, SymInt[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & fft_fft2_symint_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::IntArrayRef dim, ::std::optional norm, at::Tensor & out) { + return at::_ops::fft_fft2_out::call(self, s, dim, norm, out); +} +namespace symint { + template ::value>> + at::Tensor & fft_fft2_outf(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::IntArrayRef dim, ::std::optional norm, at::Tensor & out) { + return at::_ops::fft_fft2_out::call(self, s, dim, norm, out); + } +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/grid_sampler_2d_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/grid_sampler_2d_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9298432c61f44b8489e96f9e28a028ef8f894d12 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/grid_sampler_2d_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 at::Tensor grid_sampler_2d(const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/hypot_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/hypot_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..4825a2a111d53ee864a820cfa7b6201a6639c107 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/hypot_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_hypot : 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/is_coalesced_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_coalesced_native.h new file mode 100644 index 0000000000000000000000000000000000000000..319f5bd5214d820ed7a840538d60d9df735ad870 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_coalesced_native.h @@ -0,0 +1,22 @@ +#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 bool is_coalesced_default(const at::Tensor & self); +TORCH_API bool is_coalesced_sparse(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_pinv_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_pinv_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..2841cd87424b4f8a5b6362f7ca44e52ff5aacc67 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_pinv_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 at::Tensor & linalg_pinv_out(at::Tensor & out, const at::Tensor & self, const ::std::optional & atol={}, const ::std::optional & rtol={}, bool hermitian=false); +TORCH_API at::Tensor & linalg_pinv_outf(const at::Tensor & self, const ::std::optional & atol, const ::std::optional & rtol, bool hermitian, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/lt_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/lt_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..dce5c55d8f7891f3aeef763d7b5e78339a82b305 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/lt_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 lt_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::lt") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lt.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 lt_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::lt") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lt.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 lt_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::lt") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lt.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); +}; + +struct TORCH_API lt_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::lt") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lt.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 lt__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::lt_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lt_.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 lt__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::lt_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lt_.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); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mH_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mH_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c7920a7e54ca41c26c57db3209673f7d704dab40 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mH_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 mH { + 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::mH") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "mH(Tensor(a) self) -> Tensor(a)") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mean_meta_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mean_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1e4e7f57b5913a376d7fa89e447a7d22300fbe1c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mean_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 mean(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false, ::std::optional dtype=::std::nullopt); +TORCH_API at::Tensor & mean_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false, ::std::optional dtype=::std::nullopt); +TORCH_API at::Tensor & mean_outf(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, ::std::optional dtype, at::Tensor & out); + +} // namespace meta +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/native_dropout_backward_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/native_dropout_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..c9cfb3cc5c074eed5468ea60f3243f86fae77788 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/native_dropout_backward_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 native_dropout_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, double); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::native_dropout_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "native_dropout_backward(Tensor grad_output, Tensor mask, float scale) -> Tensor") + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & mask, double scale); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & mask, double scale); +}; + +struct TORCH_API native_dropout_backward_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, double, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::native_dropout_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "native_dropout_backward.out(Tensor grad_output, Tensor mask, float scale, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & mask, double scale, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & mask, double scale, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/native_group_norm_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/native_group_norm_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..63b7fd1cef531088104763f3789e140932d3b9be --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/native_group_norm_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 ::std::tuple native_group_norm(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, int64_t N, int64_t C, int64_t HxW, int64_t group, double eps); +TORCH_API ::std::tuple native_group_norm_symint(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, c10::SymInt N, c10::SymInt C, c10::SymInt HxW, int64_t group, double eps); +TORCH_API ::std::tuple native_group_norm_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, int64_t N, int64_t C, int64_t HxW, int64_t group, double eps); +TORCH_API ::std::tuple native_group_norm_outf(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, int64_t N, int64_t C, int64_t HxW, int64_t group, double eps, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2); +TORCH_API ::std::tuple native_group_norm_symint_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, c10::SymInt N, c10::SymInt C, c10::SymInt HxW, int64_t group, double eps); +TORCH_API ::std::tuple native_group_norm_symint_outf(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, c10::SymInt N, c10::SymInt C, c10::SymInt HxW, int64_t group, double eps, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/new_empty_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/new_empty_native.h new file mode 100644 index 0000000000000000000000000000000000000000..0cb922b3f44b7e19b62630cc4c821f82810ed2f2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/new_empty_native.h @@ -0,0 +1,22 @@ +#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 new_empty_symint(const at::Tensor & self, c10::SymIntArrayRef size, ::std::optional dtype={}, ::std::optional layout={}, ::std::optional device={}, ::std::optional pin_memory={}); +TORCH_API at::Tensor & new_empty_out_symint(const at::Tensor & self, c10::SymIntArrayRef size, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/replication_pad3d_compositeexplicitautogradnonfunctional_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/replication_pad3d_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..d14ed35d343f131dd660727d022b66f59de970d7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/replication_pad3d_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 replication_pad3d(const at::Tensor & self, at::IntArrayRef padding); +TORCH_API at::Tensor replication_pad3d_symint(const at::Tensor & self, c10::SymIntArrayRef padding); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/reshape_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/reshape_native.h new file mode 100644 index 0000000000000000000000000000000000000000..82e656663843a3c1b3de4ab363de5d1027503388 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/reshape_native.h @@ -0,0 +1,22 @@ +#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 reshape_symint(const at::Tensor & self, c10::SymIntArrayRef shape); +TORCH_API at::Tensor reshape_nested_symint(const at::Tensor & self, c10::SymIntArrayRef shape); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/row_stack_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/row_stack_native.h new file mode 100644 index 0000000000000000000000000000000000000000..d1940b0a2b3158925e6d632fcb64073009f65d7c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/row_stack_native.h @@ -0,0 +1,22 @@ +#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 row_stack(at::TensorList tensors); +TORCH_API at::Tensor & row_stack_out(at::TensorList tensors, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/rsqrt_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/rsqrt_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..cf91ed832b3a82af8b4a636ba56df72122563792 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/rsqrt_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_rsqrt : 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/special_chebyshev_polynomial_t_compositeexplicitautogradnonfunctional_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_t_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c380004c13e6ab26e01caea07ffd2214528af014 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_t_compositeexplicitautogradnonfunctional_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 compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor special_chebyshev_polynomial_t(const at::Tensor & x, const at::Tensor & n); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_digamma.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_digamma.h new file mode 100644 index 0000000000000000000000000000000000000000..c4c2bad856134692c93fc0e10e8693ef82aaf924 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_digamma.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::special_digamma(Tensor self) -> Tensor +inline at::Tensor special_digamma(const at::Tensor & self) { + return at::_ops::special_digamma::call(self); +} + +// aten::special_digamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_digamma_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::special_digamma_out::call(self, out); +} +// aten::special_digamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_digamma_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::special_digamma_out::call(self, out); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_erf_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_erf_native.h new file mode 100644 index 0000000000000000000000000000000000000000..c24de7dd216da2c483a8bb819b02f16da2b91fbf --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_erf_native.h @@ -0,0 +1,22 @@ +#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 special_erf(const at::Tensor & self); +TORCH_API at::Tensor & special_erf_out(const at::Tensor & self, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_log_softmax_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_log_softmax_native.h new file mode 100644 index 0000000000000000000000000000000000000000..87e1626cfcac6836dbec1b7c4bccc3b61724b3c8 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_log_softmax_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 special_log_softmax(const at::Tensor & self, int64_t dim, ::std::optional dtype=::std::nullopt); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/sqrt_meta_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/sqrt_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..90848bd1d220e529fce895697ba36a6dc5463b51 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/sqrt_meta_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 meta { + +TORCH_API at::Tensor sqrt(const at::Tensor & self); +TORCH_API at::Tensor & sqrt_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & sqrt_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & sqrt_(at::Tensor & self); + +} // namespace meta +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/sqrt_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/sqrt_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..7be1ba026f21fcd83b33a73e364ec3692408636b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/sqrt_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 sqrt { + 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::sqrt") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sqrt(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API sqrt_ { + using schema = 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::sqrt_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sqrt_(Tensor(a!) self) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API sqrt_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::sqrt") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sqrt.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/tensordot_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/tensordot_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..023a1dec6beb2dd53e6e66af495a7247f7fe89ae --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/tensordot_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 tensordot { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, at::IntArrayRef, at::IntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::tensordot") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "tensordot(Tensor self, Tensor other, int[] dims_self, int[] dims_other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other, at::IntArrayRef dims_self, at::IntArrayRef dims_other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::IntArrayRef dims_self, at::IntArrayRef dims_other); +}; + +struct TORCH_API tensordot_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::tensordot") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "tensordot.out(Tensor self, Tensor other, int[] dims_self, int[] dims_other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::IntArrayRef dims_self, at::IntArrayRef dims_other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::IntArrayRef dims_self, at::IntArrayRef dims_other, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/unsafe_chunk_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/unsafe_chunk_native.h new file mode 100644 index 0000000000000000000000000000000000000000..788911841b79beeb919586941d98ce0260789494 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/unsafe_chunk_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::vector unsafe_chunk(const at::Tensor & self, int64_t chunks, int64_t dim=0); +} // namespace native +} // namespace at