diff --git a/.gitattributes b/.gitattributes index 8fbc5b5985c496aeb212b7ea7f952f02b9144579..9d332d422ce5a31637be86a75acc0bcd53911894 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1926,3 +1926,8 @@ videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.cpython videollama2/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text parrot/lib/python3.10/site-packages/opencv_python.libs/libssl-28bef1ac.so.1.1 filter=lfs diff=lfs merge=lfs -text parrot/lib/python3.10/site-packages/opencv_python.libs/libgfortran-91cc3cb1.so.3.0.0 filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/linear_model/_sag_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/utils/_isfinite.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..24f8bf7e920e6ca0ca5a6ca17542369ca30ff216 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_minibatch.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02427d73dd89676ee2cc95481e05e33b647a6aafeda54130d205c4560e762d5b +size 274121 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/linear_model/_sag_fast.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/linear_model/_sag_fast.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..c2d8234ead32b6411c4c65e63c9c369f7589601f --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/linear_model/_sag_fast.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0206e05f51082e3e1af0024f8321918f56819b5df690dbc159e81b081ccd9fd +size 170705 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_base.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..dd0258f600cccce45213999a0f157aa6a497a0bf --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_base.py @@ -0,0 +1,251 @@ +""" +Common code for all metrics. + +""" +# Authors: Alexandre Gramfort +# Mathieu Blondel +# Olivier Grisel +# Arnaud Joly +# Jochen Wersdorfer +# Lars Buitinck +# Joel Nothman +# Noel Dawe +# License: BSD 3 clause + +from itertools import combinations + +import numpy as np + +from ..utils import check_array, check_consistent_length +from ..utils.multiclass import type_of_target + + +def _average_binary_score(binary_metric, y_true, y_score, average, sample_weight=None): + """Average a binary metric for multilabel classification. + + Parameters + ---------- + y_true : array, shape = [n_samples] or [n_samples, n_classes] + True binary labels in binary label indicators. + + y_score : array, shape = [n_samples] or [n_samples, n_classes] + Target scores, can either be probability estimates of the positive + class, confidence values, or binary decisions. + + average : {None, 'micro', 'macro', 'samples', 'weighted'}, default='macro' + If ``None``, the scores for each class are returned. Otherwise, + this determines the type of averaging performed on the data: + + ``'micro'``: + Calculate metrics globally by considering each element of the label + indicator matrix as a label. + ``'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). + ``'samples'``: + Calculate metrics for each instance, and find their average. + + Will be ignored when ``y_true`` is binary. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + binary_metric : callable, returns shape [n_classes] + The binary metric function to use. + + Returns + ------- + score : float or array of shape [n_classes] + If not ``None``, average the score, else return the score for each + classes. + + """ + average_options = (None, "micro", "macro", "weighted", "samples") + if average not in average_options: + raise ValueError("average has to be one of {0}".format(average_options)) + + y_type = type_of_target(y_true) + if y_type not in ("binary", "multilabel-indicator"): + raise ValueError("{0} format is not supported".format(y_type)) + + if y_type == "binary": + return binary_metric(y_true, y_score, sample_weight=sample_weight) + + check_consistent_length(y_true, y_score, sample_weight) + y_true = check_array(y_true) + y_score = check_array(y_score) + + not_average_axis = 1 + score_weight = sample_weight + average_weight = None + + if average == "micro": + if score_weight is not None: + score_weight = np.repeat(score_weight, y_true.shape[1]) + y_true = y_true.ravel() + y_score = y_score.ravel() + + elif average == "weighted": + if score_weight is not None: + average_weight = np.sum( + np.multiply(y_true, np.reshape(score_weight, (-1, 1))), axis=0 + ) + else: + average_weight = np.sum(y_true, axis=0) + if np.isclose(average_weight.sum(), 0.0): + return 0 + + elif average == "samples": + # swap average_weight <-> score_weight + average_weight = score_weight + score_weight = None + not_average_axis = 0 + + if y_true.ndim == 1: + y_true = y_true.reshape((-1, 1)) + + if y_score.ndim == 1: + y_score = y_score.reshape((-1, 1)) + + n_classes = y_score.shape[not_average_axis] + score = np.zeros((n_classes,)) + for c in range(n_classes): + y_true_c = y_true.take([c], axis=not_average_axis).ravel() + y_score_c = y_score.take([c], axis=not_average_axis).ravel() + score[c] = binary_metric(y_true_c, y_score_c, sample_weight=score_weight) + + # Average the results + if average is not None: + if average_weight is not None: + # Scores with 0 weights are forced to be 0, preventing the average + # score from being affected by 0-weighted NaN elements. + average_weight = np.asarray(average_weight) + score[average_weight == 0] = 0 + return np.average(score, weights=average_weight) + else: + return score + + +def _average_multiclass_ovo_score(binary_metric, y_true, y_score, average="macro"): + """Average one-versus-one scores for multiclass classification. + + Uses the binary metric for one-vs-one multiclass classification, + where the score is computed according to the Hand & Till (2001) algorithm. + + Parameters + ---------- + binary_metric : callable + The binary metric function to use that accepts the following as input: + y_true_target : array, shape = [n_samples_target] + Some sub-array of y_true for a pair of classes designated + positive and negative in the one-vs-one scheme. + y_score_target : array, shape = [n_samples_target] + Scores corresponding to the probability estimates + of a sample belonging to the designated positive class label + + y_true : array-like of shape (n_samples,) + True multiclass labels. + + y_score : array-like of shape (n_samples, n_classes) + Target scores corresponding to probability estimates of a sample + belonging to a particular class. + + average : {'macro', 'weighted'}, default='macro' + Determines the type of averaging performed on the pairwise binary + metric scores: + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. Classes + are assumed to be uniformly distributed. + ``'weighted'``: + Calculate metrics for each label, taking into account the + prevalence of the classes. + + Returns + ------- + score : float + Average of the pairwise binary metric scores. + """ + check_consistent_length(y_true, y_score) + + y_true_unique = np.unique(y_true) + n_classes = y_true_unique.shape[0] + n_pairs = n_classes * (n_classes - 1) // 2 + pair_scores = np.empty(n_pairs) + + is_weighted = average == "weighted" + prevalence = np.empty(n_pairs) if is_weighted else None + + # Compute scores treating a as positive class and b as negative class, + # then b as positive class and a as negative class + for ix, (a, b) in enumerate(combinations(y_true_unique, 2)): + a_mask = y_true == a + b_mask = y_true == b + ab_mask = np.logical_or(a_mask, b_mask) + + if is_weighted: + prevalence[ix] = np.average(ab_mask) + + a_true = a_mask[ab_mask] + b_true = b_mask[ab_mask] + + a_true_score = binary_metric(a_true, y_score[ab_mask, a]) + b_true_score = binary_metric(b_true, y_score[ab_mask, b]) + pair_scores[ix] = (a_true_score + b_true_score) / 2 + + return np.average(pair_scores, weights=prevalence) + + +def _check_pos_label_consistency(pos_label, y_true): + """Check if `pos_label` need to be specified or not. + + In binary classification, we fix `pos_label=1` if the labels are in the set + {-1, 1} or {0, 1}. Otherwise, we raise an error asking to specify the + `pos_label` parameters. + + Parameters + ---------- + pos_label : int, str or None + The positive label. + y_true : ndarray of shape (n_samples,) + The target vector. + + Returns + ------- + pos_label : int + If `pos_label` can be inferred, it will be returned. + + Raises + ------ + ValueError + In the case that `y_true` does not have label in {-1, 1} or {0, 1}, + it will raise a `ValueError`. + """ + # ensure binary classification if pos_label is not specified + # classes.dtype.kind in ('O', 'U', 'S') is required to avoid + # triggering a FutureWarning by calling np.array_equal(a, b) + # when elements in the two arrays are not comparable. + classes = np.unique(y_true) + if pos_label is None and ( + classes.dtype.kind in "OUS" + or not ( + np.array_equal(classes, [0, 1]) + or np.array_equal(classes, [-1, 1]) + or np.array_equal(classes, [0]) + or np.array_equal(classes, [-1]) + or np.array_equal(classes, [1]) + ) + ): + classes_repr = ", ".join(repr(c) for c in classes) + raise ValueError( + f"y_true takes value in {{{classes_repr}}} and pos_label is not " + "specified: either make y_true take value in {0, 1} or " + "{-1, 1} or pass pos_label explicitly." + ) + elif pos_label is None: + pos_label = 1 + + return pos_label diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__init__.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..133c854682f0ca03116144b9b3e6bfead4ebb545 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__init__.py @@ -0,0 +1,101 @@ +# Pairwise Distances Reductions +# ============================= +# +# Author: Julien Jerphanion +# +# Overview +# -------- +# +# This module provides routines to compute pairwise distances between a set +# of row vectors of X and another set of row vectors of Y and apply a +# reduction on top. The canonical example is the brute-force computation +# of the top k nearest neighbors by leveraging the arg-k-min reduction. +# +# The reduction takes a matrix of pairwise distances between rows of X and Y +# as input and outputs an aggregate data-structure for each row of X. The +# aggregate values are typically smaller than the number of rows in Y, hence +# the term reduction. +# +# For computational reasons, the reduction are performed on the fly on chunks +# of rows of X and Y so as to keep intermediate data-structures in CPU cache +# and avoid unnecessary round trips of large distance arrays with the RAM +# that would otherwise severely degrade the speed by making the overall +# processing memory-bound. +# +# Finally, the routines follow a generic parallelization template to process +# chunks of data with OpenMP loops (via Cython prange), either on rows of X +# or rows of Y depending on their respective sizes. +# +# +# Dispatching to specialized implementations +# ------------------------------------------ +# +# Dispatchers are meant to be used in the Python code. Under the hood, a +# dispatcher must only define the logic to choose at runtime to the correct +# dtype-specialized :class:`BaseDistancesReductionDispatcher` implementation based +# on the dtype of X and of Y. +# +# +# High-level diagram +# ------------------ +# +# Legend: +# +# A ---⊳ B: A inherits from B +# A ---x B: A dispatches to B +# +# +# (base dispatcher) +# BaseDistancesReductionDispatcher +# ∆ +# | +# | +# +-----------------------+----------------------+ +# | | +# (dispatcher) (dispatcher) +# ArgKmin RadiusNeighbors +# | | +# | | +# | (float{32,64} implem.) | +# | BaseDistancesReduction{32,64} | +# | ∆ | +# | | | +# | | | +# | +-----------------+-----------------+ | +# | | | | +# | | | | +# x | | x +# ArgKmin{32,64} RadiusNeighbors{32,64} +# | ∆ ∆ | +# | | | | +# ======================= Specializations ============================= +# | | | | +# | | | | +# x | | x +# EuclideanArgKmin{32,64} EuclideanRadiusNeighbors{32,64} +# +# For instance :class:`ArgKmin` dispatches to: +# - :class:`ArgKmin64` if X and Y are two `float64` array-likes +# - :class:`ArgKmin32` if X and Y are two `float32` array-likes +# +# In addition, if the metric parameter is set to "euclidean" or "sqeuclidean", +# then `ArgKmin{32,64}` further dispatches to `EuclideanArgKmin{32,64}`. For +# example, :class:`ArgKmin64` would dispatch to :class:`EuclideanArgKmin64`, a +# specialized subclass that optimally handles the Euclidean distance case +# using Generalized Matrix Multiplication over `float64` data (see the +# docstring of :class:`GEMMTermComputer64` for details). + + +from ._dispatcher import ( + BaseDistancesReductionDispatcher, + ArgKmin, + RadiusNeighbors, + sqeuclidean_row_norms, +) + +__all__ = [ + "BaseDistancesReductionDispatcher", + "ArgKmin", + "RadiusNeighbors", + "sqeuclidean_row_norms", +] diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..62403d1c334f0f5d4682db03e6d4df3effb8555c --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py @@ -0,0 +1,449 @@ +from abc import abstractmethod + +import numpy as np + +from typing import List + +from scipy.sparse import isspmatrix_csr + +from .._dist_metrics import BOOL_METRICS, METRIC_MAPPING + +from ._base import _sqeuclidean_row_norms32, _sqeuclidean_row_norms64 +from ._argkmin import ( + ArgKmin64, + ArgKmin32, +) +from ._radius_neighbors import ( + RadiusNeighbors64, + RadiusNeighbors32, +) + +from ... import get_config + + +def sqeuclidean_row_norms(X, num_threads): + """Compute the squared euclidean norm of the rows of X in parallel. + + Parameters + ---------- + X : ndarray or CSR matrix of shape (n_samples, n_features) + Input data. Must be c-contiguous. + + num_threads : int + The number of OpenMP threads to use. + + Returns + ------- + sqeuclidean_row_norms : ndarray of shape (n_samples,) + Arrays containing the squared euclidean norm of each row of X. + """ + if X.dtype == np.float64: + return np.asarray(_sqeuclidean_row_norms64(X, num_threads)) + if X.dtype == np.float32: + return np.asarray(_sqeuclidean_row_norms32(X, num_threads)) + + raise ValueError( + "Only float64 or float32 datasets are supported at this time, " + f"got: X.dtype={X.dtype}." + ) + + +class BaseDistancesReductionDispatcher: + """Abstract base dispatcher for pairwise distance computation & reduction. + + Each dispatcher extending the base :class:`BaseDistancesReductionDispatcher` + dispatcher must implement the :meth:`compute` classmethod. + """ + + @classmethod + def valid_metrics(cls) -> List[str]: + excluded = { + # PyFunc cannot be supported because it necessitates interacting with + # the CPython interpreter to call user defined functions. + "pyfunc", + "mahalanobis", # is numerically unstable + # In order to support discrete distance metrics, we need to have a + # stable simultaneous sort which preserves the order of the indices + # because there generally is a lot of occurrences for a given values + # of distances in this case. + # TODO: implement a stable simultaneous_sort. + "hamming", + *BOOL_METRICS, + } + return sorted(({"sqeuclidean"} | set(METRIC_MAPPING.keys())) - excluded) + + @classmethod + def is_usable_for(cls, X, Y, metric) -> bool: + """Return True if the dispatcher can be used for the + given parameters. + + 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) + Input data. + + metric : str, default='euclidean' + The distance metric to use. + For a list of available metrics, see the documentation of + :class:`~sklearn.metrics.DistanceMetric`. + + Returns + ------- + True if the dispatcher can be used, else False. + """ + + def is_numpy_c_ordered(X): + return hasattr(X, "flags") and X.flags.c_contiguous + + def is_valid_sparse_matrix(X): + return ( + isspmatrix_csr(X) + and + # TODO: support CSR matrices without non-zeros elements + X.nnz > 0 + and + # TODO: support CSR matrices with int64 indices and indptr + # See: https://github.com/scikit-learn/scikit-learn/issues/23653 + X.indices.dtype == X.indptr.dtype == np.int32 + ) + + is_usable = ( + get_config().get("enable_cython_pairwise_dist", True) + and (is_numpy_c_ordered(X) or is_valid_sparse_matrix(X)) + and (is_numpy_c_ordered(Y) or is_valid_sparse_matrix(Y)) + and X.dtype == Y.dtype + and X.dtype in (np.float32, np.float64) + and metric in cls.valid_metrics() + ) + + # The other joblib-based back-end might be more efficient on fused sparse-dense + # datasets' pairs on metric="(sq)euclidean" for some configurations because it + # uses the Squared Euclidean matrix decomposition, i.e.: + # + # ||X_c_i - Y_c_j||² = ||X_c_i||² - 2 X_c_i.Y_c_j^T + ||Y_c_j||² + # + # calling efficient sparse-dense routines for matrix and vectors multiplication + # implemented in SciPy we do not use yet here. + # See: https://github.com/scikit-learn/scikit-learn/pull/23585#issuecomment-1247996669 # noqa + # TODO: implement specialisation for (sq)euclidean on fused sparse-dense + # using sparse-dense routines for matrix-vector multiplications. + # Currently, only dense-dense and sparse-sparse are optimized for + # the Euclidean case. + fused_sparse_dense_euclidean_case_guard = not ( + (is_valid_sparse_matrix(X) ^ is_valid_sparse_matrix(Y)) # "^" is XOR + and isinstance(metric, str) + and "euclidean" in metric + ) + + return is_usable and fused_sparse_dense_euclidean_case_guard + + @classmethod + @abstractmethod + def compute( + cls, + X, + Y, + **kwargs, + ): + """Compute the reduction. + + Parameters + ---------- + X : ndarray or CSR matrix of shape (n_samples_X, n_features) + Input data. + + Y : ndarray or CSR matrix of shape (n_samples_Y, n_features) + Input data. + + **kwargs : additional parameters for the reduction + + Notes + ----- + This method is an abstract class method: it has to be implemented + for all subclasses. + """ + + +class ArgKmin(BaseDistancesReductionDispatcher): + """Compute the argkmin of row vectors of X on the ones of Y. + + For each row vector of X, computes the indices of k first the rows + vectors of Y with the smallest distances. + + ArgKmin is typically used to perform + bruteforce k-nearest neighbors queries. + + This class is not meant to be instanciated, one should only use + its :meth:`compute` classmethod which handles allocation and + deallocation consistently. + """ + + @classmethod + def compute( + cls, + X, + Y, + k, + metric="euclidean", + chunk_size=None, + metric_kwargs=None, + strategy=None, + return_distance=False, + ): + """Compute the argkmin reduction. + + Parameters + ---------- + X : ndarray or CSR matrix of shape (n_samples_X, n_features) + Input data. + + Y : ndarray or CSR matrix of shape (n_samples_Y, n_features) + Input data. + + k : int + The k for the argkmin reduction. + + metric : str, default='euclidean' + The distance metric to use for argkmin. + For a list of available metrics, see the documentation of + :class:`~sklearn.metrics.DistanceMetric`. + + chunk_size : int, default=None, + The number of vectors per chunk. If None (default) looks-up in + scikit-learn configuration for `pairwise_dist_chunk_size`, + and use 256 if it is not set. + + metric_kwargs : dict, default=None + Keyword arguments to pass to specified metric function. + + strategy : str, {'auto', 'parallel_on_X', 'parallel_on_Y'}, default=None + The chunking strategy defining which dataset parallelization are made on. + + For both strategies the computations happens with two nested loops, + respectively on chunks of X and chunks of Y. + Strategies differs on which loop (outer or inner) is made to run + in parallel with the Cython `prange` construct: + + - 'parallel_on_X' dispatches chunks of X uniformly on threads. + Each thread then iterates on all the chunks of Y. This strategy is + embarrassingly parallel and comes with no datastructures + synchronisation. + + - 'parallel_on_Y' dispatches chunks of Y uniformly on threads. + Each thread processes all the chunks of X in turn. This strategy is + a sequence of embarrassingly parallel subtasks (the inner loop on Y + chunks) with intermediate datastructures synchronisation at each + iteration of the sequential outer loop on X chunks. + + - 'auto' relies on a simple heuristic to choose between + 'parallel_on_X' and 'parallel_on_Y': when `X.shape[0]` is large enough, + 'parallel_on_X' is usually the most efficient strategy. + When `X.shape[0]` is small but `Y.shape[0]` is large, 'parallel_on_Y' + brings more opportunity for parallelism and is therefore more efficient + + - None (default) looks-up in scikit-learn configuration for + `pairwise_dist_parallel_strategy`, and use 'auto' if it is not set. + + return_distance : boolean, default=False + Return distances between each X vector and its + argkmin if set to True. + + Returns + ------- + If return_distance=False: + - argkmin_indices : ndarray of shape (n_samples_X, k) + Indices of the argkmin for each vector in X. + + If return_distance=True: + - argkmin_distances : ndarray of shape (n_samples_X, k) + Distances to the argkmin for each vector in X. + - argkmin_indices : ndarray of shape (n_samples_X, k) + Indices of the argkmin for each vector in X. + + Notes + ----- + This classmethod inspects the arguments values to dispatch to the + dtype-specialized implementation of :class:`ArgKmin`. + + This allows decoupling the API entirely from the implementation details + whilst maintaining RAII: all temporarily allocated datastructures necessary + for the concrete implementation are therefore freed when this classmethod + returns. + """ + if X.dtype == Y.dtype == np.float64: + return ArgKmin64.compute( + X=X, + Y=Y, + k=k, + metric=metric, + chunk_size=chunk_size, + metric_kwargs=metric_kwargs, + strategy=strategy, + return_distance=return_distance, + ) + + if X.dtype == Y.dtype == np.float32: + return ArgKmin32.compute( + X=X, + Y=Y, + k=k, + metric=metric, + chunk_size=chunk_size, + metric_kwargs=metric_kwargs, + strategy=strategy, + return_distance=return_distance, + ) + + raise ValueError( + "Only float64 or float32 datasets pairs are supported at this time, " + f"got: X.dtype={X.dtype} and Y.dtype={Y.dtype}." + ) + + +class RadiusNeighbors(BaseDistancesReductionDispatcher): + """Compute radius-based neighbors for two sets of vectors. + + For each row-vector X[i] of the queries X, find all the indices j of + row-vectors in Y such that: + + dist(X[i], Y[j]) <= radius + + The distance function `dist` depends on the values of the `metric` + and `metric_kwargs` parameters. + + This class is not meant to be instanciated, one should only use + its :meth:`compute` classmethod which handles allocation and + deallocation consistently. + """ + + @classmethod + def compute( + cls, + X, + Y, + radius, + metric="euclidean", + chunk_size=None, + metric_kwargs=None, + strategy=None, + return_distance=False, + sort_results=False, + ): + """Return the results of the reduction for the given arguments. + + Parameters + ---------- + X : ndarray or CSR matrix of shape (n_samples_X, n_features) + Input data. + + Y : ndarray or CSR matrix of shape (n_samples_Y, n_features) + Input data. + + radius : float + The radius defining the neighborhood. + + metric : str, default='euclidean' + The distance metric to use. + For a list of available metrics, see the documentation of + :class:`~sklearn.metrics.DistanceMetric`. + + chunk_size : int, default=None, + The number of vectors per chunk. If None (default) looks-up in + scikit-learn configuration for `pairwise_dist_chunk_size`, + and use 256 if it is not set. + + metric_kwargs : dict, default=None + Keyword arguments to pass to specified metric function. + + strategy : str, {'auto', 'parallel_on_X', 'parallel_on_Y'}, default=None + The chunking strategy defining which dataset parallelization are made on. + + For both strategies the computations happens with two nested loops, + respectively on chunks of X and chunks of Y. + Strategies differs on which loop (outer or inner) is made to run + in parallel with the Cython `prange` construct: + + - 'parallel_on_X' dispatches chunks of X uniformly on threads. + Each thread then iterates on all the chunks of Y. This strategy is + embarrassingly parallel and comes with no datastructures + synchronisation. + + - 'parallel_on_Y' dispatches chunks of Y uniformly on threads. + Each thread processes all the chunks of X in turn. This strategy is + a sequence of embarrassingly parallel subtasks (the inner loop on Y + chunks) with intermediate datastructures synchronisation at each + iteration of the sequential outer loop on X chunks. + + - 'auto' relies on a simple heuristic to choose between + 'parallel_on_X' and 'parallel_on_Y': when `X.shape[0]` is large enough, + 'parallel_on_X' is usually the most efficient strategy. + When `X.shape[0]` is small but `Y.shape[0]` is large, 'parallel_on_Y' + brings more opportunity for parallelism and is therefore more efficient + despite the synchronization step at each iteration of the outer loop + on chunks of `X`. + + - None (default) looks-up in scikit-learn configuration for + `pairwise_dist_parallel_strategy`, and use 'auto' if it is not set. + + return_distance : boolean, default=False + Return distances between each X vector and its neighbors if set to True. + + sort_results : boolean, default=False + Sort results with respect to distances between each X vector and its + neighbors if set to True. + + Returns + ------- + If return_distance=False: + - neighbors_indices : ndarray of n_samples_X ndarray + Indices of the neighbors for each vector in X. + + If return_distance=True: + - neighbors_indices : ndarray of n_samples_X ndarray + Indices of the neighbors for each vector in X. + - neighbors_distances : ndarray of n_samples_X ndarray + Distances to the neighbors for each vector in X. + + Notes + ----- + This classmethod inspects the arguments values to dispatch to the + dtype-specialized implementation of :class:`RadiusNeighbors`. + + This allows decoupling the API entirely from the implementation details + whilst maintaining RAII: all temporarily allocated datastructures necessary + for the concrete implementation are therefore freed when this classmethod + returns. + """ + if X.dtype == Y.dtype == np.float64: + return RadiusNeighbors64.compute( + X=X, + Y=Y, + radius=radius, + metric=metric, + chunk_size=chunk_size, + metric_kwargs=metric_kwargs, + strategy=strategy, + sort_results=sort_results, + return_distance=return_distance, + ) + + if X.dtype == Y.dtype == np.float32: + return RadiusNeighbors32.compute( + X=X, + Y=Y, + radius=radius, + metric=metric, + chunk_size=chunk_size, + metric_kwargs=metric_kwargs, + strategy=strategy, + sort_results=sort_results, + return_distance=return_distance, + ) + + raise ValueError( + "Only float64 or float32 datasets pairs are supported at this time, " + f"got: X.dtype={X.dtype} and Y.dtype={Y.dtype}." + ) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_ranking.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_ranking.py new file mode 100644 index 0000000000000000000000000000000000000000..9287531f18d37124c8de8deaeee2868533e6ffb4 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_ranking.py @@ -0,0 +1,1826 @@ +"""Metrics to assess performance on classification task given scores. + +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 +# Michal Karbownik +# License: BSD 3 clause + + +import warnings +from functools import partial + +import numpy as np +from scipy.sparse import csr_matrix, issparse +from scipy.stats import rankdata + +from ..utils import assert_all_finite +from ..utils import check_consistent_length +from ..utils.validation import _check_sample_weight +from ..utils import column_or_1d, check_array +from ..utils.multiclass import type_of_target +from ..utils.extmath import stable_cumsum +from ..utils.sparsefuncs import count_nonzero +from ..exceptions import UndefinedMetricWarning +from ..preprocessing import label_binarize +from ..utils._encode import _encode, _unique + +from ._base import ( + _average_binary_score, + _average_multiclass_ovo_score, + _check_pos_label_consistency, +) + + +def auc(x, y): + """Compute Area Under the Curve (AUC) using the trapezoidal rule. + + This is a general function, given points on a curve. For computing the + area under the ROC-curve, see :func:`roc_auc_score`. For an alternative + way to summarize a precision-recall curve, see + :func:`average_precision_score`. + + Parameters + ---------- + x : ndarray of shape (n,) + X coordinates. These must be either monotonic increasing or monotonic + decreasing. + y : ndarray of shape, (n,) + Y coordinates. + + Returns + ------- + auc : float + Area Under the Curve. + + See Also + -------- + roc_auc_score : Compute the area under the ROC curve. + average_precision_score : Compute average precision from prediction scores. + precision_recall_curve : Compute precision-recall pairs for different + probability thresholds. + + Examples + -------- + >>> import numpy as np + >>> from sklearn import metrics + >>> y = np.array([1, 1, 2, 2]) + >>> pred = np.array([0.1, 0.4, 0.35, 0.8]) + >>> fpr, tpr, thresholds = metrics.roc_curve(y, pred, pos_label=2) + >>> metrics.auc(fpr, tpr) + 0.75 + """ + check_consistent_length(x, y) + x = column_or_1d(x) + y = column_or_1d(y) + + if x.shape[0] < 2: + raise ValueError( + "At least 2 points are needed to compute area under curve, but x.shape = %s" + % x.shape + ) + + direction = 1 + dx = np.diff(x) + if np.any(dx < 0): + if np.all(dx <= 0): + direction = -1 + else: + raise ValueError("x is neither increasing nor decreasing : {}.".format(x)) + + area = direction * np.trapz(y, x) + if isinstance(area, np.memmap): + # Reductions such as .sum used internally in np.trapz do not return a + # scalar by default for numpy.memmap instances contrary to + # regular numpy.ndarray instances. + area = area.dtype.type(area) + return area + + +def average_precision_score( + y_true, y_score, *, average="macro", pos_label=1, sample_weight=None +): + """Compute average precision (AP) from prediction scores. + + AP summarizes a precision-recall curve as the weighted mean of precisions + achieved at each threshold, with the increase in recall from the previous + threshold used as the weight: + + .. math:: + \\text{AP} = \\sum_n (R_n - R_{n-1}) P_n + + where :math:`P_n` and :math:`R_n` are the precision and recall at the nth + threshold [1]_. This implementation is not interpolated and is different + from computing the area under the precision-recall curve with the + trapezoidal rule, which uses linear interpolation and can be too + optimistic. + + Note: this implementation is restricted to the binary classification task + or multilabel classification task. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : ndarray of shape (n_samples,) or (n_samples, n_classes) + True binary labels or binary label indicators. + + y_score : ndarray of shape (n_samples,) or (n_samples, n_classes) + Target scores, can either be probability estimates of the positive + class, confidence values, or non-thresholded measure of decisions + (as returned by :term:`decision_function` on some classifiers). + + average : {'micro', 'samples', 'weighted', 'macro'} or None, \ + default='macro' + If ``None``, the scores for each class are returned. Otherwise, + this determines the type of averaging performed on the data: + + ``'micro'``: + Calculate metrics globally by considering each element of the label + indicator matrix as a label. + ``'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). + ``'samples'``: + Calculate metrics for each instance, and find their average. + + Will be ignored when ``y_true`` is binary. + + pos_label : int or str, default=1 + The label of the positive class. Only applied to binary ``y_true``. + For multilabel-indicator ``y_true``, ``pos_label`` is fixed to 1. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + average_precision : float + Average precision score. + + See Also + -------- + roc_auc_score : Compute the area under the ROC curve. + precision_recall_curve : Compute precision-recall pairs for different + probability thresholds. + + Notes + ----- + .. versionchanged:: 0.19 + Instead of linearly interpolating between operating points, precisions + are weighted by the change in recall since the last operating point. + + References + ---------- + .. [1] `Wikipedia entry for the Average precision + `_ + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import average_precision_score + >>> y_true = np.array([0, 0, 1, 1]) + >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> average_precision_score(y_true, y_scores) + 0.83... + """ + + def _binary_uninterpolated_average_precision( + y_true, y_score, pos_label=1, sample_weight=None + ): + precision, recall, _ = precision_recall_curve( + y_true, y_score, pos_label=pos_label, sample_weight=sample_weight + ) + # Return the step function integral + # The following works because the last entry of precision is + # guaranteed to be 1, as returned by precision_recall_curve + return -np.sum(np.diff(recall) * np.array(precision)[:-1]) + + y_type = type_of_target(y_true, input_name="y_true") + if y_type == "multilabel-indicator" and pos_label != 1: + raise ValueError( + "Parameter pos_label is fixed to 1 for " + "multilabel-indicator y_true. Do not set " + "pos_label or set pos_label to 1." + ) + elif y_type == "binary": + # Convert to Python primitive type to avoid NumPy type / Python str + # comparison. See https://github.com/numpy/numpy/issues/6784 + present_labels = np.unique(y_true).tolist() + if len(present_labels) == 2 and pos_label not in present_labels: + raise ValueError( + f"pos_label={pos_label} is not a valid label. It should be " + f"one of {present_labels}" + ) + average_precision = partial( + _binary_uninterpolated_average_precision, pos_label=pos_label + ) + return _average_binary_score( + average_precision, y_true, y_score, average, sample_weight=sample_weight + ) + + +def det_curve(y_true, y_score, pos_label=None, sample_weight=None): + """Compute error rates for different probability thresholds. + + .. note:: + This metric is used for evaluation of ranking and error tradeoffs of + a binary classification task. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.24 + + Parameters + ---------- + y_true : ndarray of shape (n_samples,) + True binary labels. If labels are not either {-1, 1} or {0, 1}, then + pos_label should be explicitly given. + + y_score : ndarray of shape of (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). + + pos_label : int or str, 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. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + fpr : ndarray of shape (n_thresholds,) + False positive rate (FPR) such that element i is the false positive + rate of predictions with score >= thresholds[i]. This is occasionally + referred to as false acceptance propability or fall-out. + + fnr : ndarray of shape (n_thresholds,) + False negative rate (FNR) such that element i is the false negative + rate of predictions with score >= thresholds[i]. This is occasionally + referred to as false rejection or miss rate. + + thresholds : ndarray of shape (n_thresholds,) + Decreasing score values. + + See Also + -------- + DetCurveDisplay.from_estimator : Plot DET curve given an estimator and + some data. + DetCurveDisplay.from_predictions : Plot DET curve given the true and + predicted labels. + DetCurveDisplay : DET curve visualization. + roc_curve : Compute Receiver operating characteristic (ROC) curve. + precision_recall_curve : Compute precision-recall curve. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import det_curve + >>> y_true = np.array([0, 0, 1, 1]) + >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> fpr, fnr, thresholds = det_curve(y_true, y_scores) + >>> fpr + array([0.5, 0.5, 0. ]) + >>> fnr + array([0. , 0.5, 0.5]) + >>> thresholds + array([0.35, 0.4 , 0.8 ]) + """ + fps, tps, thresholds = _binary_clf_curve( + y_true, y_score, pos_label=pos_label, sample_weight=sample_weight + ) + + if len(np.unique(y_true)) != 2: + raise ValueError( + "Only one class present in y_true. Detection error " + "tradeoff curve is not defined in that case." + ) + + fns = tps[-1] - tps + p_count = tps[-1] + n_count = fps[-1] + + # start with false positives zero + first_ind = ( + fps.searchsorted(fps[0], side="right") - 1 + if fps.searchsorted(fps[0], side="right") > 0 + else None + ) + # stop with false negatives zero + last_ind = tps.searchsorted(tps[-1]) + 1 + sl = slice(first_ind, last_ind) + + # reverse the output such that list of false positives is decreasing + return (fps[sl][::-1] / n_count, fns[sl][::-1] / p_count, thresholds[sl][::-1]) + + +def _binary_roc_auc_score(y_true, y_score, sample_weight=None, max_fpr=None): + """Binary roc auc score.""" + if len(np.unique(y_true)) != 2: + raise ValueError( + "Only one class present in y_true. ROC AUC score " + "is not defined in that case." + ) + + fpr, tpr, _ = roc_curve(y_true, y_score, sample_weight=sample_weight) + if max_fpr is None or max_fpr == 1: + return auc(fpr, tpr) + if max_fpr <= 0 or max_fpr > 1: + raise ValueError("Expected max_fpr in range (0, 1], got: %r" % max_fpr) + + # Add a single point at max_fpr by linear interpolation + stop = np.searchsorted(fpr, max_fpr, "right") + x_interp = [fpr[stop - 1], fpr[stop]] + y_interp = [tpr[stop - 1], tpr[stop]] + tpr = np.append(tpr[:stop], np.interp(max_fpr, x_interp, y_interp)) + fpr = np.append(fpr[:stop], max_fpr) + partial_auc = auc(fpr, tpr) + + # McClish correction: standardize result to be 0.5 if non-discriminant + # and 1 if maximal + min_area = 0.5 * max_fpr**2 + max_area = max_fpr + return 0.5 * (1 + (partial_auc - min_area) / (max_area - min_area)) + + +def roc_auc_score( + y_true, + y_score, + *, + average="macro", + sample_weight=None, + max_fpr=None, + multi_class="raise", + labels=None, +): + """Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) \ + from prediction scores. + + Note: this implementation can be used with binary, multiclass and + multilabel classification, but some restrictions apply (see Parameters). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_classes) + True labels or binary label indicators. The binary and multiclass cases + expect labels with shape (n_samples,) while the multilabel case expects + binary label indicators with shape (n_samples, n_classes). + + y_score : array-like of shape (n_samples,) or (n_samples, n_classes) + Target scores. + + * In the binary case, it corresponds to an array of shape + `(n_samples,)`. Both probability estimates and non-thresholded + decision values can be provided. The probability estimates correspond + to the **probability of the class with the greater label**, + i.e. `estimator.classes_[1]` and thus + `estimator.predict_proba(X, y)[:, 1]`. The decision values + corresponds to the output of `estimator.decision_function(X, y)`. + See more information in the :ref:`User guide `; + * In the multiclass case, it corresponds to an array of shape + `(n_samples, n_classes)` of probability estimates provided by the + `predict_proba` method. The probability estimates **must** + sum to 1 across the possible classes. In addition, the order of the + class scores must correspond to the order of ``labels``, + if provided, or else to the numerical or lexicographical order of + the labels in ``y_true``. See more information in the + :ref:`User guide `; + * In the multilabel case, it corresponds to an array of shape + `(n_samples, n_classes)`. Probability estimates are provided by the + `predict_proba` method and the non-thresholded decision values by + the `decision_function` method. The probability estimates correspond + to the **probability of the class with the greater label for each + output** of the classifier. See more information in the + :ref:`User guide `. + + average : {'micro', 'macro', 'samples', 'weighted'} or None, \ + default='macro' + If ``None``, the scores for each class are returned. + Otherwise, this determines the type of averaging performed on the data. + Note: multiclass ROC AUC currently only handles the 'macro' and + 'weighted' averages. For multiclass targets, `average=None` is only + implemented for `multi_class='ovr'` and `average='micro'` is only + implemented for `multi_class='ovr'`. + + ``'micro'``: + Calculate metrics globally by considering each element of the label + indicator matrix as a label. + ``'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). + ``'samples'``: + Calculate metrics for each instance, and find their average. + + Will be ignored when ``y_true`` is binary. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + max_fpr : float > 0 and <= 1, default=None + If not ``None``, the standardized partial AUC [2]_ over the range + [0, max_fpr] is returned. For the multiclass case, ``max_fpr``, + should be either equal to ``None`` or ``1.0`` as AUC ROC partial + computation currently is not supported for multiclass. + + multi_class : {'raise', 'ovr', 'ovo'}, default='raise' + Only used for multiclass targets. Determines the type of configuration + to use. The default value raises an error, so either + ``'ovr'`` or ``'ovo'`` must be passed explicitly. + + ``'ovr'``: + Stands for One-vs-rest. Computes the AUC of each class + against the rest [3]_ [4]_. This + treats the multiclass case in the same way as the multilabel case. + Sensitive to class imbalance even when ``average == 'macro'``, + because class imbalance affects the composition of each of the + 'rest' groupings. + ``'ovo'``: + Stands for One-vs-one. Computes the average AUC of all + possible pairwise combinations of classes [5]_. + Insensitive to class imbalance when + ``average == 'macro'``. + + labels : array-like of shape (n_classes,), default=None + Only used for multiclass targets. List of labels that index the + classes in ``y_score``. If ``None``, the numerical or lexicographical + order of the labels in ``y_true`` is used. + + Returns + ------- + auc : float + Area Under the Curve score. + + See Also + -------- + average_precision_score : Area under the precision-recall curve. + 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. + + References + ---------- + .. [1] `Wikipedia entry for the Receiver operating characteristic + `_ + + .. [2] `Analyzing a portion of the ROC curve. McClish, 1989 + `_ + + .. [3] Provost, F., Domingos, P. (2000). Well-trained PETs: Improving + probability estimation trees (Section 6.2), CeDER Working Paper + #IS-00-04, Stern School of Business, New York University. + + .. [4] `Fawcett, T. (2006). An introduction to ROC analysis. Pattern + Recognition Letters, 27(8), 861-874. + `_ + + .. [5] `Hand, D.J., Till, R.J. (2001). A Simple Generalisation of the Area + Under the ROC Curve for Multiple Class Classification Problems. + Machine Learning, 45(2), 171-186. + `_ + + Examples + -------- + Binary case: + + >>> from sklearn.datasets import load_breast_cancer + >>> from sklearn.linear_model import LogisticRegression + >>> from sklearn.metrics import roc_auc_score + >>> X, y = load_breast_cancer(return_X_y=True) + >>> clf = LogisticRegression(solver="liblinear", random_state=0).fit(X, y) + >>> roc_auc_score(y, clf.predict_proba(X)[:, 1]) + 0.99... + >>> roc_auc_score(y, clf.decision_function(X)) + 0.99... + + Multiclass case: + + >>> from sklearn.datasets import load_iris + >>> X, y = load_iris(return_X_y=True) + >>> clf = LogisticRegression(solver="liblinear").fit(X, y) + >>> roc_auc_score(y, clf.predict_proba(X), multi_class='ovr') + 0.99... + + Multilabel case: + + >>> import numpy as np + >>> from sklearn.datasets import make_multilabel_classification + >>> from sklearn.multioutput import MultiOutputClassifier + >>> X, y = make_multilabel_classification(random_state=0) + >>> clf = MultiOutputClassifier(clf).fit(X, y) + >>> # get a list of n_output containing probability arrays of shape + >>> # (n_samples, n_classes) + >>> y_pred = clf.predict_proba(X) + >>> # extract the positive columns for each output + >>> y_pred = np.transpose([pred[:, 1] for pred in y_pred]) + >>> roc_auc_score(y, y_pred, average=None) + array([0.82..., 0.86..., 0.94..., 0.85... , 0.94...]) + >>> from sklearn.linear_model import RidgeClassifierCV + >>> clf = RidgeClassifierCV().fit(X, y) + >>> roc_auc_score(y, clf.decision_function(X), average=None) + array([0.81..., 0.84... , 0.93..., 0.87..., 0.94...]) + """ + + y_type = type_of_target(y_true, input_name="y_true") + y_true = check_array(y_true, ensure_2d=False, dtype=None) + y_score = check_array(y_score, ensure_2d=False) + + if y_type == "multiclass" or ( + y_type == "binary" and y_score.ndim == 2 and y_score.shape[1] > 2 + ): + # do not support partial ROC computation for multiclass + if max_fpr is not None and max_fpr != 1.0: + raise ValueError( + "Partial AUC computation not available in " + "multiclass setting, 'max_fpr' must be" + " set to `None`, received `max_fpr={0}` " + "instead".format(max_fpr) + ) + if multi_class == "raise": + raise ValueError("multi_class must be in ('ovo', 'ovr')") + return _multiclass_roc_auc_score( + y_true, y_score, labels, multi_class, average, sample_weight + ) + elif y_type == "binary": + labels = np.unique(y_true) + y_true = label_binarize(y_true, classes=labels)[:, 0] + return _average_binary_score( + partial(_binary_roc_auc_score, max_fpr=max_fpr), + y_true, + y_score, + average, + sample_weight=sample_weight, + ) + else: # multilabel-indicator + return _average_binary_score( + partial(_binary_roc_auc_score, max_fpr=max_fpr), + y_true, + y_score, + average, + sample_weight=sample_weight, + ) + + +def _multiclass_roc_auc_score( + y_true, y_score, labels, multi_class, average, sample_weight +): + """Multiclass roc auc score. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True multiclass labels. + + y_score : array-like of shape (n_samples, n_classes) + Target scores corresponding to probability estimates of a sample + belonging to a particular class + + labels : array-like of shape (n_classes,) or None + List of labels to index ``y_score`` used for multiclass. If ``None``, + the lexical order of ``y_true`` is used to index ``y_score``. + + multi_class : {'ovr', 'ovo'} + Determines the type of multiclass configuration to use. + ``'ovr'``: + Calculate metrics for the multiclass case using the one-vs-rest + approach. + ``'ovo'``: + Calculate metrics for the multiclass case using the one-vs-one + approach. + + average : {'micro', 'macro', 'weighted'} + Determines the type of averaging performed on the pairwise binary + metric scores + ``'micro'``: + Calculate metrics for the binarized-raveled classes. Only supported + for `multi_class='ovr'`. + + .. versionadded:: 1.2 + + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. Classes + are assumed to be uniformly distributed. + ``'weighted'``: + Calculate metrics for each label, taking into account the + prevalence of the classes. + + sample_weight : array-like of shape (n_samples,) or None + Sample weights. + + """ + # validation of the input y_score + if not np.allclose(1, y_score.sum(axis=1)): + raise ValueError( + "Target scores need to be probabilities for multiclass " + "roc_auc, i.e. they should sum up to 1.0 over classes" + ) + + # validation for multiclass parameter specifications + average_options = ("macro", "weighted", None) + if multi_class == "ovr": + average_options = ("micro",) + average_options + if average not in average_options: + raise ValueError( + "average must be one of {0} for multiclass problems".format(average_options) + ) + + multiclass_options = ("ovo", "ovr") + if multi_class not in multiclass_options: + raise ValueError( + "multi_class='{0}' is not supported " + "for multiclass ROC AUC, multi_class must be " + "in {1}".format(multi_class, multiclass_options) + ) + + if average is None and multi_class == "ovo": + raise NotImplementedError( + "average=None is not implemented for multi_class='ovo'." + ) + + if labels is not None: + labels = column_or_1d(labels) + classes = _unique(labels) + if len(classes) != len(labels): + raise ValueError("Parameter 'labels' must be unique") + if not np.array_equal(classes, labels): + raise ValueError("Parameter 'labels' must be ordered") + if len(classes) != y_score.shape[1]: + raise ValueError( + "Number of given labels, {0}, not equal to the number " + "of columns in 'y_score', {1}".format(len(classes), y_score.shape[1]) + ) + if len(np.setdiff1d(y_true, classes)): + raise ValueError("'y_true' contains labels not in parameter 'labels'") + else: + classes = _unique(y_true) + if len(classes) != y_score.shape[1]: + raise ValueError( + "Number of classes in y_true not equal to the number of " + "columns in 'y_score'" + ) + + if multi_class == "ovo": + if sample_weight is not None: + raise ValueError( + "sample_weight is not supported " + "for multiclass one-vs-one ROC AUC, " + "'sample_weight' must be None in this case." + ) + y_true_encoded = _encode(y_true, uniques=classes) + # Hand & Till (2001) implementation (ovo) + return _average_multiclass_ovo_score( + _binary_roc_auc_score, y_true_encoded, y_score, average=average + ) + else: + # ovr is same as multi-label + y_true_multilabel = label_binarize(y_true, classes=classes) + return _average_binary_score( + _binary_roc_auc_score, + y_true_multilabel, + y_score, + average, + sample_weight=sample_weight, + ) + + +def _binary_clf_curve(y_true, y_score, pos_label=None, sample_weight=None): + """Calculate true and false positives per binary classification threshold. + + Parameters + ---------- + y_true : ndarray of shape (n_samples,) + True targets of binary classification. + + y_score : ndarray of shape (n_samples,) + Estimated probabilities or output of a decision function. + + pos_label : int or str, default=None + The label of the positive class. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + fps : ndarray of shape (n_thresholds,) + A count of false positives, at index i being the number of negative + samples assigned a score >= thresholds[i]. The total number of + negative samples is equal to fps[-1] (thus true negatives are given by + fps[-1] - fps). + + tps : ndarray of shape (n_thresholds,) + An increasing count of true positives, at index i being the number + of positive samples assigned a score >= thresholds[i]. The total + number of positive samples is equal to tps[-1] (thus false negatives + are given by tps[-1] - tps). + + thresholds : ndarray of shape (n_thresholds,) + Decreasing score values. + """ + # Check to make sure y_true is valid + y_type = type_of_target(y_true, input_name="y_true") + if not (y_type == "binary" or (y_type == "multiclass" and pos_label is not None)): + raise ValueError("{0} format is not supported".format(y_type)) + + check_consistent_length(y_true, y_score, sample_weight) + y_true = column_or_1d(y_true) + y_score = column_or_1d(y_score) + assert_all_finite(y_true) + assert_all_finite(y_score) + + # Filter out zero-weighted samples, as they should not impact the result + if sample_weight is not None: + sample_weight = column_or_1d(sample_weight) + sample_weight = _check_sample_weight(sample_weight, y_true) + nonzero_weight_mask = sample_weight != 0 + y_true = y_true[nonzero_weight_mask] + y_score = y_score[nonzero_weight_mask] + sample_weight = sample_weight[nonzero_weight_mask] + + pos_label = _check_pos_label_consistency(pos_label, y_true) + + # make y_true a boolean vector + y_true = y_true == pos_label + + # sort scores and corresponding truth values + desc_score_indices = np.argsort(y_score, kind="mergesort")[::-1] + y_score = y_score[desc_score_indices] + y_true = y_true[desc_score_indices] + if sample_weight is not None: + weight = sample_weight[desc_score_indices] + else: + weight = 1.0 + + # y_score typically has many tied values. Here we extract + # the indices associated with the distinct values. We also + # concatenate a value for the end of the curve. + distinct_value_indices = np.where(np.diff(y_score))[0] + threshold_idxs = np.r_[distinct_value_indices, y_true.size - 1] + + # accumulate the true positives with decreasing threshold + tps = stable_cumsum(y_true * weight)[threshold_idxs] + if sample_weight is not None: + # express fps as a cumsum to ensure fps is increasing even in + # the presence of floating point errors + fps = stable_cumsum((1 - y_true) * weight)[threshold_idxs] + else: + fps = 1 + threshold_idxs - tps + return fps, tps, y_score[threshold_idxs] + + +def precision_recall_curve(y_true, probas_pred, *, pos_label=None, sample_weight=None): + """Compute precision-recall pairs for different probability thresholds. + + Note: this implementation is restricted to the binary classification task. + + 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 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 last precision and recall values are 1. and 0. respectively and do not + have a corresponding threshold. This ensures that the graph starts on the + y axis. + + The first precision and recall values are precision=class balance and recall=1.0 + which corresponds to a classifier that always predicts the positive class. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : ndarray of shape (n_samples,) + True binary labels. If labels are not either {-1, 1} or {0, 1}, then + pos_label should be explicitly given. + + probas_pred : ndarray of shape (n_samples,) + Target scores, can either be probability estimates of the positive + class, or non-thresholded measure of decisions (as returned by + `decision_function` on some classifiers). + + pos_label : int or str, 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. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + precision : ndarray of shape (n_thresholds + 1,) + Precision values such that element i is the precision of + predictions with score >= thresholds[i] and the last element is 1. + + recall : ndarray of shape (n_thresholds + 1,) + Decreasing recall values such that element i is the recall of + predictions with score >= thresholds[i] and the last element is 0. + + thresholds : ndarray of shape (n_thresholds,) + Increasing thresholds on the decision function used to compute + precision and recall where `n_thresholds = len(np.unique(probas_pred))`. + + See Also + -------- + PrecisionRecallDisplay.from_estimator : Plot Precision Recall Curve given + a binary classifier. + PrecisionRecallDisplay.from_predictions : Plot Precision Recall Curve + using predictions from a binary classifier. + average_precision_score : Compute average precision from prediction scores. + det_curve: Compute error rates for different probability thresholds. + roc_curve : Compute Receiver operating characteristic (ROC) curve. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import precision_recall_curve + >>> y_true = np.array([0, 0, 1, 1]) + >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> precision, recall, thresholds = precision_recall_curve( + ... y_true, y_scores) + >>> precision + array([0.5 , 0.66666667, 0.5 , 1. , 1. ]) + >>> recall + array([1. , 1. , 0.5, 0.5, 0. ]) + >>> thresholds + array([0.1 , 0.35, 0.4 , 0.8 ]) + """ + fps, tps, thresholds = _binary_clf_curve( + y_true, probas_pred, pos_label=pos_label, sample_weight=sample_weight + ) + + ps = tps + fps + # Initialize the result array with zeros to make sure that precision[ps == 0] + # does not contain uninitialized values. + precision = np.zeros_like(tps) + np.divide(tps, ps, out=precision, where=(ps != 0)) + + # When no positive label in y_true, recall is set to 1 for all thresholds + # tps[-1] == 0 <=> y_true == all negative labels + if tps[-1] == 0: + warnings.warn( + "No positive class found in y_true, " + "recall is set to one for all thresholds." + ) + recall = np.ones_like(tps) + else: + recall = tps / tps[-1] + + # reverse the outputs so recall is decreasing + sl = slice(None, None, -1) + return np.hstack((precision[sl], 1)), np.hstack((recall[sl], 0)), thresholds[sl] + + +def roc_curve( + y_true, y_score, *, pos_label=None, sample_weight=None, drop_intermediate=True +): + """Compute Receiver operating characteristic (ROC). + + Note: this implementation is restricted to the binary classification task. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : ndarray of shape (n_samples,) + True binary labels. If labels are not either {-1, 1} or {0, 1}, then + pos_label should be explicitly given. + + y_score : ndarray 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). + + pos_label : int or str, 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. + + 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. + + .. versionadded:: 0.17 + parameter *drop_intermediate*. + + Returns + ------- + fpr : ndarray of shape (>2,) + Increasing false positive rates such that element i is the false + positive rate of predictions with score >= `thresholds[i]`. + + tpr : ndarray of shape (>2,) + Increasing true positive rates such that element `i` is the true + positive rate of predictions with score >= `thresholds[i]`. + + thresholds : ndarray of shape = (n_thresholds,) + Decreasing thresholds on the decision function used to compute + fpr and tpr. `thresholds[0]` represents no instances being predicted + and is arbitrarily set to `max(y_score) + 1`. + + See Also + -------- + 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. + det_curve: Compute error rates for different probability thresholds. + roc_auc_score : Compute the area under the ROC curve. + + Notes + ----- + Since the thresholds are sorted from low to high values, they + are reversed upon returning them to ensure they correspond to both ``fpr`` + and ``tpr``, which are sorted in reversed order during their calculation. + + References + ---------- + .. [1] `Wikipedia entry for the Receiver operating characteristic + `_ + + .. [2] Fawcett T. An introduction to ROC analysis[J]. Pattern Recognition + Letters, 2006, 27(8):861-874. + + Examples + -------- + >>> import numpy as np + >>> from sklearn import metrics + >>> y = np.array([1, 1, 2, 2]) + >>> scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2) + >>> fpr + array([0. , 0. , 0.5, 0.5, 1. ]) + >>> tpr + array([0. , 0.5, 0.5, 1. , 1. ]) + >>> thresholds + array([1.8 , 0.8 , 0.4 , 0.35, 0.1 ]) + """ + fps, tps, thresholds = _binary_clf_curve( + y_true, y_score, pos_label=pos_label, sample_weight=sample_weight + ) + + # Attempt to drop thresholds corresponding to points in between and + # collinear with other points. These are always suboptimal and do not + # appear on a plotted ROC curve (and thus do not affect the AUC). + # Here np.diff(_, 2) is used as a "second derivative" to tell if there + # is a corner at the point. Both fps and tps must be tested to handle + # thresholds with multiple data points (which are combined in + # _binary_clf_curve). This keeps all cases where the point should be kept, + # but does not drop more complicated cases like fps = [1, 3, 7], + # tps = [1, 2, 4]; there is no harm in keeping too many thresholds. + if drop_intermediate and len(fps) > 2: + optimal_idxs = np.where( + np.r_[True, np.logical_or(np.diff(fps, 2), np.diff(tps, 2)), True] + )[0] + fps = fps[optimal_idxs] + tps = tps[optimal_idxs] + thresholds = thresholds[optimal_idxs] + + # Add an extra threshold position + # to make sure that the curve starts at (0, 0) + tps = np.r_[0, tps] + fps = np.r_[0, fps] + thresholds = np.r_[thresholds[0] + 1, thresholds] + + if fps[-1] <= 0: + warnings.warn( + "No negative samples in y_true, false positive value should be meaningless", + UndefinedMetricWarning, + ) + fpr = np.repeat(np.nan, fps.shape) + else: + fpr = fps / fps[-1] + + if tps[-1] <= 0: + warnings.warn( + "No positive samples in y_true, true positive value should be meaningless", + UndefinedMetricWarning, + ) + tpr = np.repeat(np.nan, tps.shape) + else: + tpr = tps / tps[-1] + + return fpr, tpr, thresholds + + +def label_ranking_average_precision_score(y_true, y_score, *, sample_weight=None): + """Compute ranking-based average precision. + + Label ranking average precision (LRAP) is the average over each ground + truth label assigned to each sample, of the ratio of true vs. total + labels with lower score. + + This metric is used in multilabel ranking problem, where the goal + is to give better rank to the labels associated to each sample. + + The obtained score is always strictly greater than 0 and + the best value is 1. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : {ndarray, sparse matrix} of shape (n_samples, n_labels) + True binary labels in binary indicator format. + + y_score : ndarray of shape (n_samples, n_labels) + 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. + + .. versionadded:: 0.20 + + Returns + ------- + score : float + Ranking-based average precision score. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import label_ranking_average_precision_score + >>> y_true = np.array([[1, 0, 0], [0, 0, 1]]) + >>> y_score = np.array([[0.75, 0.5, 1], [1, 0.2, 0.1]]) + >>> label_ranking_average_precision_score(y_true, y_score) + 0.416... + """ + check_consistent_length(y_true, y_score, sample_weight) + y_true = check_array(y_true, ensure_2d=False, accept_sparse="csr") + y_score = check_array(y_score, ensure_2d=False) + + if y_true.shape != y_score.shape: + raise ValueError("y_true and y_score have different shape") + + # Handle badly formatted array and the degenerate case with one label + y_type = type_of_target(y_true, input_name="y_true") + if y_type != "multilabel-indicator" and not ( + y_type == "binary" and y_true.ndim == 2 + ): + raise ValueError("{0} format is not supported".format(y_type)) + + if not issparse(y_true): + y_true = csr_matrix(y_true) + + y_score = -y_score + + n_samples, n_labels = y_true.shape + + out = 0.0 + for i, (start, stop) in enumerate(zip(y_true.indptr, y_true.indptr[1:])): + relevant = y_true.indices[start:stop] + + if relevant.size == 0 or relevant.size == n_labels: + # If all labels are relevant or unrelevant, the score is also + # equal to 1. The label ranking has no meaning. + aux = 1.0 + else: + scores_i = y_score[i] + rank = rankdata(scores_i, "max")[relevant] + L = rankdata(scores_i[relevant], "max") + aux = (L / rank).mean() + + if sample_weight is not None: + aux = aux * sample_weight[i] + out += aux + + if sample_weight is None: + out /= n_samples + else: + out /= np.sum(sample_weight) + + return out + + +def coverage_error(y_true, y_score, *, sample_weight=None): + """Coverage error measure. + + Compute how far we need to go through the ranked scores to cover all + true labels. The best value is equal to the average number + of labels in ``y_true`` per sample. + + Ties in ``y_scores`` are broken by giving maximal rank that would have + been assigned to all tied values. + + Note: Our implementation's score is 1 greater than the one given in + Tsoumakas et al., 2010. This extends it to handle the degenerate case + in which an instance has 0 true labels. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : ndarray of shape (n_samples, n_labels) + True binary labels in binary indicator format. + + y_score : ndarray of shape (n_samples, n_labels) + 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. + + Returns + ------- + coverage_error : float + The coverage error. + + References + ---------- + .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). + Mining multi-label data. In Data mining and knowledge discovery + handbook (pp. 667-685). Springer US. + """ + y_true = check_array(y_true, ensure_2d=True) + y_score = check_array(y_score, ensure_2d=True) + check_consistent_length(y_true, y_score, sample_weight) + + y_type = type_of_target(y_true, input_name="y_true") + if y_type != "multilabel-indicator": + raise ValueError("{0} format is not supported".format(y_type)) + + if y_true.shape != y_score.shape: + raise ValueError("y_true and y_score have different shape") + + y_score_mask = np.ma.masked_array(y_score, mask=np.logical_not(y_true)) + y_min_relevant = y_score_mask.min(axis=1).reshape((-1, 1)) + coverage = (y_score >= y_min_relevant).sum(axis=1) + coverage = coverage.filled(0) + + return np.average(coverage, weights=sample_weight) + + +def label_ranking_loss(y_true, y_score, *, sample_weight=None): + """Compute Ranking loss measure. + + Compute the average number of label pairs that are incorrectly ordered + given y_score weighted by the size of the label set and the number of + labels not in the label set. + + This is similar to the error set size, but weighted by the number of + relevant and irrelevant labels. The best performance is achieved with + a ranking loss of zero. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.17 + A function *label_ranking_loss* + + Parameters + ---------- + y_true : {ndarray, sparse matrix} of shape (n_samples, n_labels) + True binary labels in binary indicator format. + + y_score : ndarray of shape (n_samples, n_labels) + 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. + + Returns + ------- + loss : float + Average number of label pairs that are incorrectly ordered given + y_score weighted by the size of the label set and the number of labels not + in the label set. + + References + ---------- + .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). + Mining multi-label data. In Data mining and knowledge discovery + handbook (pp. 667-685). Springer US. + """ + y_true = check_array(y_true, ensure_2d=False, accept_sparse="csr") + y_score = check_array(y_score, ensure_2d=False) + check_consistent_length(y_true, y_score, sample_weight) + + y_type = type_of_target(y_true, input_name="y_true") + if y_type not in ("multilabel-indicator",): + raise ValueError("{0} format is not supported".format(y_type)) + + if y_true.shape != y_score.shape: + raise ValueError("y_true and y_score have different shape") + + n_samples, n_labels = y_true.shape + + y_true = csr_matrix(y_true) + + loss = np.zeros(n_samples) + for i, (start, stop) in enumerate(zip(y_true.indptr, y_true.indptr[1:])): + # Sort and bin the label scores + unique_scores, unique_inverse = np.unique(y_score[i], return_inverse=True) + true_at_reversed_rank = np.bincount( + unique_inverse[y_true.indices[start:stop]], minlength=len(unique_scores) + ) + all_at_reversed_rank = np.bincount(unique_inverse, minlength=len(unique_scores)) + false_at_reversed_rank = all_at_reversed_rank - true_at_reversed_rank + + # if the scores are ordered, it's possible to count the number of + # incorrectly ordered paires in linear time by cumulatively counting + # how many false labels of a given score have a score higher than the + # accumulated true labels with lower score. + loss[i] = np.dot(true_at_reversed_rank.cumsum(), false_at_reversed_rank) + + n_positives = count_nonzero(y_true, axis=1) + with np.errstate(divide="ignore", invalid="ignore"): + loss /= (n_labels - n_positives) * n_positives + + # When there is no positive or no negative labels, those values should + # be consider as correct, i.e. the ranking doesn't matter. + loss[np.logical_or(n_positives == 0, n_positives == n_labels)] = 0.0 + + return np.average(loss, weights=sample_weight) + + +def _dcg_sample_scores(y_true, y_score, k=None, log_base=2, ignore_ties=False): + """Compute Discounted Cumulative Gain. + + Sum the true scores ranked in the order induced by the predicted scores, + after applying a logarithmic discount. + + This ranking metric yields a high value if true labels are ranked high by + ``y_score``. + + Parameters + ---------- + y_true : ndarray of shape (n_samples, n_labels) + True targets of multilabel classification, or true scores of entities + to be ranked. + + y_score : ndarray of shape (n_samples, n_labels) + Target scores, can either be probability estimates, confidence values, + or non-thresholded measure of decisions (as returned by + "decision_function" on some classifiers). + + k : int, default=None + Only consider the highest k scores in the ranking. If `None`, use all + outputs. + + log_base : float, default=2 + Base of the logarithm used for the discount. A low value means a + sharper discount (top results are more important). + + ignore_ties : bool, default=False + Assume that there are no ties in y_score (which is likely to be the + case if y_score is continuous) for efficiency gains. + + Returns + ------- + discounted_cumulative_gain : ndarray of shape (n_samples,) + The DCG score for each sample. + + See Also + -------- + ndcg_score : The Discounted Cumulative Gain divided by the Ideal Discounted + Cumulative Gain (the DCG obtained for a perfect ranking), in order to + have a score between 0 and 1. + """ + discount = 1 / (np.log(np.arange(y_true.shape[1]) + 2) / np.log(log_base)) + if k is not None: + discount[k:] = 0 + if ignore_ties: + ranking = np.argsort(y_score)[:, ::-1] + ranked = y_true[np.arange(ranking.shape[0])[:, np.newaxis], ranking] + cumulative_gains = discount.dot(ranked.T) + else: + discount_cumsum = np.cumsum(discount) + cumulative_gains = [ + _tie_averaged_dcg(y_t, y_s, discount_cumsum) + for y_t, y_s in zip(y_true, y_score) + ] + cumulative_gains = np.asarray(cumulative_gains) + return cumulative_gains + + +def _tie_averaged_dcg(y_true, y_score, discount_cumsum): + """ + Compute DCG by averaging over possible permutations of ties. + + The gain (`y_true`) of an index falling inside a tied group (in the order + induced by `y_score`) is replaced by the average gain within this group. + The discounted gain for a tied group is then the average `y_true` within + this group times the sum of discounts of the corresponding ranks. + + This amounts to averaging scores for all possible orderings of the tied + groups. + + (note in the case of dcg@k the discount is 0 after index k) + + Parameters + ---------- + y_true : ndarray + The true relevance scores. + + y_score : ndarray + Predicted scores. + + discount_cumsum : ndarray + Precomputed cumulative sum of the discounts. + + Returns + ------- + discounted_cumulative_gain : float + The discounted cumulative gain. + + References + ---------- + McSherry, F., & Najork, M. (2008, March). Computing information retrieval + performance measures efficiently in the presence of tied scores. In + European conference on information retrieval (pp. 414-421). Springer, + Berlin, Heidelberg. + """ + _, inv, counts = np.unique(-y_score, return_inverse=True, return_counts=True) + ranked = np.zeros(len(counts)) + np.add.at(ranked, inv, y_true) + ranked /= counts + groups = np.cumsum(counts) - 1 + discount_sums = np.empty(len(counts)) + discount_sums[0] = discount_cumsum[groups[0]] + discount_sums[1:] = np.diff(discount_cumsum[groups]) + return (ranked * discount_sums).sum() + + +def _check_dcg_target_type(y_true): + y_type = type_of_target(y_true, input_name="y_true") + supported_fmt = ( + "multilabel-indicator", + "continuous-multioutput", + "multiclass-multioutput", + ) + if y_type not in supported_fmt: + raise ValueError( + "Only {} formats are supported. Got {} instead".format( + supported_fmt, y_type + ) + ) + + +def dcg_score( + y_true, y_score, *, k=None, log_base=2, sample_weight=None, ignore_ties=False +): + """Compute Discounted Cumulative Gain. + + Sum the true scores ranked in the order induced by the predicted scores, + after applying a logarithmic discount. + + This ranking metric yields a high value if true labels are ranked high by + ``y_score``. + + Usually the Normalized Discounted Cumulative Gain (NDCG, computed by + ndcg_score) is preferred. + + Parameters + ---------- + y_true : ndarray of shape (n_samples, n_labels) + True targets of multilabel classification, or true scores of entities + to be ranked. + + y_score : ndarray of shape (n_samples, n_labels) + Target scores, can either be probability estimates, confidence values, + or non-thresholded measure of decisions (as returned by + "decision_function" on some classifiers). + + k : int, default=None + Only consider the highest k scores in the ranking. If None, use all + outputs. + + log_base : float, default=2 + Base of the logarithm used for the discount. A low value means a + sharper discount (top results are more important). + + sample_weight : ndarray of shape (n_samples,), default=None + Sample weights. If `None`, all samples are given the same weight. + + ignore_ties : bool, default=False + Assume that there are no ties in y_score (which is likely to be the + case if y_score is continuous) for efficiency gains. + + Returns + ------- + discounted_cumulative_gain : float + The averaged sample DCG scores. + + See Also + -------- + ndcg_score : The Discounted Cumulative Gain divided by the Ideal Discounted + Cumulative Gain (the DCG obtained for a perfect ranking), in order to + have a score between 0 and 1. + + References + ---------- + `Wikipedia entry for Discounted Cumulative Gain + `_. + + Jarvelin, K., & Kekalainen, J. (2002). + Cumulated gain-based evaluation of IR techniques. ACM Transactions on + Information Systems (TOIS), 20(4), 422-446. + + Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May). + A theoretical analysis of NDCG ranking measures. In Proceedings of the 26th + Annual Conference on Learning Theory (COLT 2013). + + McSherry, F., & Najork, M. (2008, March). Computing information retrieval + performance measures efficiently in the presence of tied scores. In + European conference on information retrieval (pp. 414-421). Springer, + Berlin, Heidelberg. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import dcg_score + >>> # we have groud-truth relevance of some answers to a query: + >>> true_relevance = np.asarray([[10, 0, 0, 1, 5]]) + >>> # we predict scores for the answers + >>> scores = np.asarray([[.1, .2, .3, 4, 70]]) + >>> dcg_score(true_relevance, scores) + 9.49... + >>> # we can set k to truncate the sum; only top k answers contribute + >>> dcg_score(true_relevance, scores, k=2) + 5.63... + >>> # now we have some ties in our prediction + >>> scores = np.asarray([[1, 0, 0, 0, 1]]) + >>> # by default ties are averaged, so here we get the average true + >>> # relevance of our top predictions: (10 + 5) / 2 = 7.5 + >>> dcg_score(true_relevance, scores, k=1) + 7.5 + >>> # we can choose to ignore ties for faster results, but only + >>> # if we know there aren't ties in our scores, otherwise we get + >>> # wrong results: + >>> dcg_score(true_relevance, + ... scores, k=1, ignore_ties=True) + 5.0 + """ + y_true = check_array(y_true, ensure_2d=False) + y_score = check_array(y_score, ensure_2d=False) + check_consistent_length(y_true, y_score, sample_weight) + _check_dcg_target_type(y_true) + return np.average( + _dcg_sample_scores( + y_true, y_score, k=k, log_base=log_base, ignore_ties=ignore_ties + ), + weights=sample_weight, + ) + + +def _ndcg_sample_scores(y_true, y_score, k=None, ignore_ties=False): + """Compute Normalized Discounted Cumulative Gain. + + Sum the true scores ranked in the order induced by the predicted scores, + after applying a logarithmic discount. Then divide by the best possible + score (Ideal DCG, obtained for a perfect ranking) to obtain a score between + 0 and 1. + + This ranking metric yields a high value if true labels are ranked high by + ``y_score``. + + Parameters + ---------- + y_true : ndarray of shape (n_samples, n_labels) + True targets of multilabel classification, or true scores of entities + to be ranked. + + y_score : ndarray of shape (n_samples, n_labels) + Target scores, can either be probability estimates, confidence values, + or non-thresholded measure of decisions (as returned by + "decision_function" on some classifiers). + + k : int, default=None + Only consider the highest k scores in the ranking. If None, use all + outputs. + + ignore_ties : bool, default=False + Assume that there are no ties in y_score (which is likely to be the + case if y_score is continuous) for efficiency gains. + + Returns + ------- + normalized_discounted_cumulative_gain : ndarray of shape (n_samples,) + The NDCG score for each sample (float in [0., 1.]). + + See Also + -------- + dcg_score : Discounted Cumulative Gain (not normalized). + + """ + gain = _dcg_sample_scores(y_true, y_score, k, ignore_ties=ignore_ties) + # Here we use the order induced by y_true so we can ignore ties since + # the gain associated to tied indices is the same (permuting ties doesn't + # change the value of the re-ordered y_true) + normalizing_gain = _dcg_sample_scores(y_true, y_true, k, ignore_ties=True) + all_irrelevant = normalizing_gain == 0 + gain[all_irrelevant] = 0 + gain[~all_irrelevant] /= normalizing_gain[~all_irrelevant] + return gain + + +def ndcg_score(y_true, y_score, *, k=None, sample_weight=None, ignore_ties=False): + """Compute Normalized Discounted Cumulative Gain. + + Sum the true scores ranked in the order induced by the predicted scores, + after applying a logarithmic discount. Then divide by the best possible + score (Ideal DCG, obtained for a perfect ranking) to obtain a score between + 0 and 1. + + This ranking metric returns a high value if true labels are ranked high by + ``y_score``. + + Parameters + ---------- + y_true : ndarray of shape (n_samples, n_labels) + True targets of multilabel classification, or true scores of entities + to be ranked. Negative values in `y_true` may result in an output + that is not between 0 and 1. + + .. versionchanged:: 1.2 + These negative values are deprecated, and will raise an error in v1.4. + + y_score : ndarray of shape (n_samples, n_labels) + Target scores, can either be probability estimates, confidence values, + or non-thresholded measure of decisions (as returned by + "decision_function" on some classifiers). + + k : int, default=None + Only consider the highest k scores in the ranking. If `None`, use all + outputs. + + sample_weight : ndarray of shape (n_samples,), default=None + Sample weights. If `None`, all samples are given the same weight. + + ignore_ties : bool, default=False + Assume that there are no ties in y_score (which is likely to be the + case if y_score is continuous) for efficiency gains. + + Returns + ------- + normalized_discounted_cumulative_gain : float in [0., 1.] + The averaged NDCG scores for all samples. + + See Also + -------- + dcg_score : Discounted Cumulative Gain (not normalized). + + References + ---------- + `Wikipedia entry for Discounted Cumulative Gain + `_ + + Jarvelin, K., & Kekalainen, J. (2002). + Cumulated gain-based evaluation of IR techniques. ACM Transactions on + Information Systems (TOIS), 20(4), 422-446. + + Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May). + A theoretical analysis of NDCG ranking measures. In Proceedings of the 26th + Annual Conference on Learning Theory (COLT 2013) + + McSherry, F., & Najork, M. (2008, March). Computing information retrieval + performance measures efficiently in the presence of tied scores. In + European conference on information retrieval (pp. 414-421). Springer, + Berlin, Heidelberg. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import ndcg_score + >>> # we have groud-truth relevance of some answers to a query: + >>> true_relevance = np.asarray([[10, 0, 0, 1, 5]]) + >>> # we predict some scores (relevance) for the answers + >>> scores = np.asarray([[.1, .2, .3, 4, 70]]) + >>> ndcg_score(true_relevance, scores) + 0.69... + >>> scores = np.asarray([[.05, 1.1, 1., .5, .0]]) + >>> ndcg_score(true_relevance, scores) + 0.49... + >>> # we can set k to truncate the sum; only top k answers contribute. + >>> ndcg_score(true_relevance, scores, k=4) + 0.35... + >>> # the normalization takes k into account so a perfect answer + >>> # would still get 1.0 + >>> ndcg_score(true_relevance, true_relevance, k=4) + 1.0... + >>> # now we have some ties in our prediction + >>> scores = np.asarray([[1, 0, 0, 0, 1]]) + >>> # by default ties are averaged, so here we get the average (normalized) + >>> # true relevance of our top predictions: (10 / 10 + 5 / 10) / 2 = .75 + >>> ndcg_score(true_relevance, scores, k=1) + 0.75... + >>> # we can choose to ignore ties for faster results, but only + >>> # if we know there aren't ties in our scores, otherwise we get + >>> # wrong results: + >>> ndcg_score(true_relevance, + ... scores, k=1, ignore_ties=True) + 0.5... + """ + y_true = check_array(y_true, ensure_2d=False) + y_score = check_array(y_score, ensure_2d=False) + check_consistent_length(y_true, y_score, sample_weight) + + if y_true.min() < 0: + # TODO(1.4): Replace warning w/ ValueError + warnings.warn( + "ndcg_score should not be used on negative y_true values. ndcg_score will" + " raise a ValueError on negative y_true values starting from version 1.4.", + FutureWarning, + ) + _check_dcg_target_type(y_true) + gain = _ndcg_sample_scores(y_true, y_score, k=k, ignore_ties=ignore_ties) + return np.average(gain, weights=sample_weight) + + +def top_k_accuracy_score( + y_true, y_score, *, k=2, normalize=True, sample_weight=None, labels=None +): + """Top-k Accuracy classification score. + + This metric computes the number of times where the correct label is among + the top `k` labels predicted (ranked by predicted scores). Note that the + multilabel case isn't covered here. + + Read more in the :ref:`User Guide ` + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True labels. + + y_score : array-like of shape (n_samples,) or (n_samples, n_classes) + Target scores. These can be either probability estimates or + non-thresholded decision values (as returned by + :term:`decision_function` on some classifiers). + The binary case expects scores with shape (n_samples,) while the + multiclass case expects scores with shape (n_samples, n_classes). + In the multiclass case, the order of the class scores must + correspond to the order of ``labels``, if provided, or else to + the numerical or lexicographical order of the labels in ``y_true``. + If ``y_true`` does not contain all the labels, ``labels`` must be + provided. + + k : int, default=2 + Number of most likely outcomes considered to find the correct label. + + normalize : bool, default=True + If `True`, return the fraction of correctly classified samples. + Otherwise, return the number of correctly classified samples. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. If `None`, all samples are given the same weight. + + labels : array-like of shape (n_classes,), default=None + Multiclass only. List of labels that index the classes in ``y_score``. + If ``None``, the numerical or lexicographical order of the labels in + ``y_true`` is used. If ``y_true`` does not contain all the labels, + ``labels`` must be provided. + + Returns + ------- + score : float + The top-k accuracy score. The best performance is 1 with + `normalize == True` and the number of samples with + `normalize == False`. + + 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. + + Notes + ----- + In cases where two or more labels are assigned equal predicted scores, + the labels with the highest indices will be chosen first. This might + impact the result if the correct label falls after the threshold because + of that. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import top_k_accuracy_score + >>> y_true = np.array([0, 1, 2, 2]) + >>> y_score = np.array([[0.5, 0.2, 0.2], # 0 is in top 2 + ... [0.3, 0.4, 0.2], # 1 is in top 2 + ... [0.2, 0.4, 0.3], # 2 is in top 2 + ... [0.7, 0.2, 0.1]]) # 2 isn't in top 2 + >>> top_k_accuracy_score(y_true, y_score, k=2) + 0.75 + >>> # Not normalizing gives the number of "correctly" classified samples + >>> top_k_accuracy_score(y_true, y_score, k=2, normalize=False) + 3 + """ + y_true = check_array(y_true, ensure_2d=False, dtype=None) + y_true = column_or_1d(y_true) + y_type = type_of_target(y_true, input_name="y_true") + if y_type == "binary" and labels is not None and len(labels) > 2: + y_type = "multiclass" + if y_type not in {"binary", "multiclass"}: + raise ValueError( + f"y type must be 'binary' or 'multiclass', got '{y_type}' instead." + ) + y_score = check_array(y_score, ensure_2d=False) + if y_type == "binary": + if y_score.ndim == 2 and y_score.shape[1] != 1: + raise ValueError( + "`y_true` is binary while y_score is 2d with" + f" {y_score.shape[1]} classes. If `y_true` does not contain all the" + " labels, `labels` must be provided." + ) + y_score = column_or_1d(y_score) + + check_consistent_length(y_true, y_score, sample_weight) + y_score_n_classes = y_score.shape[1] if y_score.ndim == 2 else 2 + + if labels is None: + classes = _unique(y_true) + n_classes = len(classes) + + if n_classes != y_score_n_classes: + raise ValueError( + f"Number of classes in 'y_true' ({n_classes}) not equal " + f"to the number of classes in 'y_score' ({y_score_n_classes})." + "You can provide a list of all known classes by assigning it " + "to the `labels` parameter." + ) + else: + labels = column_or_1d(labels) + classes = _unique(labels) + n_labels = len(labels) + n_classes = len(classes) + + if n_classes != n_labels: + raise ValueError("Parameter 'labels' must be unique.") + + if not np.array_equal(classes, labels): + raise ValueError("Parameter 'labels' must be ordered.") + + if n_classes != y_score_n_classes: + raise ValueError( + f"Number of given labels ({n_classes}) not equal to the " + f"number of classes in 'y_score' ({y_score_n_classes})." + ) + + if len(np.setdiff1d(y_true, classes)): + raise ValueError("'y_true' contains labels not in parameter 'labels'.") + + if k >= n_classes: + warnings.warn( + f"'k' ({k}) greater than or equal to 'n_classes' ({n_classes}) " + "will result in a perfect score and is therefore meaningless.", + UndefinedMetricWarning, + ) + + y_true_encoded = _encode(y_true, uniques=classes) + + if y_type == "binary": + if k == 1: + threshold = 0.5 if y_score.min() >= 0 and y_score.max() <= 1 else 0 + y_pred = (y_score > threshold).astype(np.int64) + hits = y_pred == y_true_encoded + else: + hits = np.ones_like(y_score, dtype=np.bool_) + elif y_type == "multiclass": + sorted_pred = np.argsort(y_score, axis=1, kind="mergesort")[:, ::-1] + hits = (y_true_encoded == sorted_pred[:, :k].T).any(axis=0) + + if normalize: + return np.average(hits, weights=sample_weight) + elif sample_weight is None: + return np.sum(hits) + else: + return np.dot(hits, sample_weight) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..6e1d27b1773cd0bf1852bd8d033e2020558ce087 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f61b3136021cc79f20389c80b3c58dc74558c0604ae25ee04ebbe6bdd3db52b0 +size 241201 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_available_if.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_available_if.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac6119317ca34bf2367d000fcf836f73d1805890 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_available_if.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_encode.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_encode.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..707979dcf6754edbd78e8315a98980af08b505d5 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_encode.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_mask.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_mask.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2e989deab5ecf2c378c3715b05f7cc4488dd5a4 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_mask.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_mocking.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_mocking.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b6f1ae93e52c69ac2d45a14b85daff119fc7a08 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_mocking.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_set_output.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_set_output.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d307fcd129884d45b079a6131498123725471c1 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_set_output.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_show_versions.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_show_versions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1adc67be0a6cb81024814a5e1459973aaded8902 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_show_versions.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_tags.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_tags.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aede49c819b7db19190c56b596a929e9326315fc Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_tags.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_testing.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_testing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce3962560f407451238f7f71bd3f141f81e1c75b Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/_testing.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/deprecation.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/deprecation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29b138c5284c7505b85f3e0491af9f18281cf04d Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/deprecation.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/estimator_checks.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/estimator_checks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..845e61e377f5ab74179006b81c8f7d0f191730a3 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/estimator_checks.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/extmath.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/extmath.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d14a66a3d500dcd1d88170a14ad0764a188257d Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/extmath.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/fixes.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/fixes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abe8a5b3d8a8c63c1ec350339cf5a65e00890d1b Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/fixes.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/graph.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/graph.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..954e3fa81bb751ed97feabc721f1909ece749618 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/graph.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/multiclass.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/multiclass.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e10b8664189398ec1ae0652ef5c7f19d3a345bc Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/multiclass.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/optimize.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/optimize.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f15e2d2bcfdd9a3baecebc64e73c8cd34344aa85 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/optimize.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/stats.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/stats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f189a16ec0c0016953b5dad08250809ce75bc3ac Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/stats.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/validation.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/validation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f087f826e87fc0d6b68bab84bccc0b77091a60a0 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/__pycache__/validation.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_estimator_html_repr.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/_estimator_html_repr.py new file mode 100644 index 0000000000000000000000000000000000000000..622137d4c256a99d3dbe9dafeac0bcd249fbff48 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_estimator_html_repr.py @@ -0,0 +1,428 @@ +from contextlib import closing +from io import StringIO +from inspect import isclass +from string import Template +import html + +from .. import config_context + + +class _IDCounter: + """Generate sequential ids with a prefix.""" + + def __init__(self, prefix): + self.prefix = prefix + self.count = 0 + + def get_id(self): + self.count += 1 + return f"{self.prefix}-{self.count}" + + +_CONTAINER_ID_COUNTER = _IDCounter("sk-container-id") +_ESTIMATOR_ID_COUNTER = _IDCounter("sk-estimator-id") + + +class _VisualBlock: + """HTML Representation of Estimator + + Parameters + ---------- + kind : {'serial', 'parallel', 'single'} + kind of HTML block + + estimators : list of estimators or `_VisualBlock`s or a single estimator + If kind != 'single', then `estimators` is a list of + estimators. + If kind == 'single', then `estimators` is a single estimator. + + names : list of str, default=None + If kind != 'single', then `names` corresponds to estimators. + If kind == 'single', then `names` is a single string corresponding to + the single estimator. + + name_details : list of str, str, or None, default=None + If kind != 'single', then `name_details` corresponds to `names`. + If kind == 'single', then `name_details` is a single string + corresponding to the single estimator. + + dash_wrapped : bool, default=True + If true, wrapped HTML element will be wrapped with a dashed border. + Only active when kind != 'single'. + """ + + def __init__( + self, kind, estimators, *, names=None, name_details=None, dash_wrapped=True + ): + self.kind = kind + self.estimators = estimators + self.dash_wrapped = dash_wrapped + + if self.kind in ("parallel", "serial"): + if names is None: + names = (None,) * len(estimators) + if name_details is None: + name_details = (None,) * len(estimators) + + self.names = names + self.name_details = name_details + + def _sk_visual_block_(self): + return self + + +def _write_label_html( + out, + name, + name_details, + outer_class="sk-label-container", + inner_class="sk-label", + checked=False, +): + """Write labeled html with or without a dropdown with named details""" + out.write(f'
') + name = html.escape(name) + + if name_details is not None: + name_details = html.escape(str(name_details)) + label_class = "sk-toggleable__label sk-toggleable__label-arrow" + + checked_str = "checked" if checked else "" + est_id = _ESTIMATOR_ID_COUNTER.get_id() + out.write( + '' + f'' + f'
{name_details}'
+            "
" + ) + else: + out.write(f"") + out.write("
") # outer_class inner_class + + +def _get_visual_block(estimator): + """Generate information about how to display an estimator.""" + if hasattr(estimator, "_sk_visual_block_"): + try: + return estimator._sk_visual_block_() + except Exception: + return _VisualBlock( + "single", + estimator, + names=estimator.__class__.__name__, + name_details=str(estimator), + ) + + if isinstance(estimator, str): + return _VisualBlock( + "single", estimator, names=estimator, name_details=estimator + ) + elif estimator is None: + return _VisualBlock("single", estimator, names="None", name_details="None") + + # check if estimator looks like a meta estimator wraps estimators + if hasattr(estimator, "get_params") and not isclass(estimator): + estimators = [ + (key, est) + for key, est in estimator.get_params(deep=False).items() + if hasattr(est, "get_params") and hasattr(est, "fit") and not isclass(est) + ] + if estimators: + return _VisualBlock( + "parallel", + [est for _, est in estimators], + names=[f"{key}: {est.__class__.__name__}" for key, est in estimators], + name_details=[str(est) for _, est in estimators], + ) + + return _VisualBlock( + "single", + estimator, + names=estimator.__class__.__name__, + name_details=str(estimator), + ) + + +def _write_estimator_html( + out, estimator, estimator_label, estimator_label_details, first_call=False +): + """Write estimator to html in serial, parallel, or by itself (single).""" + if first_call: + est_block = _get_visual_block(estimator) + else: + with config_context(print_changed_only=True): + est_block = _get_visual_block(estimator) + + if est_block.kind in ("serial", "parallel"): + dashed_wrapped = first_call or est_block.dash_wrapped + dash_cls = " sk-dashed-wrapped" if dashed_wrapped else "" + out.write(f'
') + + if estimator_label: + _write_label_html(out, estimator_label, estimator_label_details) + + kind = est_block.kind + out.write(f'
') + est_infos = zip(est_block.estimators, est_block.names, est_block.name_details) + + for est, name, name_details in est_infos: + if kind == "serial": + _write_estimator_html(out, est, name, name_details) + else: # parallel + out.write('
') + # wrap element in a serial visualblock + serial_block = _VisualBlock("serial", [est], dash_wrapped=False) + _write_estimator_html(out, serial_block, name, name_details) + out.write("
") # sk-parallel-item + + out.write("
") + elif est_block.kind == "single": + _write_label_html( + out, + est_block.names, + est_block.name_details, + outer_class="sk-item", + inner_class="sk-estimator", + checked=first_call, + ) + + +_STYLE = """ +#$id { + color: black; + background-color: white; +} +#$id pre{ + padding: 0; +} +#$id div.sk-toggleable { + background-color: white; +} +#$id label.sk-toggleable__label { + cursor: pointer; + display: block; + width: 100%; + margin-bottom: 0; + padding: 0.3em; + box-sizing: border-box; + text-align: center; +} +#$id label.sk-toggleable__label-arrow:before { + content: "▸"; + float: left; + margin-right: 0.25em; + color: #696969; +} +#$id label.sk-toggleable__label-arrow:hover:before { + color: black; +} +#$id div.sk-estimator:hover label.sk-toggleable__label-arrow:before { + color: black; +} +#$id div.sk-toggleable__content { + max-height: 0; + max-width: 0; + overflow: hidden; + text-align: left; + background-color: #f0f8ff; +} +#$id div.sk-toggleable__content pre { + margin: 0.2em; + color: black; + border-radius: 0.25em; + background-color: #f0f8ff; +} +#$id input.sk-toggleable__control:checked~div.sk-toggleable__content { + max-height: 200px; + max-width: 100%; + overflow: auto; +} +#$id input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before { + content: "▾"; +} +#$id div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label { + background-color: #d4ebff; +} +#$id div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label { + background-color: #d4ebff; +} +#$id input.sk-hidden--visually { + border: 0; + clip: rect(1px 1px 1px 1px); + clip: rect(1px, 1px, 1px, 1px); + height: 1px; + margin: -1px; + overflow: hidden; + padding: 0; + position: absolute; + width: 1px; +} +#$id div.sk-estimator { + font-family: monospace; + background-color: #f0f8ff; + border: 1px dotted black; + border-radius: 0.25em; + box-sizing: border-box; + margin-bottom: 0.5em; +} +#$id div.sk-estimator:hover { + background-color: #d4ebff; +} +#$id div.sk-parallel-item::after { + content: ""; + width: 100%; + border-bottom: 1px solid gray; + flex-grow: 1; +} +#$id div.sk-label:hover label.sk-toggleable__label { + background-color: #d4ebff; +} +#$id div.sk-serial::before { + content: ""; + position: absolute; + border-left: 1px solid gray; + box-sizing: border-box; + top: 0; + bottom: 0; + left: 50%; + z-index: 0; +} +#$id div.sk-serial { + display: flex; + flex-direction: column; + align-items: center; + background-color: white; + padding-right: 0.2em; + padding-left: 0.2em; + position: relative; +} +#$id div.sk-item { + position: relative; + z-index: 1; +} +#$id div.sk-parallel { + display: flex; + align-items: stretch; + justify-content: center; + background-color: white; + position: relative; +} +#$id div.sk-item::before, #$id div.sk-parallel-item::before { + content: ""; + position: absolute; + border-left: 1px solid gray; + box-sizing: border-box; + top: 0; + bottom: 0; + left: 50%; + z-index: -1; +} +#$id div.sk-parallel-item { + display: flex; + flex-direction: column; + z-index: 1; + position: relative; + background-color: white; +} +#$id div.sk-parallel-item:first-child::after { + align-self: flex-end; + width: 50%; +} +#$id div.sk-parallel-item:last-child::after { + align-self: flex-start; + width: 50%; +} +#$id div.sk-parallel-item:only-child::after { + width: 0; +} +#$id div.sk-dashed-wrapped { + border: 1px dashed gray; + margin: 0 0.4em 0.5em 0.4em; + box-sizing: border-box; + padding-bottom: 0.4em; + background-color: white; +} +#$id div.sk-label label { + font-family: monospace; + font-weight: bold; + display: inline-block; + line-height: 1.2em; +} +#$id div.sk-label-container { + text-align: center; +} +#$id div.sk-container { + /* jupyter's `normalize.less` sets `[hidden] { display: none; }` + but bootstrap.min.css set `[hidden] { display: none !important; }` + so we also need the `!important` here to be able to override the + default hidden behavior on the sphinx rendered scikit-learn.org. + See: https://github.com/scikit-learn/scikit-learn/issues/21755 */ + display: inline-block !important; + position: relative; +} +#$id div.sk-text-repr-fallback { + display: none; +} +""".replace( + " ", "" +).replace( + "\n", "" +) # noqa + + +def estimator_html_repr(estimator): + """Build a HTML representation of an estimator. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : estimator object + The estimator to visualize. + + Returns + ------- + html: str + HTML representation of estimator. + """ + with closing(StringIO()) as out: + container_id = _CONTAINER_ID_COUNTER.get_id() + style_template = Template(_STYLE) + style_with_id = style_template.substitute(id=container_id) + estimator_str = str(estimator) + + # The fallback message is shown by default and loading the CSS sets + # div.sk-text-repr-fallback to display: none to hide the fallback message. + # + # If the notebook is trusted, the CSS is loaded which hides the fallback + # message. If the notebook is not trusted, then the CSS is not loaded and the + # fallback message is shown by default. + # + # The reverse logic applies to HTML repr div.sk-container. + # div.sk-container is hidden by default and the loading the CSS displays it. + fallback_msg = ( + "In a Jupyter environment, please rerun this cell to show the HTML" + " representation or trust the notebook.
On GitHub, the" + " HTML representation is unable to render, please try loading this page" + " with nbviewer.org." + ) + out.write( + f"" + f'
' + '
' + f"
{html.escape(estimator_str)}
{fallback_msg}" + "
" + '
") + + html_output = out.getvalue() + return html_output diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_fast_dict.pxd b/videollama2/lib/python3.10/site-packages/sklearn/utils/_fast_dict.pxd new file mode 100644 index 0000000000000000000000000000000000000000..1bcc149a54ab5d19ba5f3e08f669839296a084a7 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_fast_dict.pxd @@ -0,0 +1,22 @@ +# Author: Gael Varoquaux +# License: BSD +""" +Uses C++ map containers for fast dict-like behavior with keys being +integers, and values float. +""" + +from libcpp.map cimport map as cpp_map + +# Import the C-level symbols of numpy +cimport numpy as cnp + +ctypedef cnp.float64_t DTYPE_t + +ctypedef cnp.intp_t ITYPE_t + +############################################################################### +# An object to be used in Python + +cdef class IntFloatDict: + cdef cpp_map[ITYPE_t, DTYPE_t] my_map + cdef _to_arrays(self, ITYPE_t [:] keys, DTYPE_t [:] values) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_isfinite.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/utils/_isfinite.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..537cc0187758321b4fa3936571d1fb94825386fd --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_isfinite.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6297f649f6414e2131de7a03bcbf7cea238832bb3bd1a13bfce9469a7aa2346d +size 253625 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_random.pxd b/videollama2/lib/python3.10/site-packages/sklearn/utils/_random.pxd new file mode 100644 index 0000000000000000000000000000000000000000..9bd7b9666f490cfbb7557830244e2321bb23d65f --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_random.pxd @@ -0,0 +1,39 @@ +# Authors: Arnaud Joly +# +# License: BSD 3 clause + + +cimport numpy as cnp +ctypedef cnp.npy_uint32 UINT32_t + +cdef inline UINT32_t DEFAULT_SEED = 1 + +cdef enum: + # Max value for our rand_r replacement (near the bottom). + # We don't use RAND_MAX because it's different across platforms and + # particularly tiny on Windows/MSVC. + # It corresponds to the maximum representable value for + # 32-bit signed integers (i.e. 2^31 - 1). + RAND_R_MAX = 0x7FFFFFFF + +cpdef sample_without_replacement(cnp.int_t n_population, + cnp.int_t n_samples, + method=*, + random_state=*) + +# rand_r replacement using a 32bit XorShift generator +# See http://www.jstatsoft.org/v08/i14/paper for details +cdef inline UINT32_t our_rand_r(UINT32_t* seed) nogil: + """Generate a pseudo-random np.uint32 from a np.uint32 seed""" + # seed shouldn't ever be 0. + if (seed[0] == 0): seed[0] = DEFAULT_SEED + + seed[0] ^= (seed[0] << 13) + seed[0] ^= (seed[0] >> 17) + seed[0] ^= (seed[0] << 5) + + # Use the modulo to make sure that we don't return a values greater than the + # maximum representable value for signed 32bit integers (i.e. 2^31 - 1). + # Note that the parenthesis are needed to avoid overflow: here + # RAND_R_MAX is cast to UINT32_t before 1 is added. + return seed[0] % ((RAND_R_MAX) + 1) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.pxd b/videollama2/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.pxd new file mode 100644 index 0000000000000000000000000000000000000000..7e6054976b8cd5a489dcad631cbe7f8deb2718b3 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.pxd @@ -0,0 +1,116 @@ + +#------------------------------------------------------------------------------ + +""" +Dataset abstractions for sequential data access. +WARNING: Do not edit .pxd file directly, it is generated from .pxd.tp +""" + +cimport numpy as cnp + +# SequentialDataset and its two concrete subclasses are (optionally randomized) +# iterators over the rows of a matrix X and corresponding target values y. + + +cdef class SequentialDataset64: + cdef int current_index + cdef cnp.ndarray index + cdef int *index_data_ptr + cdef Py_ssize_t n_samples + cdef cnp.uint32_t seed + + cdef void shuffle(self, cnp.uint32_t seed) nogil + cdef int _get_next_index(self) nogil + cdef int _get_random_index(self) nogil + + cdef void _sample(self, double **x_data_ptr, int **x_ind_ptr, + int *nnz, double *y, double *sample_weight, + int current_index) nogil + cdef void next(self, double **x_data_ptr, int **x_ind_ptr, + int *nnz, double *y, double *sample_weight) nogil + cdef int random(self, double **x_data_ptr, int **x_ind_ptr, + int *nnz, double *y, double *sample_weight) nogil + + +cdef class ArrayDataset64(SequentialDataset64): + cdef cnp.ndarray X + cdef cnp.ndarray Y + cdef cnp.ndarray sample_weights + cdef Py_ssize_t n_features + cdef cnp.npy_intp X_stride + cdef double *X_data_ptr + cdef double *Y_data_ptr + cdef cnp.ndarray feature_indices + cdef int *feature_indices_ptr + cdef double *sample_weight_data + + +cdef class CSRDataset64(SequentialDataset64): + cdef cnp.ndarray X_data + cdef cnp.ndarray X_indptr + cdef cnp.ndarray X_indices + cdef cnp.ndarray Y + cdef cnp.ndarray sample_weights + cdef double *X_data_ptr + cdef int *X_indptr_ptr + cdef int *X_indices_ptr + cdef double *Y_data_ptr + cdef double *sample_weight_data + +#------------------------------------------------------------------------------ + +""" +Dataset abstractions for sequential data access. +WARNING: Do not edit .pxd file directly, it is generated from .pxd.tp +""" + +cimport numpy as cnp + +# SequentialDataset and its two concrete subclasses are (optionally randomized) +# iterators over the rows of a matrix X and corresponding target values y. + + +cdef class SequentialDataset32: + cdef int current_index + cdef cnp.ndarray index + cdef int *index_data_ptr + cdef Py_ssize_t n_samples + cdef cnp.uint32_t seed + + cdef void shuffle(self, cnp.uint32_t seed) nogil + cdef int _get_next_index(self) nogil + cdef int _get_random_index(self) nogil + + cdef void _sample(self, float **x_data_ptr, int **x_ind_ptr, + int *nnz, float *y, float *sample_weight, + int current_index) nogil + cdef void next(self, float **x_data_ptr, int **x_ind_ptr, + int *nnz, float *y, float *sample_weight) nogil + cdef int random(self, float **x_data_ptr, int **x_ind_ptr, + int *nnz, float *y, float *sample_weight) nogil + + +cdef class ArrayDataset32(SequentialDataset32): + cdef cnp.ndarray X + cdef cnp.ndarray Y + cdef cnp.ndarray sample_weights + cdef Py_ssize_t n_features + cdef cnp.npy_intp X_stride + cdef float *X_data_ptr + cdef float *Y_data_ptr + cdef cnp.ndarray feature_indices + cdef int *feature_indices_ptr + cdef float *sample_weight_data + + +cdef class CSRDataset32(SequentialDataset32): + cdef cnp.ndarray X_data + cdef cnp.ndarray X_indptr + cdef cnp.ndarray X_indices + cdef cnp.ndarray Y + cdef cnp.ndarray sample_weights + cdef float *X_data_ptr + cdef int *X_indptr_ptr + cdef int *X_indices_ptr + cdef float *Y_data_ptr + cdef float *sample_weight_data diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_sorting.pxd b/videollama2/lib/python3.10/site-packages/sklearn/utils/_sorting.pxd new file mode 100644 index 0000000000000000000000000000000000000000..412d67c479fac868c44a3b6ebfb2937b09319f9a --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_sorting.pxd @@ -0,0 +1,9 @@ +from ._typedefs cimport DTYPE_t, ITYPE_t + +from cython cimport floating + +cdef int simultaneous_sort( + floating *dist, + ITYPE_t *idx, + ITYPE_t size, +) nogil diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_typedefs.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/utils/_typedefs.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..8d54be1ba96ffe958f0b267ed8225c3cac3f4ebf Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/_typedefs.cpython-310-x86_64-linux-gnu.so differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f87cc0c6d8d99c583233a1a4abe24e24bbec32fb --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ad4d62de9cdbea5d9f4005dd26d8b9c59939b60a2f0ee27bd663a92ae288774 +size 145705 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/deprecation.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..19d41aa1eaf85e6157ee4ea36ea92b24af9865e3 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/deprecation.py @@ -0,0 +1,115 @@ +import warnings +import functools + + +__all__ = ["deprecated"] + + +class deprecated: + """Decorator to mark a function or class as deprecated. + + Issue a warning when the function is called/the class is instantiated and + adds a warning to the docstring. + + The optional extra argument will be appended to the deprecation message + and the docstring. Note: to use this with the default value for extra, put + in an empty of parentheses: + + >>> from sklearn.utils import deprecated + >>> deprecated() + + + >>> @deprecated() + ... def some_function(): pass + + Parameters + ---------- + extra : str, default='' + To be added to the deprecation messages. + """ + + # Adapted from https://wiki.python.org/moin/PythonDecoratorLibrary, + # but with many changes. + + def __init__(self, extra=""): + self.extra = extra + + def __call__(self, obj): + """Call method + + Parameters + ---------- + obj : object + """ + if isinstance(obj, type): + return self._decorate_class(obj) + elif isinstance(obj, property): + # Note that this is only triggered properly if the `property` + # decorator comes before the `deprecated` decorator, like so: + # + # @deprecated(msg) + # @property + # def deprecated_attribute_(self): + # ... + return self._decorate_property(obj) + else: + return self._decorate_fun(obj) + + def _decorate_class(self, cls): + msg = "Class %s is deprecated" % cls.__name__ + if self.extra: + msg += "; %s" % self.extra + + # FIXME: we should probably reset __new__ for full generality + init = cls.__init__ + + def wrapped(*args, **kwargs): + warnings.warn(msg, category=FutureWarning) + return init(*args, **kwargs) + + cls.__init__ = wrapped + + wrapped.__name__ = "__init__" + wrapped.deprecated_original = init + + return cls + + def _decorate_fun(self, fun): + """Decorate function fun""" + + msg = "Function %s is deprecated" % fun.__name__ + if self.extra: + msg += "; %s" % self.extra + + @functools.wraps(fun) + def wrapped(*args, **kwargs): + warnings.warn(msg, category=FutureWarning) + return fun(*args, **kwargs) + + # Add a reference to the wrapped function so that we can introspect + # on function arguments in Python 2 (already works in Python 3) + wrapped.__wrapped__ = fun + + return wrapped + + def _decorate_property(self, prop): + msg = self.extra + + @property + @functools.wraps(prop) + def wrapped(*args, **kwargs): + warnings.warn(msg, category=FutureWarning) + return prop.fget(*args, **kwargs) + + return wrapped + + +def _is_deprecated(func): + """Helper to check if func is wrapped by our deprecated decorator""" + closures = getattr(func, "__closure__", []) + if closures is None: + closures = [] + is_deprecated = "deprecated" in "".join( + [c.cell_contents for c in closures if isinstance(c.cell_contents, str)] + ) + return is_deprecated diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/fixes.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/fixes.py new file mode 100644 index 0000000000000000000000000000000000000000..37a25ff96ba00e2f3c6a36bfcce90549a005e1fb --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/fixes.py @@ -0,0 +1,216 @@ +"""Compatibility fixes for older version of python, numpy and scipy + +If you add content to this file, please give the version of the package +at which the fix is no longer needed. +""" +# Authors: Emmanuelle Gouillart +# Gael Varoquaux +# Fabian Pedregosa +# Lars Buitinck +# +# License: BSD 3 clause + +from importlib import resources +import sys + +import sklearn +import numpy as np +import scipy +import scipy.stats +import threadpoolctl + +from .deprecation import deprecated +from ..externals._packaging.version import parse as parse_version + + +np_version = parse_version(np.__version__) +sp_version = parse_version(scipy.__version__) + + +if sp_version >= parse_version("1.4"): + from scipy.sparse.linalg import lobpcg +else: + # Backport of lobpcg functionality from scipy 1.4.0, can be removed + # once support for sp_version < parse_version('1.4') is dropped + # mypy error: Name 'lobpcg' already defined (possibly by an import) + from ..externals._lobpcg import lobpcg # type: ignore # noqa + +try: + from scipy.optimize._linesearch import line_search_wolfe2, line_search_wolfe1 +except ImportError: # SciPy < 1.8 + from scipy.optimize.linesearch import line_search_wolfe2, line_search_wolfe1 # type: ignore # noqa + + +def _object_dtype_isnan(X): + return X != X + + +class loguniform(scipy.stats.reciprocal): + """A class supporting log-uniform random variables. + + Parameters + ---------- + low : float + The minimum value + high : float + The maximum value + + Methods + ------- + rvs(self, size=None, random_state=None) + Generate log-uniform random variables + + The most useful method for Scikit-learn usage is highlighted here. + For a full list, see + `scipy.stats.reciprocal + `_. + This list includes all functions of ``scipy.stats`` continuous + distributions such as ``pdf``. + + Notes + ----- + This class generates values between ``low`` and ``high`` or + + low <= loguniform(low, high).rvs() <= high + + The logarithmic probability density function (PDF) is uniform. When + ``x`` is a uniformly distributed random variable between 0 and 1, ``10**x`` + are random variables that are equally likely to be returned. + + This class is an alias to ``scipy.stats.reciprocal``, which uses the + reciprocal distribution: + https://en.wikipedia.org/wiki/Reciprocal_distribution + + Examples + -------- + + >>> from sklearn.utils.fixes import loguniform + >>> rv = loguniform(1e-3, 1e1) + >>> rvs = rv.rvs(random_state=42, size=1000) + >>> rvs.min() # doctest: +SKIP + 0.0010435856341129003 + >>> rvs.max() # doctest: +SKIP + 9.97403052786026 + """ + + +# TODO: remove when the minimum scipy version is >= 1.5 +if sp_version >= parse_version("1.5"): + from scipy.linalg import eigh as _eigh # noqa +else: + + def _eigh(*args, **kwargs): + """Wrapper for `scipy.linalg.eigh` that handles the deprecation of `eigvals`.""" + eigvals = kwargs.pop("subset_by_index", None) + return scipy.linalg.eigh(*args, eigvals=eigvals, **kwargs) + + +# Rename the `method` kwarg to `interpolation` for NumPy < 1.22, because +# `interpolation` kwarg was deprecated in favor of `method` in NumPy >= 1.22. +def _percentile(a, q, *, method="linear", **kwargs): + return np.percentile(a, q, interpolation=method, **kwargs) + + +if np_version < parse_version("1.22"): + percentile = _percentile +else: # >= 1.22 + from numpy import percentile # type: ignore # noqa + + +# compatibility fix for threadpoolctl >= 3.0.0 +# since version 3 it's possible to setup a global threadpool controller to avoid +# looping through all loaded shared libraries each time. +# the global controller is created during the first call to threadpoolctl. +def _get_threadpool_controller(): + if not hasattr(threadpoolctl, "ThreadpoolController"): + return None + + if not hasattr(sklearn, "_sklearn_threadpool_controller"): + sklearn._sklearn_threadpool_controller = threadpoolctl.ThreadpoolController() + + return sklearn._sklearn_threadpool_controller + + +def threadpool_limits(limits=None, user_api=None): + controller = _get_threadpool_controller() + if controller is not None: + return controller.limit(limits=limits, user_api=user_api) + else: + return threadpoolctl.threadpool_limits(limits=limits, user_api=user_api) + + +threadpool_limits.__doc__ = threadpoolctl.threadpool_limits.__doc__ + + +def threadpool_info(): + controller = _get_threadpool_controller() + if controller is not None: + return controller.info() + else: + return threadpoolctl.threadpool_info() + + +threadpool_info.__doc__ = threadpoolctl.threadpool_info.__doc__ + + +@deprecated( + "The function `delayed` has been moved from `sklearn.utils.fixes` to " + "`sklearn.utils.parallel`. This import path will be removed in 1.5." +) +def delayed(function): + from sklearn.utils.parallel import delayed + + return delayed(function) + + +# TODO: Remove when SciPy 1.11 is the minimum supported version +def _mode(a, axis=0): + if sp_version >= parse_version("1.9.0"): + mode = scipy.stats.mode(a, axis=axis, keepdims=True) + if sp_version >= parse_version("1.10.999"): + # scipy.stats.mode has changed returned array shape with axis=None + # and keepdims=True, see https://github.com/scipy/scipy/pull/17561 + if axis is None: + mode = np.ravel(mode) + return mode + return scipy.stats.mode(a, axis=axis) + + +############################################################################### +# Backport of Python 3.9's importlib.resources +# TODO: Remove when Python 3.9 is the minimum supported version + + +def _open_text(data_module, data_file_name): + if sys.version_info >= (3, 9): + return resources.files(data_module).joinpath(data_file_name).open("r") + else: + return resources.open_text(data_module, data_file_name) + + +def _open_binary(data_module, data_file_name): + if sys.version_info >= (3, 9): + return resources.files(data_module).joinpath(data_file_name).open("rb") + else: + return resources.open_binary(data_module, data_file_name) + + +def _read_text(descr_module, descr_file_name): + if sys.version_info >= (3, 9): + return resources.files(descr_module).joinpath(descr_file_name).read_text() + else: + return resources.read_text(descr_module, descr_file_name) + + +def _path(data_module, data_file_name): + if sys.version_info >= (3, 9): + return resources.as_file(resources.files(data_module).joinpath(data_file_name)) + else: + return resources.path(data_module, data_file_name) + + +def _is_resource(data_module, data_file_name): + if sys.version_info >= (3, 9): + return resources.files(data_module).joinpath(data_file_name).is_file() + else: + return resources.is_resource(data_module, data_file_name) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..348f896a090fffb6a392a11132d56e9b390facad Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/conftest.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/conftest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..761a68cbe5a7b47f8607b06dca942e3dec5b6265 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/conftest.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_array_api.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_array_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddab4551feefcfc5aea7858ab44d259ca7012057 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_array_api.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_arrayfuncs.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_arrayfuncs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78f342ef793ff3fc68fca4558c499e976fe441b4 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_arrayfuncs.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_class_weight.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_class_weight.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70fae79c702832e1731bbb167228ef15592c1490 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_class_weight.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_blas.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_blas.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd639dbdd27f0d81c8ff6f3b5a36677402af75ff Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_blas.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_templating.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_templating.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a676253b3c3cc851ab2ceeeec6ccfd5acfb38568 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_cython_templating.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_deprecation.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_deprecation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d49aa83ee4976047e2c1adb609a7a3b77a0773f4 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_deprecation.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_encode.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_encode.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30490c22a0c54cc0a6d6c08bc6f8e5fa299a0b13 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_encode.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..597ebb27d7dae0dab49cdbbb85d0420beb02ba47 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_checks.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_html_repr.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_html_repr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e214527715b046e6002dd9cb343edb3e21fd1aca Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_estimator_html_repr.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_fast_dict.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_fast_dict.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c0e020ed17cbd5f058106cdd4ebae53e74c6ab3 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_fast_dict.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_mocking.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_mocking.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d38d97d14337ebea046ae28d9faff175ac5878df Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_mocking.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_murmurhash.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_murmurhash.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..208c1d04953de0877bdba0589d2d39998ee55d3c Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_murmurhash.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75a5161e374da4df8370930cd684e0c13fe2d2f7 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_optimize.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_param_validation.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_param_validation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e50b79a57e37765555abe837f8c2c762783fff4c Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_param_validation.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_random.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_random.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e75c88844c21758ddcb975772a890d26a6ca8441 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_random.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_readonly_wrapper.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_readonly_wrapper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d670230f4ecbc4085e996c2762c378732ff503c Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_readonly_wrapper.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_seq_dataset.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_seq_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a03d987e53e9fe8102aad80f32dd4ff168660037 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_seq_dataset.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_set_output.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_set_output.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e796a31c1f0e2b6d9ae9056bf2dac8f61b106e6f Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_set_output.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_shortest_path.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_shortest_path.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bddb94cf959ee06caa9929e5b56fed3b0abcdd03 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_shortest_path.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_show_versions.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_show_versions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6d99aab70bc326b07cf96337cf00c17ce9c5a65 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_show_versions.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_sparsefuncs.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_sparsefuncs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d17cf784598fec4524eb64de199d6931507923a0 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_sparsefuncs.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_tags.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_tags.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26c7b4787a270b47e264fe6f3525f3137c41ac6f Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_tags.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_testing.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_testing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5a812c30eb73dab22d74de59fcc40bbd2ac4618 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_testing.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_validation.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_validation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23bfd54d3bd1c3090f305052c4462f1369adce28 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_validation.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_weight_vector.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_weight_vector.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..690585d26d1301b9f2ffe765651c1dbb4f294bd9 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__pycache__/test_weight_vector.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_mocking.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_mocking.py new file mode 100644 index 0000000000000000000000000000000000000000..a12c41256581a895e2ffd14cfb1cfa3e097dae9e --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_mocking.py @@ -0,0 +1,183 @@ +import numpy as np +import pytest +from scipy import sparse + +from numpy.testing import assert_array_equal +from numpy.testing import assert_allclose + +from sklearn.datasets import load_iris +from sklearn.utils import check_array +from sklearn.utils import _safe_indexing +from sklearn.utils._testing import _convert_container + +from sklearn.utils._mocking import CheckingClassifier + + +@pytest.fixture +def iris(): + return load_iris(return_X_y=True) + + +def _success(x): + return True + + +def _fail(x): + return False + + +@pytest.mark.parametrize( + "kwargs", + [ + {}, + {"check_X": _success}, + {"check_y": _success}, + {"check_X": _success, "check_y": _success}, + ], +) +def test_check_on_fit_success(iris, kwargs): + X, y = iris + CheckingClassifier(**kwargs).fit(X, y) + + +@pytest.mark.parametrize( + "kwargs", + [ + {"check_X": _fail}, + {"check_y": _fail}, + {"check_X": _success, "check_y": _fail}, + {"check_X": _fail, "check_y": _success}, + {"check_X": _fail, "check_y": _fail}, + ], +) +def test_check_on_fit_fail(iris, kwargs): + X, y = iris + clf = CheckingClassifier(**kwargs) + with pytest.raises(AssertionError): + clf.fit(X, y) + + +@pytest.mark.parametrize( + "pred_func", ["predict", "predict_proba", "decision_function", "score"] +) +def test_check_X_on_predict_success(iris, pred_func): + X, y = iris + clf = CheckingClassifier(check_X=_success).fit(X, y) + getattr(clf, pred_func)(X) + + +@pytest.mark.parametrize( + "pred_func", ["predict", "predict_proba", "decision_function", "score"] +) +def test_check_X_on_predict_fail(iris, pred_func): + X, y = iris + clf = CheckingClassifier(check_X=_success).fit(X, y) + clf.set_params(check_X=_fail) + with pytest.raises(AssertionError): + getattr(clf, pred_func)(X) + + +@pytest.mark.parametrize("input_type", ["list", "array", "sparse", "dataframe"]) +def test_checking_classifier(iris, input_type): + # Check that the CheckingClassifier outputs what we expect + X, y = iris + X = _convert_container(X, input_type) + clf = CheckingClassifier() + clf.fit(X, y) + + assert_array_equal(clf.classes_, np.unique(y)) + assert len(clf.classes_) == 3 + assert clf.n_features_in_ == 4 + + y_pred = clf.predict(X) + assert_array_equal(y_pred, np.zeros(y_pred.size, dtype=int)) + + assert clf.score(X) == pytest.approx(0) + clf.set_params(foo_param=10) + assert clf.fit(X, y).score(X) == pytest.approx(1) + + y_proba = clf.predict_proba(X) + assert y_proba.shape == (150, 3) + assert_allclose(y_proba[:, 0], 1) + assert_allclose(y_proba[:, 1:], 0) + + y_decision = clf.decision_function(X) + assert y_decision.shape == (150, 3) + assert_allclose(y_decision[:, 0], 1) + assert_allclose(y_decision[:, 1:], 0) + + # check the shape in case of binary classification + first_2_classes = np.logical_or(y == 0, y == 1) + X = _safe_indexing(X, first_2_classes) + y = _safe_indexing(y, first_2_classes) + clf.fit(X, y) + + y_proba = clf.predict_proba(X) + assert y_proba.shape == (100, 2) + assert_allclose(y_proba[:, 0], 1) + assert_allclose(y_proba[:, 1], 0) + + y_decision = clf.decision_function(X) + assert y_decision.shape == (100,) + assert_allclose(y_decision, 0) + + +def test_checking_classifier_with_params(iris): + X, y = iris + X_sparse = sparse.csr_matrix(X) + + clf = CheckingClassifier(check_X=sparse.issparse) + with pytest.raises(AssertionError): + clf.fit(X, y) + clf.fit(X_sparse, y) + + clf = CheckingClassifier( + check_X=check_array, check_X_params={"accept_sparse": False} + ) + clf.fit(X, y) + with pytest.raises(TypeError, match="A sparse matrix was passed"): + clf.fit(X_sparse, y) + + +def test_checking_classifier_fit_params(iris): + # check the error raised when the number of samples is not the one expected + X, y = iris + clf = CheckingClassifier(expected_sample_weight=True) + sample_weight = np.ones(len(X) // 2) + + msg = f"sample_weight.shape == ({len(X) // 2},), expected ({len(X)},)!" + with pytest.raises(ValueError) as exc: + clf.fit(X, y, sample_weight=sample_weight) + assert exc.value.args[0] == msg + + +def test_checking_classifier_missing_fit_params(iris): + X, y = iris + clf = CheckingClassifier(expected_sample_weight=True) + err_msg = "Expected sample_weight to be passed" + with pytest.raises(AssertionError, match=err_msg): + clf.fit(X, y) + + +@pytest.mark.parametrize( + "methods_to_check", + [["predict"], ["predict", "predict_proba"]], +) +@pytest.mark.parametrize( + "predict_method", ["predict", "predict_proba", "decision_function", "score"] +) +def test_checking_classifier_methods_to_check(iris, methods_to_check, predict_method): + # check that methods_to_check allows to bypass checks + X, y = iris + + clf = CheckingClassifier( + check_X=sparse.issparse, + methods_to_check=methods_to_check, + ) + + clf.fit(X, y) + if predict_method in methods_to_check: + with pytest.raises(AssertionError): + getattr(clf, predict_method)(X) + else: + getattr(clf, predict_method)(X) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_show_versions.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_show_versions.py new file mode 100644 index 0000000000000000000000000000000000000000..e6590bfde15f54677767f63318526a421e388fb7 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_show_versions.py @@ -0,0 +1,41 @@ +from sklearn.utils.fixes import threadpool_info +from sklearn.utils._show_versions import _get_sys_info +from sklearn.utils._show_versions import _get_deps_info +from sklearn.utils._show_versions import show_versions +from sklearn.utils._testing import ignore_warnings + + +def test_get_sys_info(): + sys_info = _get_sys_info() + + assert "python" in sys_info + assert "executable" in sys_info + assert "machine" in sys_info + + +def test_get_deps_info(): + with ignore_warnings(): + deps_info = _get_deps_info() + + assert "pip" in deps_info + assert "setuptools" in deps_info + assert "sklearn" in deps_info + assert "numpy" in deps_info + assert "scipy" in deps_info + assert "Cython" in deps_info + assert "pandas" in deps_info + assert "matplotlib" in deps_info + assert "joblib" in deps_info + + +def test_show_versions(capsys): + with ignore_warnings(): + show_versions() + out, err = capsys.readouterr() + + assert "python" in out + assert "numpy" in out + + info = threadpool_info() + if info: + assert "threadpoolctl info:" in out diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_stats.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..fdf679b99b7f296b6037fbc262bfddd49cd03c89 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_stats.py @@ -0,0 +1,98 @@ +import numpy as np +from numpy.testing import assert_allclose +from pytest import approx + +from sklearn.utils.stats import _weighted_percentile + + +def test_weighted_percentile(): + y = np.empty(102, dtype=np.float64) + y[:50] = 0 + y[-51:] = 2 + y[-1] = 100000 + y[50] = 1 + sw = np.ones(102, dtype=np.float64) + sw[-1] = 0.0 + score = _weighted_percentile(y, sw, 50) + assert approx(score) == 1 + + +def test_weighted_percentile_equal(): + y = np.empty(102, dtype=np.float64) + y.fill(0.0) + sw = np.ones(102, dtype=np.float64) + sw[-1] = 0.0 + score = _weighted_percentile(y, sw, 50) + assert score == 0 + + +def test_weighted_percentile_zero_weight(): + y = np.empty(102, dtype=np.float64) + y.fill(1.0) + sw = np.ones(102, dtype=np.float64) + sw.fill(0.0) + score = _weighted_percentile(y, sw, 50) + assert approx(score) == 1.0 + + +def test_weighted_percentile_zero_weight_zero_percentile(): + y = np.array([0, 1, 2, 3, 4, 5]) + sw = np.array([0, 0, 1, 1, 1, 0]) + score = _weighted_percentile(y, sw, 0) + assert approx(score) == 2 + + score = _weighted_percentile(y, sw, 50) + assert approx(score) == 3 + + score = _weighted_percentile(y, sw, 100) + assert approx(score) == 4 + + +def test_weighted_median_equal_weights(): + # Checks weighted percentile=0.5 is same as median when weights equal + rng = np.random.RandomState(0) + # Odd size as _weighted_percentile takes lower weighted percentile + x = rng.randint(10, size=11) + weights = np.ones(x.shape) + + median = np.median(x) + w_median = _weighted_percentile(x, weights) + assert median == approx(w_median) + + +def test_weighted_median_integer_weights(): + # Checks weighted percentile=0.5 is same as median when manually weight + # data + rng = np.random.RandomState(0) + x = rng.randint(20, size=10) + weights = rng.choice(5, size=10) + x_manual = np.repeat(x, weights) + + median = np.median(x_manual) + w_median = _weighted_percentile(x, weights) + + assert median == approx(w_median) + + +def test_weighted_percentile_2d(): + # Check for when array 2D and sample_weight 1D + rng = np.random.RandomState(0) + x1 = rng.randint(10, size=10) + w1 = rng.choice(5, size=10) + + x2 = rng.randint(20, size=10) + x_2d = np.vstack((x1, x2)).T + + w_median = _weighted_percentile(x_2d, w1) + p_axis_0 = [_weighted_percentile(x_2d[:, i], w1) for i in range(x_2d.shape[1])] + assert_allclose(w_median, p_axis_0) + + # Check when array and sample_weight boht 2D + w2 = rng.choice(5, size=10) + w_2d = np.vstack((w1, w2)).T + + w_median = _weighted_percentile(x_2d, w_2d) + p_axis_0 = [ + _weighted_percentile(x_2d[:, i], w_2d[:, i]) for i in range(x_2d.shape[1]) + ] + assert_allclose(w_median, p_axis_0) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_weight_vector.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_weight_vector.py new file mode 100644 index 0000000000000000000000000000000000000000..627d46d1fda067ca1803fd041a646d244eae3275 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_weight_vector.py @@ -0,0 +1,24 @@ +import numpy as np +import pytest +from sklearn.utils._weight_vector import ( + WeightVector32, + WeightVector64, +) + + +@pytest.mark.parametrize( + "dtype, WeightVector", + [ + (np.float32, WeightVector32), + (np.float64, WeightVector64), + ], +) +def test_type_invariance(dtype, WeightVector): + """Check the `dtype` consistency of `WeightVector`.""" + weights = np.random.rand(100).astype(dtype) + average_weights = np.random.rand(100).astype(dtype) + + weight_vector = WeightVector(weights, average_weights) + + assert np.asarray(weight_vector.w).dtype is np.dtype(dtype) + assert np.asarray(weight_vector.aw).dtype is np.dtype(dtype) diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_masked_scale_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_masked_scale_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..278750621cc24b58b9c7fe9cebb0e84e16d5f086 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_masked_scale_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 _masked_scale { + 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::_masked_scale") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_masked_scale(Tensor self, Tensor mask, float scale) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & mask, double scale); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mask, double scale); +}; + +struct TORCH_API _masked_scale_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::_masked_scale") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_masked_scale.out(Tensor self, Tensor mask, float scale, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & mask, double scale, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, 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/_scaled_dot_product_cudnn_attention_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_cudnn_attention_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..0c4f59a5c39125b7832c94f078e16ee471356511 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_cudnn_attention_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 _scaled_dot_product_cudnn_attention(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const ::std::optional & attn_bias, bool compute_log_sumexp, double dropout_p=0.0, bool is_causal=false, bool return_debug_mask=false, ::std::optional scale=::std::nullopt); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_csc_tensor_unsafe.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_csc_tensor_unsafe.h new file mode 100644 index 0000000000000000000000000000000000000000..2db395d6c288cfa74145380176a93470171f2c46 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_csc_tensor_unsafe.h @@ -0,0 +1,34 @@ +#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::_sparse_csc_tensor_unsafe(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor _sparse_csc_tensor_unsafe(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, at::TensorOptions options={}) { + return at::_ops::_sparse_csc_tensor_unsafe::call(ccol_indices, row_indices, values, size, c10::optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::_sparse_csc_tensor_unsafe(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor _sparse_csc_tensor_unsafe(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory) { + return at::_ops::_sparse_csc_tensor_unsafe::call(ccol_indices, row_indices, values, size, dtype, layout, device, pin_memory); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_copy_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_copy_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..bebeeb126d48388d8ebf694aeea74cc0f2d33f66 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_copy_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 & _test_autograd_multiple_dispatch_view_copy_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & _test_autograd_multiple_dispatch_view_copy_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell_backward.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..53fcd8583001c66b7a62685bdb9bab763f80d021 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_lstm_cell_backward.h @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_thnn_fused_lstm_cell_backward(Tensor? grad_hy, Tensor? grad_cy, Tensor cx, Tensor cy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor) +inline ::std::tuple _thnn_fused_lstm_cell_backward(const ::std::optional & grad_hy, const ::std::optional & grad_cy, const at::Tensor & cx, const at::Tensor & cy, const at::Tensor & workspace, bool has_bias) { + return at::_ops::_thnn_fused_lstm_cell_backward::call(grad_hy, grad_cy, cx, cy, workspace, has_bias); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_to_sparse_csr_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_to_sparse_csr_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..0b311424a26d4916bb63d7b6608ccde3c009e986 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_to_sparse_csr_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 _to_sparse_csr { + using schema = at::Tensor (const at::Tensor &, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_to_sparse_csr") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_to_sparse_csr(Tensor self, int? dense_dim=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, ::std::optional dense_dim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, ::std::optional dense_dim); +}; + +struct TORCH_API _to_sparse_csr_out { + using schema = at::Tensor & (const at::Tensor &, ::std::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_to_sparse_csr") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_to_sparse_csr.out(Tensor self, int? dense_dim=None, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, ::std::optional dense_dim, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, ::std::optional dense_dim, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy.h new file mode 100644 index 0000000000000000000000000000000000000000..8c405caaf5327d9f3b97be71dd80c2895a7c3302 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/binary_cross_entropy.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::binary_cross_entropy(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor +inline at::Tensor binary_cross_entropy(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, int64_t reduction=at::Reduction::Mean) { + return at::_ops::binary_cross_entropy::call(self, target, weight, reduction); +} + +// aten::binary_cross_entropy.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & binary_cross_entropy_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight={}, int64_t reduction=at::Reduction::Mean) { + return at::_ops::binary_cross_entropy_out::call(self, target, weight, reduction, out); +} +// aten::binary_cross_entropy.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & binary_cross_entropy_outf(const at::Tensor & self, const at::Tensor & target, const ::std::optional & weight, int64_t reduction, at::Tensor & out) { + return at::_ops::binary_cross_entropy_out::call(self, target, weight, reduction, out); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/conv_transpose1d_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/conv_transpose1d_native.h new file mode 100644 index 0000000000000000000000000000000000000000..36bfcff07bcae65c775f02b0f68ac9280fe75458 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/conv_transpose1d_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 conv_transpose1d_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 native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fractional_max_pool2d_backward_meta_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fractional_max_pool2d_backward_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..64561c87b0da88a0458f9b0a07963a82b9da4b23 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fractional_max_pool2d_backward_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 fractional_max_pool2d_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices); +TORCH_API at::Tensor & fractional_max_pool2d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices); +TORCH_API at::Tensor & fractional_max_pool2d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices, at::Tensor & grad_input); + +} // namespace meta +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fractional_max_pool3d_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fractional_max_pool3d_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..7ea591768bd37f66e5918f6dd021d352a5cd2941 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fractional_max_pool3d_cuda_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API ::std::tuple fractional_max_pool3d(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & random_samples); +TORCH_API ::std::tuple fractional_max_pool3d_out(at::Tensor & output, at::Tensor & indices, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & random_samples); +TORCH_API ::std::tuple fractional_max_pool3d_outf(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & random_samples, at::Tensor & output, at::Tensor & indices); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/index_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/index_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..ad9463bcb16ca692a8ade7bb56afe428b86b6e1d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/index_meta.h @@ -0,0 +1,50 @@ +#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_index_Tensor : public TensorIteratorBase { + + template + struct TORCH_API precompute_out { + + precompute_out set_sizes(at::DimVector value) { + static_assert(SIZES == false, "sizes already set"); + precompute_out ret; +ret.sizes = value; +ret.strides = this->strides; +return ret; + } + + + precompute_out set_strides(at::DimVector value) { + static_assert(STRIDES == false, "strides already set"); + precompute_out ret; +ret.sizes = this->sizes; +ret.strides = value; +return ret; + } + + at::DimVector sizes; +at::DimVector strides; + }; + using meta_return_ty = precompute_out ; + meta_return_ty meta(const at::Tensor & self, at::IOptTensorListRef indices); +}; + +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_pinned_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_pinned_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..fb0152474ec8c70f7e5e5d21980ec6f84b71172c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_pinned_compositeexplicitautograd_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 compositeexplicitautograd { + +TORCH_API bool is_pinned(const at::Tensor & self, ::std::optional device=::std::nullopt); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/ne_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/ne_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..e34c5ef359ee4eef7061344b5d6f1206cfb0de19 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/ne_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 ne_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::ne") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ne.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 ne_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::ne") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ne.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 ne_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::ne") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ne.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 ne_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::ne") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ne.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 ne__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::ne_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ne_.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 ne__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::ne_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ne_.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/normal_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/normal_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9926cf0ce46ca092930b1567503bd4f43e61bb1a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/normal_compositeexplicitautograd_dispatch.h @@ -0,0 +1,33 @@ +#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 normal_functional(const at::Tensor & self, double mean=0, double std=1, ::std::optional generator=::std::nullopt); +TORCH_API at::Tensor & normal_out(at::Tensor & out, const at::Tensor & self, double mean=0, double std=1, ::std::optional generator=::std::nullopt); +TORCH_API at::Tensor & normal_outf(const at::Tensor & self, double mean, double std, ::std::optional generator, at::Tensor & out); +TORCH_API at::Tensor normal(double mean, double std, at::IntArrayRef size, ::std::optional generator=::std::nullopt, at::TensorOptions options={}); +TORCH_API at::Tensor normal(double mean, double std, at::IntArrayRef size, ::std::optional generator, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); +TORCH_API at::Tensor normal_symint(double mean, double std, c10::SymIntArrayRef size, ::std::optional generator=::std::nullopt, at::TensorOptions options={}); +TORCH_API at::Tensor normal_symint(double mean, double std, c10::SymIntArrayRef size, ::std::optional generator, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory); +TORCH_API at::Tensor & normal_out(at::Tensor & out, double mean, double std, at::IntArrayRef size, ::std::optional generator=::std::nullopt); +TORCH_API at::Tensor & normal_outf(double mean, double std, at::IntArrayRef size, ::std::optional generator, at::Tensor & out); +TORCH_API at::Tensor & normal_symint_out(at::Tensor & out, double mean, double std, c10::SymIntArrayRef size, ::std::optional generator=::std::nullopt); +TORCH_API at::Tensor & normal_symint_outf(double mean, double std, c10::SymIntArrayRef size, ::std::optional generator, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_v_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_v_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..cd57d81c6ab0aaef3105a006cfb8d6ddf35c8ecd --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_v_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_special_chebyshev_polynomial_v : public TensorIteratorBase { + + + void meta(const at::Tensor & x, const at::Tensor & n); +}; + +} // namespace native +} // namespace at