diff --git a/.gitattributes b/.gitattributes index 40eea14872807652db3aa82bb53647e0c1e9ef2e..c541863735ccd41746ae44ab0ada0f5a99d11a60 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1915,3 +1915,12 @@ videollama2/lib/python3.10/site-packages/sklearn/tree/_tree.cpython-310-x86_64-l videollama2/lib/python3.10/site-packages/sklearn/ensemble/_hist_gradient_boosting/_binning.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text videollama2/lib/python3.10/site-packages/sklearn/utils/arrayfuncs.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text videollama2/lib/python3.10/site-packages/sklearn/utils/_cython_blas.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/utils/_logistic_sigmoid.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/utils/murmurhash.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/utils/_random.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/utils/sparsefuncs_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/utils/_readonly_array_wrapper.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_elkan.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.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/_agglomerative.py b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_agglomerative.py new file mode 100644 index 0000000000000000000000000000000000000000..ec54a915cc17a0cdfbdbd9fc71de8759624b4094 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_agglomerative.py @@ -0,0 +1,1333 @@ +"""Hierarchical Agglomerative Clustering + +These routines perform some hierarchical agglomerative clustering of some +input data. + +Authors : Vincent Michel, Bertrand Thirion, Alexandre Gramfort, + Gael Varoquaux +License: BSD 3 clause +""" +import warnings +from heapq import heapify, heappop, heappush, heappushpop +from numbers import Integral, Real + +import numpy as np +from scipy import sparse +from scipy.sparse.csgraph import connected_components + +from ..base import BaseEstimator, ClusterMixin, ClassNamePrefixFeaturesOutMixin +from ..metrics.pairwise import paired_distances +from ..metrics.pairwise import _VALID_METRICS +from ..metrics import DistanceMetric +from ..metrics._dist_metrics import METRIC_MAPPING +from ..utils import check_array +from ..utils._fast_dict import IntFloatDict +from ..utils.graph import _fix_connected_components +from ..utils._param_validation import Hidden, Interval, StrOptions, HasMethods +from ..utils.validation import check_memory + +# mypy error: Module 'sklearn.cluster' has no attribute '_hierarchical_fast' +from . import _hierarchical_fast as _hierarchical # type: ignore +from ._feature_agglomeration import AgglomerationTransform + +############################################################################### +# For non fully-connected graphs + + +def _fix_connectivity(X, connectivity, affinity): + """ + Fixes the connectivity matrix. + + The different steps are: + + - copies it + - makes it symmetric + - converts it to LIL if necessary + - completes it if necessary. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Feature matrix representing `n_samples` samples to be clustered. + + connectivity : sparse matrix, default=None + Connectivity matrix. Defines for each sample the neighboring samples + following a given structure of the data. The matrix is assumed to + be symmetric and only the upper triangular half is used. + Default is `None`, i.e, the Ward algorithm is unstructured. + + affinity : {"euclidean", "precomputed"}, default="euclidean" + Which affinity to use. At the moment `precomputed` and + ``euclidean`` are supported. `euclidean` uses the + negative squared Euclidean distance between points. + + Returns + ------- + connectivity : sparse matrix + The fixed connectivity matrix. + + n_connected_components : int + The number of connected components in the graph. + """ + n_samples = X.shape[0] + if connectivity.shape[0] != n_samples or connectivity.shape[1] != n_samples: + raise ValueError( + "Wrong shape for connectivity matrix: %s when X is %s" + % (connectivity.shape, X.shape) + ) + + # Make the connectivity matrix symmetric: + connectivity = connectivity + connectivity.T + + # Convert connectivity matrix to LIL + if not sparse.isspmatrix_lil(connectivity): + if not sparse.isspmatrix(connectivity): + connectivity = sparse.lil_matrix(connectivity) + else: + connectivity = connectivity.tolil() + + # Compute the number of nodes + n_connected_components, labels = connected_components(connectivity) + + if n_connected_components > 1: + warnings.warn( + "the number of connected components of the " + "connectivity matrix is %d > 1. Completing it to avoid " + "stopping the tree early." % n_connected_components, + stacklevel=2, + ) + # XXX: Can we do without completing the matrix? + connectivity = _fix_connected_components( + X=X, + graph=connectivity, + n_connected_components=n_connected_components, + component_labels=labels, + metric=affinity, + mode="connectivity", + ) + + return connectivity, n_connected_components + + +def _single_linkage_tree( + connectivity, + n_samples, + n_nodes, + n_clusters, + n_connected_components, + return_distance, +): + """ + Perform single linkage clustering on sparse data via the minimum + spanning tree from scipy.sparse.csgraph, then using union-find to label. + The parent array is then generated by walking through the tree. + """ + from scipy.sparse.csgraph import minimum_spanning_tree + + # explicitly cast connectivity to ensure safety + connectivity = connectivity.astype(np.float64, copy=False) + + # Ensure zero distances aren't ignored by setting them to "epsilon" + epsilon_value = np.finfo(dtype=connectivity.data.dtype).eps + connectivity.data[connectivity.data == 0] = epsilon_value + + # Use scipy.sparse.csgraph to generate a minimum spanning tree + mst = minimum_spanning_tree(connectivity.tocsr()) + + # Convert the graph to scipy.cluster.hierarchy array format + mst = mst.tocoo() + + # Undo the epsilon values + mst.data[mst.data == epsilon_value] = 0 + + mst_array = np.vstack([mst.row, mst.col, mst.data]).T + + # Sort edges of the min_spanning_tree by weight + mst_array = mst_array[np.argsort(mst_array.T[2], kind="mergesort"), :] + + # Convert edge list into standard hierarchical clustering format + single_linkage_tree = _hierarchical._single_linkage_label(mst_array) + children_ = single_linkage_tree[:, :2].astype(int) + + # Compute parents + parent = np.arange(n_nodes, dtype=np.intp) + for i, (left, right) in enumerate(children_, n_samples): + if n_clusters is not None and i >= n_nodes: + break + if left < n_nodes: + parent[left] = i + if right < n_nodes: + parent[right] = i + + if return_distance: + distances = single_linkage_tree[:, 2] + return children_, n_connected_components, n_samples, parent, distances + return children_, n_connected_components, n_samples, parent + + +############################################################################### +# Hierarchical tree building functions + + +def ward_tree(X, *, connectivity=None, n_clusters=None, return_distance=False): + """Ward clustering based on a Feature matrix. + + Recursively merges the pair of clusters that minimally increases + within-cluster variance. + + The inertia matrix uses a Heapq-based representation. + + This is the structured version, that takes into account some topological + structure between samples. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Feature matrix representing `n_samples` samples to be clustered. + + connectivity : sparse matrix, default=None + Connectivity matrix. Defines for each sample the neighboring samples + following a given structure of the data. The matrix is assumed to + be symmetric and only the upper triangular half is used. + Default is None, i.e, the Ward algorithm is unstructured. + + n_clusters : int, default=None + `n_clusters` should be less than `n_samples`. Stop early the + construction of the tree at `n_clusters.` This is useful to decrease + computation time if the number of clusters is not small compared to the + number of samples. In this case, the complete tree is not computed, thus + the 'children' output is of limited use, and the 'parents' output should + rather be used. This option is valid only when specifying a connectivity + matrix. + + return_distance : bool, default=False + If `True`, return the distance between the clusters. + + Returns + ------- + children : ndarray of shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i`. + + n_connected_components : int + The number of connected components in the graph. + + n_leaves : int + The number of leaves in the tree. + + parents : ndarray of shape (n_nodes,) or None + The parent of each node. Only returned when a connectivity matrix + is specified, elsewhere 'None' is returned. + + distances : ndarray of shape (n_nodes-1,) + Only returned if `return_distance` is set to `True` (for compatibility). + The distances between the centers of the nodes. `distances[i]` + corresponds to a weighted Euclidean distance between + the nodes `children[i, 1]` and `children[i, 2]`. If the nodes refer to + leaves of the tree, then `distances[i]` is their unweighted Euclidean + distance. Distances are updated in the following way + (from scipy.hierarchy.linkage): + + The new entry :math:`d(u,v)` is computed as follows, + + .. math:: + + d(u,v) = \\sqrt{\\frac{|v|+|s|} + {T}d(v,s)^2 + + \\frac{|v|+|t|} + {T}d(v,t)^2 + - \\frac{|v|} + {T}d(s,t)^2} + + where :math:`u` is the newly joined cluster consisting of + clusters :math:`s` and :math:`t`, :math:`v` is an unused + cluster in the forest, :math:`T=|v|+|s|+|t|`, and + :math:`|*|` is the cardinality of its argument. This is also + known as the incremental algorithm. + """ + X = np.asarray(X) + if X.ndim == 1: + X = np.reshape(X, (-1, 1)) + n_samples, n_features = X.shape + + if connectivity is None: + from scipy.cluster import hierarchy # imports PIL + + if n_clusters is not None: + warnings.warn( + "Partial build of the tree is implemented " + "only for structured clustering (i.e. with " + "explicit connectivity). The algorithm " + "will build the full tree and only " + "retain the lower branches required " + "for the specified number of clusters", + stacklevel=2, + ) + X = np.require(X, requirements="W") + out = hierarchy.ward(X) + children_ = out[:, :2].astype(np.intp) + + if return_distance: + distances = out[:, 2] + return children_, 1, n_samples, None, distances + else: + return children_, 1, n_samples, None + + connectivity, n_connected_components = _fix_connectivity( + X, connectivity, affinity="euclidean" + ) + if n_clusters is None: + n_nodes = 2 * n_samples - 1 + else: + if n_clusters > n_samples: + raise ValueError( + "Cannot provide more clusters than samples. " + "%i n_clusters was asked, and there are %i " + "samples." % (n_clusters, n_samples) + ) + n_nodes = 2 * n_samples - n_clusters + + # create inertia matrix + coord_row = [] + coord_col = [] + A = [] + for ind, row in enumerate(connectivity.rows): + A.append(row) + # We keep only the upper triangular for the moments + # Generator expressions are faster than arrays on the following + row = [i for i in row if i < ind] + coord_row.extend( + len(row) + * [ + ind, + ] + ) + coord_col.extend(row) + + coord_row = np.array(coord_row, dtype=np.intp, order="C") + coord_col = np.array(coord_col, dtype=np.intp, order="C") + + # build moments as a list + moments_1 = np.zeros(n_nodes, order="C") + moments_1[:n_samples] = 1 + moments_2 = np.zeros((n_nodes, n_features), order="C") + moments_2[:n_samples] = X + inertia = np.empty(len(coord_row), dtype=np.float64, order="C") + _hierarchical.compute_ward_dist(moments_1, moments_2, coord_row, coord_col, inertia) + inertia = list(zip(inertia, coord_row, coord_col)) + heapify(inertia) + + # prepare the main fields + parent = np.arange(n_nodes, dtype=np.intp) + used_node = np.ones(n_nodes, dtype=bool) + children = [] + if return_distance: + distances = np.empty(n_nodes - n_samples) + + not_visited = np.empty(n_nodes, dtype=np.int8, order="C") + + # recursive merge loop + for k in range(n_samples, n_nodes): + # identify the merge + while True: + inert, i, j = heappop(inertia) + if used_node[i] and used_node[j]: + break + parent[i], parent[j] = k, k + children.append((i, j)) + used_node[i] = used_node[j] = False + if return_distance: # store inertia value + distances[k - n_samples] = inert + + # update the moments + moments_1[k] = moments_1[i] + moments_1[j] + moments_2[k] = moments_2[i] + moments_2[j] + + # update the structure matrix A and the inertia matrix + coord_col = [] + not_visited.fill(1) + not_visited[k] = 0 + _hierarchical._get_parents(A[i], coord_col, parent, not_visited) + _hierarchical._get_parents(A[j], coord_col, parent, not_visited) + # List comprehension is faster than a for loop + [A[col].append(k) for col in coord_col] + A.append(coord_col) + coord_col = np.array(coord_col, dtype=np.intp, order="C") + coord_row = np.empty(coord_col.shape, dtype=np.intp, order="C") + coord_row.fill(k) + n_additions = len(coord_row) + ini = np.empty(n_additions, dtype=np.float64, order="C") + + _hierarchical.compute_ward_dist(moments_1, moments_2, coord_row, coord_col, ini) + + # List comprehension is faster than a for loop + [heappush(inertia, (ini[idx], k, coord_col[idx])) for idx in range(n_additions)] + + # Separate leaves in children (empty lists up to now) + n_leaves = n_samples + # sort children to get consistent output with unstructured version + children = [c[::-1] for c in children] + children = np.array(children) # return numpy array for efficient caching + + if return_distance: + # 2 is scaling factor to compare w/ unstructured version + distances = np.sqrt(2.0 * distances) + return children, n_connected_components, n_leaves, parent, distances + else: + return children, n_connected_components, n_leaves, parent + + +# single average and complete linkage +def linkage_tree( + X, + connectivity=None, + n_clusters=None, + linkage="complete", + affinity="euclidean", + return_distance=False, +): + """Linkage agglomerative clustering based on a Feature matrix. + + The inertia matrix uses a Heapq-based representation. + + This is the structured version, that takes into account some topological + structure between samples. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Feature matrix representing `n_samples` samples to be clustered. + + connectivity : sparse matrix, default=None + Connectivity matrix. Defines for each sample the neighboring samples + following a given structure of the data. The matrix is assumed to + be symmetric and only the upper triangular half is used. + Default is `None`, i.e, the Ward algorithm is unstructured. + + n_clusters : int, default=None + Stop early the construction of the tree at `n_clusters`. This is + useful to decrease computation time if the number of clusters is + not small compared to the number of samples. In this case, the + complete tree is not computed, thus the 'children' output is of + limited use, and the 'parents' output should rather be used. + This option is valid only when specifying a connectivity matrix. + + linkage : {"average", "complete", "single"}, default="complete" + Which linkage criteria to use. The linkage criterion determines which + distance to use between sets of observation. + - "average" uses the average of the distances of each observation of + the two sets. + - "complete" or maximum linkage uses the maximum distances between + all observations of the two sets. + - "single" uses the minimum of the distances between all + observations of the two sets. + + affinity : str or callable, default='euclidean' + Which metric to use. Can be 'euclidean', 'manhattan', or any + distance known to paired distance (see metric.pairwise). + + return_distance : bool, default=False + Whether or not to return the distances between the clusters. + + Returns + ------- + children : ndarray of shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i`. + + n_connected_components : int + The number of connected components in the graph. + + n_leaves : int + The number of leaves in the tree. + + parents : ndarray of shape (n_nodes, ) or None + The parent of each node. Only returned when a connectivity matrix + is specified, elsewhere 'None' is returned. + + distances : ndarray of shape (n_nodes-1,) + Returned when `return_distance` is set to `True`. + + distances[i] refers to the distance between children[i][0] and + children[i][1] when they are merged. + + See Also + -------- + ward_tree : Hierarchical clustering with ward linkage. + """ + X = np.asarray(X) + if X.ndim == 1: + X = np.reshape(X, (-1, 1)) + n_samples, n_features = X.shape + + linkage_choices = { + "complete": _hierarchical.max_merge, + "average": _hierarchical.average_merge, + "single": None, + } # Single linkage is handled differently + try: + join_func = linkage_choices[linkage] + except KeyError as e: + raise ValueError( + "Unknown linkage option, linkage should be one of %s, but %s was given" + % (linkage_choices.keys(), linkage) + ) from e + + if affinity == "cosine" and np.any(~np.any(X, axis=1)): + raise ValueError("Cosine affinity cannot be used when X contains zero vectors") + + if connectivity is None: + from scipy.cluster import hierarchy # imports PIL + + if n_clusters is not None: + warnings.warn( + "Partial build of the tree is implemented " + "only for structured clustering (i.e. with " + "explicit connectivity). The algorithm " + "will build the full tree and only " + "retain the lower branches required " + "for the specified number of clusters", + stacklevel=2, + ) + + if affinity == "precomputed": + # for the linkage function of hierarchy to work on precomputed + # data, provide as first argument an ndarray of the shape returned + # by sklearn.metrics.pairwise_distances. + if X.shape[0] != X.shape[1]: + raise ValueError( + f"Distance matrix should be square, got matrix of shape {X.shape}" + ) + i, j = np.triu_indices(X.shape[0], k=1) + X = X[i, j] + elif affinity == "l2": + # Translate to something understood by scipy + affinity = "euclidean" + elif affinity in ("l1", "manhattan"): + affinity = "cityblock" + elif callable(affinity): + X = affinity(X) + i, j = np.triu_indices(X.shape[0], k=1) + X = X[i, j] + if ( + linkage == "single" + and affinity != "precomputed" + and not callable(affinity) + and affinity in METRIC_MAPPING + ): + + # We need the fast cythonized metric from neighbors + dist_metric = DistanceMetric.get_metric(affinity) + + # The Cython routines used require contiguous arrays + X = np.ascontiguousarray(X, dtype=np.double) + + mst = _hierarchical.mst_linkage_core(X, dist_metric) + # Sort edges of the min_spanning_tree by weight + mst = mst[np.argsort(mst.T[2], kind="mergesort"), :] + + # Convert edge list into standard hierarchical clustering format + out = _hierarchical.single_linkage_label(mst) + else: + out = hierarchy.linkage(X, method=linkage, metric=affinity) + children_ = out[:, :2].astype(int, copy=False) + + if return_distance: + distances = out[:, 2] + return children_, 1, n_samples, None, distances + return children_, 1, n_samples, None + + connectivity, n_connected_components = _fix_connectivity( + X, connectivity, affinity=affinity + ) + connectivity = connectivity.tocoo() + # Put the diagonal to zero + diag_mask = connectivity.row != connectivity.col + connectivity.row = connectivity.row[diag_mask] + connectivity.col = connectivity.col[diag_mask] + connectivity.data = connectivity.data[diag_mask] + del diag_mask + + if affinity == "precomputed": + distances = X[connectivity.row, connectivity.col].astype(np.float64, copy=False) + else: + # FIXME We compute all the distances, while we could have only computed + # the "interesting" distances + distances = paired_distances( + X[connectivity.row], X[connectivity.col], metric=affinity + ) + connectivity.data = distances + + if n_clusters is None: + n_nodes = 2 * n_samples - 1 + else: + assert n_clusters <= n_samples + n_nodes = 2 * n_samples - n_clusters + + if linkage == "single": + return _single_linkage_tree( + connectivity, + n_samples, + n_nodes, + n_clusters, + n_connected_components, + return_distance, + ) + + if return_distance: + distances = np.empty(n_nodes - n_samples) + # create inertia heap and connection matrix + A = np.empty(n_nodes, dtype=object) + inertia = list() + + # LIL seems to the best format to access the rows quickly, + # without the numpy overhead of slicing CSR indices and data. + connectivity = connectivity.tolil() + # We are storing the graph in a list of IntFloatDict + for ind, (data, row) in enumerate(zip(connectivity.data, connectivity.rows)): + A[ind] = IntFloatDict( + np.asarray(row, dtype=np.intp), np.asarray(data, dtype=np.float64) + ) + # We keep only the upper triangular for the heap + # Generator expressions are faster than arrays on the following + inertia.extend( + _hierarchical.WeightedEdge(d, ind, r) for r, d in zip(row, data) if r < ind + ) + del connectivity + + heapify(inertia) + + # prepare the main fields + parent = np.arange(n_nodes, dtype=np.intp) + used_node = np.ones(n_nodes, dtype=np.intp) + children = [] + + # recursive merge loop + for k in range(n_samples, n_nodes): + # identify the merge + while True: + edge = heappop(inertia) + if used_node[edge.a] and used_node[edge.b]: + break + i = edge.a + j = edge.b + + if return_distance: + # store distances + distances[k - n_samples] = edge.weight + + parent[i] = parent[j] = k + children.append((i, j)) + # Keep track of the number of elements per cluster + n_i = used_node[i] + n_j = used_node[j] + used_node[k] = n_i + n_j + used_node[i] = used_node[j] = False + + # update the structure matrix A and the inertia matrix + # a clever 'min', or 'max' operation between A[i] and A[j] + coord_col = join_func(A[i], A[j], used_node, n_i, n_j) + for col, d in coord_col: + A[col].append(k, d) + # Here we use the information from coord_col (containing the + # distances) to update the heap + heappush(inertia, _hierarchical.WeightedEdge(d, k, col)) + A[k] = coord_col + # Clear A[i] and A[j] to save memory + A[i] = A[j] = 0 + + # Separate leaves in children (empty lists up to now) + n_leaves = n_samples + + # # return numpy array for efficient caching + children = np.array(children)[:, ::-1] + + if return_distance: + return children, n_connected_components, n_leaves, parent, distances + return children, n_connected_components, n_leaves, parent + + +# Matching names to tree-building strategies +def _complete_linkage(*args, **kwargs): + kwargs["linkage"] = "complete" + return linkage_tree(*args, **kwargs) + + +def _average_linkage(*args, **kwargs): + kwargs["linkage"] = "average" + return linkage_tree(*args, **kwargs) + + +def _single_linkage(*args, **kwargs): + kwargs["linkage"] = "single" + return linkage_tree(*args, **kwargs) + + +_TREE_BUILDERS = dict( + ward=ward_tree, + complete=_complete_linkage, + average=_average_linkage, + single=_single_linkage, +) + +############################################################################### +# Functions for cutting hierarchical clustering tree + + +def _hc_cut(n_clusters, children, n_leaves): + """Function cutting the ward tree for a given number of clusters. + + Parameters + ---------- + n_clusters : int or ndarray + The number of clusters to form. + + children : ndarray of shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i`. + + n_leaves : int + Number of leaves of the tree. + + Returns + ------- + labels : array [n_samples] + Cluster labels for each point. + """ + if n_clusters > n_leaves: + raise ValueError( + "Cannot extract more clusters than samples: " + "%s clusters where given for a tree with %s leaves." + % (n_clusters, n_leaves) + ) + # In this function, we store nodes as a heap to avoid recomputing + # the max of the nodes: the first element is always the smallest + # We use negated indices as heaps work on smallest elements, and we + # are interested in largest elements + # children[-1] is the root of the tree + nodes = [-(max(children[-1]) + 1)] + for _ in range(n_clusters - 1): + # As we have a heap, nodes[0] is the smallest element + these_children = children[-nodes[0] - n_leaves] + # Insert the 2 children and remove the largest node + heappush(nodes, -these_children[0]) + heappushpop(nodes, -these_children[1]) + label = np.zeros(n_leaves, dtype=np.intp) + for i, node in enumerate(nodes): + label[_hierarchical._hc_get_descendent(-node, children, n_leaves)] = i + return label + + +############################################################################### + + +class AgglomerativeClustering(ClusterMixin, BaseEstimator): + """ + Agglomerative Clustering. + + Recursively merges pair of clusters of sample data; uses linkage distance. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int or None, default=2 + The number of clusters to find. It must be ``None`` if + ``distance_threshold`` is not ``None``. + + affinity : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. If metric is a string or callable, it must be one of + the options allowed by :func:`sklearn.metrics.pairwise_distances` for + its metric parameter. + If linkage is "ward", only "euclidean" is accepted. + If "precomputed", a distance matrix (instead of a similarity matrix) + is needed as input for the fit method. + + .. deprecated:: 1.2 + `affinity` was deprecated in version 1.2 and will be renamed to + `metric` in 1.4. + + metric : str or callable, default=None + Metric used to compute the linkage. Can be "euclidean", "l1", "l2", + "manhattan", "cosine", or "precomputed". If set to `None` then + "euclidean" is used. If linkage is "ward", only "euclidean" is + accepted. If "precomputed", a distance matrix is needed as input for + the fit method. + + .. versionadded:: 1.2 + + memory : str or object with the joblib.Memory interface, default=None + Used to cache the output of the computation of the tree. + By default, no caching is done. If a string is given, it is the + path to the caching directory. + + connectivity : array-like or callable, default=None + Connectivity matrix. Defines for each sample the neighboring + samples following a given structure of the data. + This can be a connectivity matrix itself or a callable that transforms + the data into a connectivity matrix, such as derived from + `kneighbors_graph`. Default is ``None``, i.e, the + hierarchical clustering algorithm is unstructured. + + compute_full_tree : 'auto' or bool, default='auto' + Stop early the construction of the tree at ``n_clusters``. This is + useful to decrease computation time if the number of clusters is not + small compared to the number of samples. This option is useful only + when specifying a connectivity matrix. Note also that when varying the + number of clusters and using caching, it may be advantageous to compute + the full tree. It must be ``True`` if ``distance_threshold`` is not + ``None``. By default `compute_full_tree` is "auto", which is equivalent + to `True` when `distance_threshold` is not `None` or that `n_clusters` + is inferior to the maximum between 100 or `0.02 * n_samples`. + Otherwise, "auto" is equivalent to `False`. + + linkage : {'ward', 'complete', 'average', 'single'}, default='ward' + Which linkage criterion to use. The linkage criterion determines which + distance to use between sets of observation. The algorithm will merge + the pairs of cluster that minimize this criterion. + + - 'ward' minimizes the variance of the clusters being merged. + - 'average' uses the average of the distances of each observation of + the two sets. + - 'complete' or 'maximum' linkage uses the maximum distances between + all observations of the two sets. + - 'single' uses the minimum of the distances between all observations + of the two sets. + + .. versionadded:: 0.20 + Added the 'single' option + + distance_threshold : float, default=None + The linkage distance threshold at or above which clusters will not be + merged. If not ``None``, ``n_clusters`` must be ``None`` and + ``compute_full_tree`` must be ``True``. + + .. versionadded:: 0.21 + + compute_distances : bool, default=False + Computes distances between clusters even if `distance_threshold` is not + used. This can be used to make dendrogram visualization, but introduces + a computational and memory overhead. + + .. versionadded:: 0.24 + + Attributes + ---------- + n_clusters_ : int + The number of clusters found by the algorithm. If + ``distance_threshold=None``, it will be equal to the given + ``n_clusters``. + + labels_ : ndarray of shape (n_samples) + Cluster labels for each point. + + n_leaves_ : int + Number of leaves in the hierarchical tree. + + n_connected_components_ : int + The estimated number of connected components in the graph. + + .. versionadded:: 0.21 + ``n_connected_components_`` was added to replace ``n_components_``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + children_ : array-like of shape (n_samples-1, 2) + The children of each non-leaf node. Values less than `n_samples` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_samples` is a non-leaf + node and has children `children_[i - n_samples]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_samples + i`. + + distances_ : array-like of shape (n_nodes-1,) + Distances between nodes in the corresponding place in `children_`. + Only computed if `distance_threshold` is used or `compute_distances` + is set to `True`. + + See Also + -------- + FeatureAgglomeration : Agglomerative clustering but for features instead of + samples. + ward_tree : Hierarchical clustering with ward linkage. + + Examples + -------- + >>> from sklearn.cluster import AgglomerativeClustering + >>> import numpy as np + >>> X = np.array([[1, 2], [1, 4], [1, 0], + ... [4, 2], [4, 4], [4, 0]]) + >>> clustering = AgglomerativeClustering().fit(X) + >>> clustering + AgglomerativeClustering() + >>> clustering.labels_ + array([1, 1, 1, 0, 0, 0]) + """ + + _parameter_constraints: dict = { + "n_clusters": [Interval(Integral, 1, None, closed="left"), None], + "affinity": [ + Hidden(StrOptions({"deprecated"})), + StrOptions(set(_VALID_METRICS) | {"precomputed"}), + callable, + ], + "metric": [ + StrOptions(set(_VALID_METRICS) | {"precomputed"}), + callable, + None, + ], + "memory": [str, HasMethods("cache"), None], + "connectivity": ["array-like", callable, None], + "compute_full_tree": [StrOptions({"auto"}), "boolean"], + "linkage": [StrOptions(set(_TREE_BUILDERS.keys()))], + "distance_threshold": [Interval(Real, 0, None, closed="left"), None], + "compute_distances": ["boolean"], + } + + def __init__( + self, + n_clusters=2, + *, + affinity="deprecated", # TODO(1.4): Remove + metric=None, # TODO(1.4): Set to "euclidean" + memory=None, + connectivity=None, + compute_full_tree="auto", + linkage="ward", + distance_threshold=None, + compute_distances=False, + ): + self.n_clusters = n_clusters + self.distance_threshold = distance_threshold + self.memory = memory + self.connectivity = connectivity + self.compute_full_tree = compute_full_tree + self.linkage = linkage + self.affinity = affinity + self.metric = metric + self.compute_distances = compute_distances + + def fit(self, X, y=None): + """Fit the hierarchical clustering from features, or distance matrix. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) or \ + (n_samples, n_samples) + Training instances to cluster, or distances between instances if + ``metric='precomputed'``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + Returns the fitted instance. + """ + self._validate_params() + X = self._validate_data(X, ensure_min_samples=2) + return self._fit(X) + + def _fit(self, X): + """Fit without validation + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) or (n_samples, n_samples) + Training instances to cluster, or distances between instances if + ``affinity='precomputed'``. + + Returns + ------- + self : object + Returns the fitted instance. + """ + memory = check_memory(self.memory) + + self._metric = self.metric + # TODO(1.4): Remove + if self.affinity != "deprecated": + if self.metric is not None: + raise ValueError( + "Both `affinity` and `metric` attributes were set. Attribute" + " `affinity` was deprecated in version 1.2 and will be removed in" + " 1.4. To avoid this error, only set the `metric` attribute." + ) + warnings.warn( + "Attribute `affinity` was deprecated in version 1.2 and will be removed" + " in 1.4. Use `metric` instead", + FutureWarning, + ) + self._metric = self.affinity + elif self.metric is None: + self._metric = "euclidean" + + if not ((self.n_clusters is None) ^ (self.distance_threshold is None)): + raise ValueError( + "Exactly one of n_clusters and " + "distance_threshold has to be set, and the other " + "needs to be None." + ) + + if self.distance_threshold is not None and not self.compute_full_tree: + raise ValueError( + "compute_full_tree must be True if distance_threshold is set." + ) + + if self.linkage == "ward" and self._metric != "euclidean": + raise ValueError( + f"{self._metric} was provided as metric. Ward can only " + "work with euclidean distances." + ) + + tree_builder = _TREE_BUILDERS[self.linkage] + + connectivity = self.connectivity + if self.connectivity is not None: + if callable(self.connectivity): + connectivity = self.connectivity(X) + connectivity = check_array( + connectivity, accept_sparse=["csr", "coo", "lil"] + ) + + n_samples = len(X) + compute_full_tree = self.compute_full_tree + if self.connectivity is None: + compute_full_tree = True + if compute_full_tree == "auto": + if self.distance_threshold is not None: + compute_full_tree = True + else: + # Early stopping is likely to give a speed up only for + # a large number of clusters. The actual threshold + # implemented here is heuristic + compute_full_tree = self.n_clusters < max(100, 0.02 * n_samples) + n_clusters = self.n_clusters + if compute_full_tree: + n_clusters = None + + # Construct the tree + kwargs = {} + if self.linkage != "ward": + kwargs["linkage"] = self.linkage + kwargs["affinity"] = self._metric + + distance_threshold = self.distance_threshold + + return_distance = (distance_threshold is not None) or self.compute_distances + + out = memory.cache(tree_builder)( + X, + connectivity=connectivity, + n_clusters=n_clusters, + return_distance=return_distance, + **kwargs, + ) + (self.children_, self.n_connected_components_, self.n_leaves_, parents) = out[ + :4 + ] + + if return_distance: + self.distances_ = out[-1] + + if self.distance_threshold is not None: # distance_threshold is used + self.n_clusters_ = ( + np.count_nonzero(self.distances_ >= distance_threshold) + 1 + ) + else: # n_clusters is used + self.n_clusters_ = self.n_clusters + + # Cut the tree + if compute_full_tree: + self.labels_ = _hc_cut(self.n_clusters_, self.children_, self.n_leaves_) + else: + labels = _hierarchical.hc_get_heads(parents, copy=False) + # copy to avoid holding a reference on the original array + labels = np.copy(labels[:n_samples]) + # Reassign cluster numbers + self.labels_ = np.searchsorted(np.unique(labels), labels) + return self + + def fit_predict(self, X, y=None): + """Fit and return the result of each sample's clustering assignment. + + In addition to fitting, this method also return the result of the + clustering assignment for each sample in the training set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or \ + (n_samples, n_samples) + Training instances to cluster, or distances between instances if + ``affinity='precomputed'``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. + """ + return super().fit_predict(X, y) + + +class FeatureAgglomeration( + ClassNamePrefixFeaturesOutMixin, AgglomerativeClustering, AgglomerationTransform +): + """Agglomerate features. + + Recursively merges pair of clusters of features. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int or None, default=2 + The number of clusters to find. It must be ``None`` if + ``distance_threshold`` is not ``None``. + + affinity : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. If metric is a string or callable, it must be one of + the options allowed by :func:`sklearn.metrics.pairwise_distances` for + its metric parameter. + If linkage is "ward", only "euclidean" is accepted. + If "precomputed", a distance matrix (instead of a similarity matrix) + is needed as input for the fit method. + + .. deprecated:: 1.2 + `affinity` was deprecated in version 1.2 and will be renamed to + `metric` in 1.4. + + metric : str or callable, default=None + Metric used to compute the linkage. Can be "euclidean", "l1", "l2", + "manhattan", "cosine", or "precomputed". If set to `None` then + "euclidean" is used. If linkage is "ward", only "euclidean" is + accepted. If "precomputed", a distance matrix is needed as input for + the fit method. + + .. versionadded:: 1.2 + + memory : str or object with the joblib.Memory interface, default=None + Used to cache the output of the computation of the tree. + By default, no caching is done. If a string is given, it is the + path to the caching directory. + + connectivity : array-like or callable, default=None + Connectivity matrix. Defines for each feature the neighboring + features following a given structure of the data. + This can be a connectivity matrix itself or a callable that transforms + the data into a connectivity matrix, such as derived from + `kneighbors_graph`. Default is `None`, i.e, the + hierarchical clustering algorithm is unstructured. + + compute_full_tree : 'auto' or bool, default='auto' + Stop early the construction of the tree at `n_clusters`. This is useful + to decrease computation time if the number of clusters is not small + compared to the number of features. This option is useful only when + specifying a connectivity matrix. Note also that when varying the + number of clusters and using caching, it may be advantageous to compute + the full tree. It must be ``True`` if ``distance_threshold`` is not + ``None``. By default `compute_full_tree` is "auto", which is equivalent + to `True` when `distance_threshold` is not `None` or that `n_clusters` + is inferior to the maximum between 100 or `0.02 * n_samples`. + Otherwise, "auto" is equivalent to `False`. + + linkage : {"ward", "complete", "average", "single"}, default="ward" + Which linkage criterion to use. The linkage criterion determines which + distance to use between sets of features. The algorithm will merge + the pairs of cluster that minimize this criterion. + + - "ward" minimizes the variance of the clusters being merged. + - "complete" or maximum linkage uses the maximum distances between + all features of the two sets. + - "average" uses the average of the distances of each feature of + the two sets. + - "single" uses the minimum of the distances between all features + of the two sets. + + pooling_func : callable, default=np.mean + This combines the values of agglomerated features into a single + value, and should accept an array of shape [M, N] and the keyword + argument `axis=1`, and reduce it to an array of size [M]. + + distance_threshold : float, default=None + The linkage distance threshold at or above which clusters will not be + merged. If not ``None``, ``n_clusters`` must be ``None`` and + ``compute_full_tree`` must be ``True``. + + .. versionadded:: 0.21 + + compute_distances : bool, default=False + Computes distances between clusters even if `distance_threshold` is not + used. This can be used to make dendrogram visualization, but introduces + a computational and memory overhead. + + .. versionadded:: 0.24 + + Attributes + ---------- + n_clusters_ : int + The number of clusters found by the algorithm. If + ``distance_threshold=None``, it will be equal to the given + ``n_clusters``. + + labels_ : array-like of (n_features,) + Cluster labels for each feature. + + n_leaves_ : int + Number of leaves in the hierarchical tree. + + n_connected_components_ : int + The estimated number of connected components in the graph. + + .. versionadded:: 0.21 + ``n_connected_components_`` was added to replace ``n_components_``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + children_ : array-like of shape (n_nodes-1, 2) + The children of each non-leaf node. Values less than `n_features` + correspond to leaves of the tree which are the original samples. + A node `i` greater than or equal to `n_features` is a non-leaf + node and has children `children_[i - n_features]`. Alternatively + at the i-th iteration, children[i][0] and children[i][1] + are merged to form node `n_features + i`. + + distances_ : array-like of shape (n_nodes-1,) + Distances between nodes in the corresponding place in `children_`. + Only computed if `distance_threshold` is used or `compute_distances` + is set to `True`. + + See Also + -------- + AgglomerativeClustering : Agglomerative clustering samples instead of + features. + ward_tree : Hierarchical clustering with ward linkage. + + Examples + -------- + >>> import numpy as np + >>> from sklearn import datasets, cluster + >>> digits = datasets.load_digits() + >>> images = digits.images + >>> X = np.reshape(images, (len(images), -1)) + >>> agglo = cluster.FeatureAgglomeration(n_clusters=32) + >>> agglo.fit(X) + FeatureAgglomeration(n_clusters=32) + >>> X_reduced = agglo.transform(X) + >>> X_reduced.shape + (1797, 32) + """ + + _parameter_constraints: dict = { + "n_clusters": [Interval(Integral, 1, None, closed="left"), None], + "affinity": [ + Hidden(StrOptions({"deprecated"})), + StrOptions(set(_VALID_METRICS) | {"precomputed"}), + callable, + ], + "metric": [ + StrOptions(set(_VALID_METRICS) | {"precomputed"}), + callable, + None, + ], + "memory": [str, HasMethods("cache"), None], + "connectivity": ["array-like", callable, None], + "compute_full_tree": [StrOptions({"auto"}), "boolean"], + "linkage": [StrOptions(set(_TREE_BUILDERS.keys()))], + "pooling_func": [callable], + "distance_threshold": [Interval(Real, 0, None, closed="left"), None], + "compute_distances": ["boolean"], + } + + def __init__( + self, + n_clusters=2, + *, + affinity="deprecated", # TODO(1.4): Remove + metric=None, # TODO(1.4): Set to "euclidean" + memory=None, + connectivity=None, + compute_full_tree="auto", + linkage="ward", + pooling_func=np.mean, + distance_threshold=None, + compute_distances=False, + ): + super().__init__( + n_clusters=n_clusters, + memory=memory, + connectivity=connectivity, + compute_full_tree=compute_full_tree, + linkage=linkage, + affinity=affinity, + metric=metric, + distance_threshold=distance_threshold, + compute_distances=compute_distances, + ) + self.pooling_func = pooling_func + + def fit(self, X, y=None): + """Fit the hierarchical clustering on the data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The data. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + Returns the transformer. + """ + self._validate_params() + X = self._validate_data(X, ensure_min_features=2) + super()._fit(X.T) + self._n_features_out = self.n_clusters_ + return self + + @property + def fit_predict(self): + """Fit and return the result of each sample's clustering assignment.""" + raise AttributeError diff --git a/videollama2/lib/python3.10/site-packages/sklearn/cluster/_bicluster.py b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_bicluster.py new file mode 100644 index 0000000000000000000000000000000000000000..73cb1c35290167ad5188b4ddd835da0dab4d1689 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_bicluster.py @@ -0,0 +1,628 @@ +"""Spectral biclustering algorithms.""" +# Authors : Kemal Eren +# License: BSD 3 clause + +from abc import ABCMeta, abstractmethod + +import numpy as np +from numbers import Integral + +from scipy.linalg import norm +from scipy.sparse import dia_matrix, issparse +from scipy.sparse.linalg import eigsh, svds + +from . import KMeans, MiniBatchKMeans +from ..base import BaseEstimator, BiclusterMixin +from ..utils import check_random_state +from ..utils import check_scalar + +from ..utils.extmath import make_nonnegative, randomized_svd, safe_sparse_dot + +from ..utils.validation import assert_all_finite +from ..utils._param_validation import Interval, StrOptions + + +__all__ = ["SpectralCoclustering", "SpectralBiclustering"] + + +def _scale_normalize(X): + """Normalize ``X`` by scaling rows and columns independently. + + Returns the normalized matrix and the row and column scaling + factors. + """ + X = make_nonnegative(X) + row_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=1))).squeeze() + col_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=0))).squeeze() + row_diag = np.where(np.isnan(row_diag), 0, row_diag) + col_diag = np.where(np.isnan(col_diag), 0, col_diag) + if issparse(X): + n_rows, n_cols = X.shape + r = dia_matrix((row_diag, [0]), shape=(n_rows, n_rows)) + c = dia_matrix((col_diag, [0]), shape=(n_cols, n_cols)) + an = r * X * c + else: + an = row_diag[:, np.newaxis] * X * col_diag + return an, row_diag, col_diag + + +def _bistochastic_normalize(X, max_iter=1000, tol=1e-5): + """Normalize rows and columns of ``X`` simultaneously so that all + rows sum to one constant and all columns sum to a different + constant. + """ + # According to paper, this can also be done more efficiently with + # deviation reduction and balancing algorithms. + X = make_nonnegative(X) + X_scaled = X + for _ in range(max_iter): + X_new, _, _ = _scale_normalize(X_scaled) + if issparse(X): + dist = norm(X_scaled.data - X.data) + else: + dist = norm(X_scaled - X_new) + X_scaled = X_new + if dist is not None and dist < tol: + break + return X_scaled + + +def _log_normalize(X): + """Normalize ``X`` according to Kluger's log-interactions scheme.""" + X = make_nonnegative(X, min_value=1) + if issparse(X): + raise ValueError( + "Cannot compute log of a sparse matrix," + " because log(x) diverges to -infinity as x" + " goes to 0." + ) + L = np.log(X) + row_avg = L.mean(axis=1)[:, np.newaxis] + col_avg = L.mean(axis=0) + avg = L.mean() + return L - row_avg - col_avg + avg + + +class BaseSpectral(BiclusterMixin, BaseEstimator, metaclass=ABCMeta): + """Base class for spectral biclustering.""" + + _parameter_constraints: dict = { + "svd_method": [StrOptions({"randomized", "arpack"})], + "n_svd_vecs": [Interval(Integral, 0, None, closed="left"), None], + "mini_batch": ["boolean"], + "init": [StrOptions({"k-means++", "random"}), np.ndarray], + "n_init": [Interval(Integral, 1, None, closed="left")], + "random_state": ["random_state"], + } + + @abstractmethod + def __init__( + self, + n_clusters=3, + svd_method="randomized", + n_svd_vecs=None, + mini_batch=False, + init="k-means++", + n_init=10, + random_state=None, + ): + self.n_clusters = n_clusters + self.svd_method = svd_method + self.n_svd_vecs = n_svd_vecs + self.mini_batch = mini_batch + self.init = init + self.n_init = n_init + self.random_state = random_state + + @abstractmethod + def _check_parameters(self, n_samples): + """Validate parameters depending on the input data.""" + + def fit(self, X, y=None): + """Create a biclustering for X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + SpectralBiclustering instance. + """ + self._validate_params() + + X = self._validate_data(X, accept_sparse="csr", dtype=np.float64) + self._check_parameters(X.shape[0]) + self._fit(X) + return self + + def _svd(self, array, n_components, n_discard): + """Returns first `n_components` left and right singular + vectors u and v, discarding the first `n_discard`. + """ + if self.svd_method == "randomized": + kwargs = {} + if self.n_svd_vecs is not None: + kwargs["n_oversamples"] = self.n_svd_vecs + u, _, vt = randomized_svd( + array, n_components, random_state=self.random_state, **kwargs + ) + + elif self.svd_method == "arpack": + u, _, vt = svds(array, k=n_components, ncv=self.n_svd_vecs) + if np.any(np.isnan(vt)): + # some eigenvalues of A * A.T are negative, causing + # sqrt() to be np.nan. This causes some vectors in vt + # to be np.nan. + A = safe_sparse_dot(array.T, array) + random_state = check_random_state(self.random_state) + # initialize with [-1,1] as in ARPACK + v0 = random_state.uniform(-1, 1, A.shape[0]) + _, v = eigsh(A, ncv=self.n_svd_vecs, v0=v0) + vt = v.T + if np.any(np.isnan(u)): + A = safe_sparse_dot(array, array.T) + random_state = check_random_state(self.random_state) + # initialize with [-1,1] as in ARPACK + v0 = random_state.uniform(-1, 1, A.shape[0]) + _, u = eigsh(A, ncv=self.n_svd_vecs, v0=v0) + + assert_all_finite(u) + assert_all_finite(vt) + u = u[:, n_discard:] + vt = vt[n_discard:] + return u, vt.T + + def _k_means(self, data, n_clusters): + if self.mini_batch: + model = MiniBatchKMeans( + n_clusters, + init=self.init, + n_init=self.n_init, + random_state=self.random_state, + ) + else: + model = KMeans( + n_clusters, + init=self.init, + n_init=self.n_init, + random_state=self.random_state, + ) + model.fit(data) + centroid = model.cluster_centers_ + labels = model.labels_ + return centroid, labels + + def _more_tags(self): + return { + "_xfail_checks": { + "check_estimators_dtypes": "raises nan error", + "check_fit2d_1sample": "_scale_normalize fails", + "check_fit2d_1feature": "raises apply_along_axis error", + "check_estimator_sparse_data": "does not fail gracefully", + "check_methods_subset_invariance": "empty array passed inside", + "check_dont_overwrite_parameters": "empty array passed inside", + "check_fit2d_predict1d": "empty array passed inside", + } + } + + +class SpectralCoclustering(BaseSpectral): + """Spectral Co-Clustering algorithm (Dhillon, 2001). + + Clusters rows and columns of an array `X` to solve the relaxed + normalized cut of the bipartite graph created from `X` as follows: + the edge between row vertex `i` and column vertex `j` has weight + `X[i, j]`. + + The resulting bicluster structure is block-diagonal, since each + row and each column belongs to exactly one bicluster. + + Supports sparse matrices, as long as they are nonnegative. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int, default=3 + The number of biclusters to find. + + svd_method : {'randomized', 'arpack'}, default='randomized' + Selects the algorithm for finding singular vectors. May be + 'randomized' or 'arpack'. If 'randomized', use + :func:`sklearn.utils.extmath.randomized_svd`, which may be faster + for large matrices. If 'arpack', use + :func:`scipy.sparse.linalg.svds`, which is more accurate, but + possibly slower in some cases. + + n_svd_vecs : int, default=None + Number of vectors to use in calculating the SVD. Corresponds + to `ncv` when `svd_method=arpack` and `n_oversamples` when + `svd_method` is 'randomized`. + + mini_batch : bool, default=False + Whether to use mini-batch k-means, which is faster but may get + different results. + + init : {'k-means++', 'random'}, or ndarray of shape \ + (n_clusters, n_features), default='k-means++' + Method for initialization of k-means algorithm; defaults to + 'k-means++'. + + n_init : int, default=10 + Number of random initializations that are tried with the + k-means algorithm. + + If mini-batch k-means is used, the best initialization is + chosen and the algorithm runs once. Otherwise, the algorithm + is run for each initialization and the best solution chosen. + + random_state : int, RandomState instance, default=None + Used for randomizing the singular value decomposition and the k-means + initialization. Use an int to make the randomness deterministic. + See :term:`Glossary `. + + Attributes + ---------- + rows_ : array-like of shape (n_row_clusters, n_rows) + Results of the clustering. `rows[i, r]` is True if + cluster `i` contains row `r`. Available only after calling ``fit``. + + columns_ : array-like of shape (n_column_clusters, n_columns) + Results of the clustering, like `rows`. + + row_labels_ : array-like of shape (n_rows,) + The bicluster label of each row. + + column_labels_ : array-like of shape (n_cols,) + The bicluster label of each column. + + biclusters_ : tuple of two ndarrays + The tuple contains the `rows_` and `columns_` arrays. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + SpectralBiclustering : Partitions rows and columns under the assumption + that the data has an underlying checkerboard structure. + + References + ---------- + * :doi:`Dhillon, Inderjit S, 2001. Co-clustering documents and words using + bipartite spectral graph partitioning. + <10.1145/502512.502550>` + + Examples + -------- + >>> from sklearn.cluster import SpectralCoclustering + >>> import numpy as np + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> clustering = SpectralCoclustering(n_clusters=2, random_state=0).fit(X) + >>> clustering.row_labels_ #doctest: +SKIP + array([0, 1, 1, 0, 0, 0], dtype=int32) + >>> clustering.column_labels_ #doctest: +SKIP + array([0, 0], dtype=int32) + >>> clustering + SpectralCoclustering(n_clusters=2, random_state=0) + """ + + _parameter_constraints: dict = { + **BaseSpectral._parameter_constraints, + "n_clusters": [Interval(Integral, 1, None, closed="left")], + } + + def __init__( + self, + n_clusters=3, + *, + svd_method="randomized", + n_svd_vecs=None, + mini_batch=False, + init="k-means++", + n_init=10, + random_state=None, + ): + super().__init__( + n_clusters, svd_method, n_svd_vecs, mini_batch, init, n_init, random_state + ) + + def _check_parameters(self, n_samples): + if self.n_clusters > n_samples: + raise ValueError( + f"n_clusters should be <= n_samples={n_samples}. Got" + f" {self.n_clusters} instead." + ) + + def _fit(self, X): + normalized_data, row_diag, col_diag = _scale_normalize(X) + n_sv = 1 + int(np.ceil(np.log2(self.n_clusters))) + u, v = self._svd(normalized_data, n_sv, n_discard=1) + z = np.vstack((row_diag[:, np.newaxis] * u, col_diag[:, np.newaxis] * v)) + + _, labels = self._k_means(z, self.n_clusters) + + n_rows = X.shape[0] + self.row_labels_ = labels[:n_rows] + self.column_labels_ = labels[n_rows:] + + self.rows_ = np.vstack([self.row_labels_ == c for c in range(self.n_clusters)]) + self.columns_ = np.vstack( + [self.column_labels_ == c for c in range(self.n_clusters)] + ) + + +class SpectralBiclustering(BaseSpectral): + """Spectral biclustering (Kluger, 2003). + + Partitions rows and columns under the assumption that the data has + an underlying checkerboard structure. For instance, if there are + two row partitions and three column partitions, each row will + belong to three biclusters, and each column will belong to two + biclusters. The outer product of the corresponding row and column + label vectors gives this checkerboard structure. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int or tuple (n_row_clusters, n_column_clusters), default=3 + The number of row and column clusters in the checkerboard + structure. + + method : {'bistochastic', 'scale', 'log'}, default='bistochastic' + Method of normalizing and converting singular vectors into + biclusters. May be one of 'scale', 'bistochastic', or 'log'. + The authors recommend using 'log'. If the data is sparse, + however, log normalization will not work, which is why the + default is 'bistochastic'. + + .. warning:: + if `method='log'`, the data must not be sparse. + + n_components : int, default=6 + Number of singular vectors to check. + + n_best : int, default=3 + Number of best singular vectors to which to project the data + for clustering. + + svd_method : {'randomized', 'arpack'}, default='randomized' + Selects the algorithm for finding singular vectors. May be + 'randomized' or 'arpack'. If 'randomized', uses + :func:`~sklearn.utils.extmath.randomized_svd`, which may be faster + for large matrices. If 'arpack', uses + `scipy.sparse.linalg.svds`, which is more accurate, but + possibly slower in some cases. + + n_svd_vecs : int, default=None + Number of vectors to use in calculating the SVD. Corresponds + to `ncv` when `svd_method=arpack` and `n_oversamples` when + `svd_method` is 'randomized`. + + mini_batch : bool, default=False + Whether to use mini-batch k-means, which is faster but may get + different results. + + init : {'k-means++', 'random'} or ndarray of shape (n_clusters, n_features), \ + default='k-means++' + Method for initialization of k-means algorithm; defaults to + 'k-means++'. + + n_init : int, default=10 + Number of random initializations that are tried with the + k-means algorithm. + + If mini-batch k-means is used, the best initialization is + chosen and the algorithm runs once. Otherwise, the algorithm + is run for each initialization and the best solution chosen. + + random_state : int, RandomState instance, default=None + Used for randomizing the singular value decomposition and the k-means + initialization. Use an int to make the randomness deterministic. + See :term:`Glossary `. + + Attributes + ---------- + rows_ : array-like of shape (n_row_clusters, n_rows) + Results of the clustering. `rows[i, r]` is True if + cluster `i` contains row `r`. Available only after calling ``fit``. + + columns_ : array-like of shape (n_column_clusters, n_columns) + Results of the clustering, like `rows`. + + row_labels_ : array-like of shape (n_rows,) + Row partition labels. + + column_labels_ : array-like of shape (n_cols,) + Column partition labels. + + biclusters_ : tuple of two ndarrays + The tuple contains the `rows_` and `columns_` arrays. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + SpectralCoclustering : Spectral Co-Clustering algorithm (Dhillon, 2001). + + References + ---------- + + * :doi:`Kluger, Yuval, et. al., 2003. Spectral biclustering of microarray + data: coclustering genes and conditions. + <10.1101/gr.648603>` + + Examples + -------- + >>> from sklearn.cluster import SpectralBiclustering + >>> import numpy as np + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> clustering = SpectralBiclustering(n_clusters=2, random_state=0).fit(X) + >>> clustering.row_labels_ + array([1, 1, 1, 0, 0, 0], dtype=int32) + >>> clustering.column_labels_ + array([0, 1], dtype=int32) + >>> clustering + SpectralBiclustering(n_clusters=2, random_state=0) + """ + + _parameter_constraints: dict = { + **BaseSpectral._parameter_constraints, + "n_clusters": [Interval(Integral, 1, None, closed="left"), tuple], + "method": [StrOptions({"bistochastic", "scale", "log"})], + "n_components": [Interval(Integral, 1, None, closed="left")], + "n_best": [Interval(Integral, 1, None, closed="left")], + } + + def __init__( + self, + n_clusters=3, + *, + method="bistochastic", + n_components=6, + n_best=3, + svd_method="randomized", + n_svd_vecs=None, + mini_batch=False, + init="k-means++", + n_init=10, + random_state=None, + ): + super().__init__( + n_clusters, svd_method, n_svd_vecs, mini_batch, init, n_init, random_state + ) + self.method = method + self.n_components = n_components + self.n_best = n_best + + def _check_parameters(self, n_samples): + if isinstance(self.n_clusters, Integral): + if self.n_clusters > n_samples: + raise ValueError( + f"n_clusters should be <= n_samples={n_samples}. Got" + f" {self.n_clusters} instead." + ) + else: # tuple + try: + n_row_clusters, n_column_clusters = self.n_clusters + check_scalar( + n_row_clusters, + "n_row_clusters", + target_type=Integral, + min_val=1, + max_val=n_samples, + ) + check_scalar( + n_column_clusters, + "n_column_clusters", + target_type=Integral, + min_val=1, + max_val=n_samples, + ) + except (ValueError, TypeError) as e: + raise ValueError( + "Incorrect parameter n_clusters has value:" + f" {self.n_clusters}. It should either be a single integer" + " or an iterable with two integers:" + " (n_row_clusters, n_column_clusters)" + " And the values are should be in the" + " range: (1, n_samples)" + ) from e + + if self.n_best > self.n_components: + raise ValueError( + f"n_best={self.n_best} must be <= n_components={self.n_components}." + ) + + def _fit(self, X): + n_sv = self.n_components + if self.method == "bistochastic": + normalized_data = _bistochastic_normalize(X) + n_sv += 1 + elif self.method == "scale": + normalized_data, _, _ = _scale_normalize(X) + n_sv += 1 + elif self.method == "log": + normalized_data = _log_normalize(X) + n_discard = 0 if self.method == "log" else 1 + u, v = self._svd(normalized_data, n_sv, n_discard) + ut = u.T + vt = v.T + + try: + n_row_clusters, n_col_clusters = self.n_clusters + except TypeError: + n_row_clusters = n_col_clusters = self.n_clusters + + best_ut = self._fit_best_piecewise(ut, self.n_best, n_row_clusters) + + best_vt = self._fit_best_piecewise(vt, self.n_best, n_col_clusters) + + self.row_labels_ = self._project_and_cluster(X, best_vt.T, n_row_clusters) + + self.column_labels_ = self._project_and_cluster(X.T, best_ut.T, n_col_clusters) + + self.rows_ = np.vstack( + [ + self.row_labels_ == label + for label in range(n_row_clusters) + for _ in range(n_col_clusters) + ] + ) + self.columns_ = np.vstack( + [ + self.column_labels_ == label + for _ in range(n_row_clusters) + for label in range(n_col_clusters) + ] + ) + + def _fit_best_piecewise(self, vectors, n_best, n_clusters): + """Find the ``n_best`` vectors that are best approximated by piecewise + constant vectors. + + The piecewise vectors are found by k-means; the best is chosen + according to Euclidean distance. + + """ + + def make_piecewise(v): + centroid, labels = self._k_means(v.reshape(-1, 1), n_clusters) + return centroid[labels].ravel() + + piecewise_vectors = np.apply_along_axis(make_piecewise, axis=1, arr=vectors) + dists = np.apply_along_axis(norm, axis=1, arr=(vectors - piecewise_vectors)) + result = vectors[np.argsort(dists)[:n_best]] + return result + + def _project_and_cluster(self, data, vectors, n_clusters): + """Project ``data`` to ``vectors`` and cluster the result.""" + projected = safe_sparse_dot(data, vectors) + _, labels = self._k_means(projected, n_clusters) + return labels diff --git a/videollama2/lib/python3.10/site-packages/sklearn/cluster/_feature_agglomeration.py b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_feature_agglomeration.py new file mode 100644 index 0000000000000000000000000000000000000000..457a83dd41e71076e53d1d2a296c99edb2acf9ff --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_feature_agglomeration.py @@ -0,0 +1,75 @@ +""" +Feature agglomeration. Base classes and functions for performing feature +agglomeration. +""" +# Author: V. Michel, A. Gramfort +# License: BSD 3 clause + +import numpy as np + +from ..base import TransformerMixin +from ..utils.validation import check_is_fitted +from scipy.sparse import issparse + +############################################################################### +# Mixin class for feature agglomeration. + + +class AgglomerationTransform(TransformerMixin): + """ + A class for feature agglomeration via the transform interface. + """ + + def transform(self, X): + """ + Transform a new matrix using the built clustering. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or \ + (n_samples, n_samples) + A M by N array of M observations in N dimensions or a length + M array of M one-dimensional observations. + + Returns + ------- + Y : ndarray of shape (n_samples, n_clusters) or (n_clusters,) + The pooled values for each feature cluster. + """ + check_is_fitted(self) + + X = self._validate_data(X, reset=False) + if self.pooling_func == np.mean and not issparse(X): + size = np.bincount(self.labels_) + n_samples = X.shape[0] + # a fast way to compute the mean of grouped features + nX = np.array( + [np.bincount(self.labels_, X[i, :]) / size for i in range(n_samples)] + ) + else: + nX = [ + self.pooling_func(X[:, self.labels_ == l], axis=1) + for l in np.unique(self.labels_) + ] + nX = np.array(nX).T + return nX + + def inverse_transform(self, Xred): + """ + Inverse the transformation and return a vector of size `n_features`. + + Parameters + ---------- + Xred : array-like of shape (n_samples, n_clusters) or (n_clusters,) + The values to be assigned to each cluster of samples. + + Returns + ------- + X : ndarray of shape (n_samples, n_features) or (n_features,) + A vector of size `n_samples` with the values of `Xred` assigned to + each of the cluster of samples. + """ + check_is_fitted(self) + + unil, inverse = np.unique(self.labels_, return_inverse=True) + return Xred[..., inverse] diff --git a/videollama2/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..95b2771db5be5097aeeef2981ffb36a8eee27576 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbab2dfb377c76cc63b49b08c32f7f7c3848f951b42019bc08cd41b58f02d397 +size 327769 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0dbd610be938e0d095ff9118fdd76e391fba79cd --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f2d3838bfb6b911e555204f2e11c0bc2097fe95370c871103e0b4f622b5dd059 +size 417737 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pxd b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pxd new file mode 100644 index 0000000000000000000000000000000000000000..efbf4ed3246e36002a190ca6939eca6e8153e05d --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pxd @@ -0,0 +1,19 @@ +from cython cimport floating + + +cdef floating _euclidean_dense_dense(floating*, floating*, int, bint) nogil + +cdef floating _euclidean_sparse_dense(floating[::1], int[::1], floating[::1], + floating, bint) nogil + +cpdef void _relocate_empty_clusters_dense( + floating[:, ::1], floating[::1], floating[:, ::1], + floating[:, ::1], floating[::1], int[::1]) + +cpdef void _relocate_empty_clusters_sparse( + floating[::1], int[::1], int[::1], floating[::1], floating[:, ::1], + floating[:, ::1], floating[::1], int[::1]) + +cdef void _average_centers(floating[:, ::1], floating[::1]) + +cdef void _center_shift(floating[:, ::1], floating[:, ::1], floating[::1]) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_elkan.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_elkan.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7754cecb168c9e41a311100ff4c8c33c57d5e90d --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_elkan.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edfd181e6be2fe2da302115e3d5729c53f06d0a7d66d42a19b5e21f87d37ea6d +size 431033 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/cluster/_mean_shift.py b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_mean_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..4d1837ded92f9eee508999403d57e15c4394bd32 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_mean_shift.py @@ -0,0 +1,536 @@ +"""Mean shift clustering algorithm. + +Mean shift clustering aims to discover *blobs* in a smooth density of +samples. It is a centroid based algorithm, which works by updating candidates +for centroids to be the mean of the points within a given region. These +candidates are then filtered in a post-processing stage to eliminate +near-duplicates to form the final set of centroids. + +Seeding is performed using a binning technique for scalability. +""" + +# Authors: Conrad Lee +# Alexandre Gramfort +# Gael Varoquaux +# Martino Sorbaro + +import numpy as np +import warnings +from numbers import Integral, Real + +from collections import defaultdict +from ..utils._param_validation import Interval +from ..utils.validation import check_is_fitted +from ..utils.parallel import delayed, Parallel +from ..utils import check_random_state, gen_batches, check_array +from ..base import BaseEstimator, ClusterMixin +from ..neighbors import NearestNeighbors +from ..metrics.pairwise import pairwise_distances_argmin +from .._config import config_context + + +def estimate_bandwidth(X, *, quantile=0.3, n_samples=None, random_state=0, n_jobs=None): + """Estimate the bandwidth to use with the mean-shift algorithm. + + That this function takes time at least quadratic in n_samples. For large + datasets, it's wise to set that parameter to a small value. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Input points. + + quantile : float, default=0.3 + Should be between [0, 1] + 0.5 means that the median of all pairwise distances is used. + + n_samples : int, default=None + The number of samples to use. If not given, all samples are used. + + random_state : int, RandomState instance, default=None + The generator used to randomly select the samples from input points + for bandwidth estimation. Use an int to make the randomness + deterministic. + See :term:`Glossary `. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Returns + ------- + bandwidth : float + The bandwidth parameter. + """ + X = check_array(X) + + random_state = check_random_state(random_state) + if n_samples is not None: + idx = random_state.permutation(X.shape[0])[:n_samples] + X = X[idx] + n_neighbors = int(X.shape[0] * quantile) + if n_neighbors < 1: # cannot fit NearestNeighbors with n_neighbors = 0 + n_neighbors = 1 + nbrs = NearestNeighbors(n_neighbors=n_neighbors, n_jobs=n_jobs) + nbrs.fit(X) + + bandwidth = 0.0 + for batch in gen_batches(len(X), 500): + d, _ = nbrs.kneighbors(X[batch, :], return_distance=True) + bandwidth += np.max(d, axis=1).sum() + + return bandwidth / X.shape[0] + + +# separate function for each seed's iterative loop +def _mean_shift_single_seed(my_mean, X, nbrs, max_iter): + # For each seed, climb gradient until convergence or max_iter + bandwidth = nbrs.get_params()["radius"] + stop_thresh = 1e-3 * bandwidth # when mean has converged + completed_iterations = 0 + while True: + # Find mean of points within bandwidth + i_nbrs = nbrs.radius_neighbors([my_mean], bandwidth, return_distance=False)[0] + points_within = X[i_nbrs] + if len(points_within) == 0: + break # Depending on seeding strategy this condition may occur + my_old_mean = my_mean # save the old mean + my_mean = np.mean(points_within, axis=0) + # If converged or at max_iter, adds the cluster + if ( + np.linalg.norm(my_mean - my_old_mean) < stop_thresh + or completed_iterations == max_iter + ): + break + completed_iterations += 1 + return tuple(my_mean), len(points_within), completed_iterations + + +def mean_shift( + X, + *, + bandwidth=None, + seeds=None, + bin_seeding=False, + min_bin_freq=1, + cluster_all=True, + max_iter=300, + n_jobs=None, +): + """Perform mean shift clustering of data using a flat kernel. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + + X : array-like of shape (n_samples, n_features) + Input data. + + bandwidth : float, default=None + Kernel bandwidth. + + If bandwidth is not given, it is determined using a heuristic based on + the median of all pairwise distances. This will take quadratic time in + the number of samples. The sklearn.cluster.estimate_bandwidth function + can be used to do this more efficiently. + + seeds : array-like of shape (n_seeds, n_features) or None + Point used as initial kernel locations. If None and bin_seeding=False, + each data point is used as a seed. If None and bin_seeding=True, + see bin_seeding. + + bin_seeding : bool, default=False + If true, initial kernel locations are not locations of all + points, but rather the location of the discretized version of + points, where points are binned onto a grid whose coarseness + corresponds to the bandwidth. Setting this option to True will speed + up the algorithm because fewer seeds will be initialized. + Ignored if seeds argument is not None. + + min_bin_freq : int, default=1 + To speed up the algorithm, accept only those bins with at least + min_bin_freq points as seeds. + + cluster_all : bool, default=True + If true, then all points are clustered, even those orphans that are + not within any kernel. Orphans are assigned to the nearest kernel. + If false, then orphans are given cluster label -1. + + max_iter : int, default=300 + Maximum number of iterations, per seed point before the clustering + operation terminates (for that seed point), if has not converged yet. + + n_jobs : int, default=None + The number of jobs to use for the computation. The following tasks benefit + from the parallelization: + + - The search of nearest neighbors for bandwidth estimation and label + assignments. See the details in the docstring of the + ``NearestNeighbors`` class. + - Hill-climbing optimization for all seeds. + + See :term:`Glossary ` for more details. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + .. versionadded:: 0.17 + Parallel Execution using *n_jobs*. + + Returns + ------- + + cluster_centers : ndarray of shape (n_clusters, n_features) + Coordinates of cluster centers. + + labels : ndarray of shape (n_samples,) + Cluster labels for each point. + + Notes + ----- + For an example, see :ref:`examples/cluster/plot_mean_shift.py + `. + """ + model = MeanShift( + bandwidth=bandwidth, + seeds=seeds, + min_bin_freq=min_bin_freq, + bin_seeding=bin_seeding, + cluster_all=cluster_all, + n_jobs=n_jobs, + max_iter=max_iter, + ).fit(X) + return model.cluster_centers_, model.labels_ + + +def get_bin_seeds(X, bin_size, min_bin_freq=1): + """Find seeds for mean_shift. + + Finds seeds by first binning data onto a grid whose lines are + spaced bin_size apart, and then choosing those bins with at least + min_bin_freq points. + + Parameters + ---------- + + X : array-like of shape (n_samples, n_features) + Input points, the same points that will be used in mean_shift. + + bin_size : float + Controls the coarseness of the binning. Smaller values lead + to more seeding (which is computationally more expensive). If you're + not sure how to set this, set it to the value of the bandwidth used + in clustering.mean_shift. + + min_bin_freq : int, default=1 + Only bins with at least min_bin_freq will be selected as seeds. + Raising this value decreases the number of seeds found, which + makes mean_shift computationally cheaper. + + Returns + ------- + bin_seeds : array-like of shape (n_samples, n_features) + Points used as initial kernel positions in clustering.mean_shift. + """ + if bin_size == 0: + return X + + # Bin points + bin_sizes = defaultdict(int) + for point in X: + binned_point = np.round(point / bin_size) + bin_sizes[tuple(binned_point)] += 1 + + # Select only those bins as seeds which have enough members + bin_seeds = np.array( + [point for point, freq in bin_sizes.items() if freq >= min_bin_freq], + dtype=np.float32, + ) + if len(bin_seeds) == len(X): + warnings.warn( + "Binning data failed with provided bin_size=%f, using data points as seeds." + % bin_size + ) + return X + bin_seeds = bin_seeds * bin_size + return bin_seeds + + +class MeanShift(ClusterMixin, BaseEstimator): + """Mean shift clustering using a flat kernel. + + Mean shift clustering aims to discover "blobs" in a smooth density of + samples. It is a centroid-based algorithm, which works by updating + candidates for centroids to be the mean of the points within a given + region. These candidates are then filtered in a post-processing stage to + eliminate near-duplicates to form the final set of centroids. + + Seeding is performed using a binning technique for scalability. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + bandwidth : float, default=None + Bandwidth used in the flat kernel. + + If not given, the bandwidth is estimated using + sklearn.cluster.estimate_bandwidth; see the documentation for that + function for hints on scalability (see also the Notes, below). + + seeds : array-like of shape (n_samples, n_features), default=None + Seeds used to initialize kernels. If not set, + the seeds are calculated by clustering.get_bin_seeds + with bandwidth as the grid size and default values for + other parameters. + + bin_seeding : bool, default=False + If true, initial kernel locations are not locations of all + points, but rather the location of the discretized version of + points, where points are binned onto a grid whose coarseness + corresponds to the bandwidth. Setting this option to True will speed + up the algorithm because fewer seeds will be initialized. + The default value is False. + Ignored if seeds argument is not None. + + min_bin_freq : int, default=1 + To speed up the algorithm, accept only those bins with at least + min_bin_freq points as seeds. + + cluster_all : bool, default=True + If true, then all points are clustered, even those orphans that are + not within any kernel. Orphans are assigned to the nearest kernel. + If false, then orphans are given cluster label -1. + + n_jobs : int, default=None + The number of jobs to use for the computation. The following tasks benefit + from the parallelization: + + - The search of nearest neighbors for bandwidth estimation and label + assignments. See the details in the docstring of the + ``NearestNeighbors`` class. + - Hill-climbing optimization for all seeds. + + See :term:`Glossary ` for more details. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + max_iter : int, default=300 + Maximum number of iterations, per seed point before the clustering + operation terminates (for that seed point), if has not converged yet. + + .. versionadded:: 0.22 + + Attributes + ---------- + cluster_centers_ : ndarray of shape (n_clusters, n_features) + Coordinates of cluster centers. + + labels_ : ndarray of shape (n_samples,) + Labels of each point. + + n_iter_ : int + Maximum number of iterations performed on each seed. + + .. versionadded:: 0.22 + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + KMeans : K-Means clustering. + + Notes + ----- + + Scalability: + + Because this implementation uses a flat kernel and + a Ball Tree to look up members of each kernel, the complexity will tend + towards O(T*n*log(n)) in lower dimensions, with n the number of samples + and T the number of points. In higher dimensions the complexity will + tend towards O(T*n^2). + + Scalability can be boosted by using fewer seeds, for example by using + a higher value of min_bin_freq in the get_bin_seeds function. + + Note that the estimate_bandwidth function is much less scalable than the + mean shift algorithm and will be the bottleneck if it is used. + + References + ---------- + + Dorin Comaniciu and Peter Meer, "Mean Shift: A robust approach toward + feature space analysis". IEEE Transactions on Pattern Analysis and + Machine Intelligence. 2002. pp. 603-619. + + Examples + -------- + >>> from sklearn.cluster import MeanShift + >>> import numpy as np + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> clustering = MeanShift(bandwidth=2).fit(X) + >>> clustering.labels_ + array([1, 1, 1, 0, 0, 0]) + >>> clustering.predict([[0, 0], [5, 5]]) + array([1, 0]) + >>> clustering + MeanShift(bandwidth=2) + """ + + _parameter_constraints: dict = { + "bandwidth": [Interval(Real, 0, None, closed="neither"), None], + "seeds": ["array-like", None], + "bin_seeding": ["boolean"], + "min_bin_freq": [Interval(Integral, 1, None, closed="left")], + "cluster_all": ["boolean"], + "n_jobs": [Integral, None], + "max_iter": [Interval(Integral, 0, None, closed="left")], + } + + def __init__( + self, + *, + bandwidth=None, + seeds=None, + bin_seeding=False, + min_bin_freq=1, + cluster_all=True, + n_jobs=None, + max_iter=300, + ): + self.bandwidth = bandwidth + self.seeds = seeds + self.bin_seeding = bin_seeding + self.cluster_all = cluster_all + self.min_bin_freq = min_bin_freq + self.n_jobs = n_jobs + self.max_iter = max_iter + + def fit(self, X, y=None): + """Perform clustering. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Samples to cluster. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + Fitted instance. + """ + self._validate_params() + X = self._validate_data(X) + bandwidth = self.bandwidth + if bandwidth is None: + bandwidth = estimate_bandwidth(X, n_jobs=self.n_jobs) + + seeds = self.seeds + if seeds is None: + if self.bin_seeding: + seeds = get_bin_seeds(X, bandwidth, self.min_bin_freq) + else: + seeds = X + n_samples, n_features = X.shape + center_intensity_dict = {} + + # We use n_jobs=1 because this will be used in nested calls under + # parallel calls to _mean_shift_single_seed so there is no need for + # for further parallelism. + nbrs = NearestNeighbors(radius=bandwidth, n_jobs=1).fit(X) + + # execute iterations on all seeds in parallel + all_res = Parallel(n_jobs=self.n_jobs)( + delayed(_mean_shift_single_seed)(seed, X, nbrs, self.max_iter) + for seed in seeds + ) + # copy results in a dictionary + for i in range(len(seeds)): + if all_res[i][1]: # i.e. len(points_within) > 0 + center_intensity_dict[all_res[i][0]] = all_res[i][1] + + self.n_iter_ = max([x[2] for x in all_res]) + + if not center_intensity_dict: + # nothing near seeds + raise ValueError( + "No point was within bandwidth=%f of any seed. Try a different seeding" + " strategy or increase the bandwidth." + % bandwidth + ) + + # POST PROCESSING: remove near duplicate points + # If the distance between two kernels is less than the bandwidth, + # then we have to remove one because it is a duplicate. Remove the + # one with fewer points. + + sorted_by_intensity = sorted( + center_intensity_dict.items(), + key=lambda tup: (tup[1], tup[0]), + reverse=True, + ) + sorted_centers = np.array([tup[0] for tup in sorted_by_intensity]) + unique = np.ones(len(sorted_centers), dtype=bool) + nbrs = NearestNeighbors(radius=bandwidth, n_jobs=self.n_jobs).fit( + sorted_centers + ) + for i, center in enumerate(sorted_centers): + if unique[i]: + neighbor_idxs = nbrs.radius_neighbors([center], return_distance=False)[ + 0 + ] + unique[neighbor_idxs] = 0 + unique[i] = 1 # leave the current point as unique + cluster_centers = sorted_centers[unique] + + # ASSIGN LABELS: a point belongs to the cluster that it is closest to + nbrs = NearestNeighbors(n_neighbors=1, n_jobs=self.n_jobs).fit(cluster_centers) + labels = np.zeros(n_samples, dtype=int) + distances, idxs = nbrs.kneighbors(X) + if self.cluster_all: + labels = idxs.flatten() + else: + labels.fill(-1) + bool_selector = distances.flatten() <= bandwidth + labels[bool_selector] = idxs.flatten()[bool_selector] + + self.cluster_centers_, self.labels_ = cluster_centers, labels + return self + + def predict(self, X): + """Predict the closest cluster each sample in X belongs to. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + New data to predict. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Index of the cluster each sample belongs to. + """ + check_is_fitted(self) + X = self._validate_data(X, reset=False) + with config_context(assume_finite=True): + return pairwise_distances_argmin(X, self.cluster_centers_) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/cluster/_spectral.py b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_spectral.py new file mode 100644 index 0000000000000000000000000000000000000000..25f5ee7f9453cf002eeb3e6df99ed627ebd8184b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/cluster/_spectral.py @@ -0,0 +1,791 @@ +"""Algorithms for spectral clustering""" + +# Author: Gael Varoquaux +# Brian Cheung +# Wei LI +# Andrew Knyazev +# License: BSD 3 clause + +from numbers import Integral, Real +import warnings + +import numpy as np + +from scipy.linalg import LinAlgError, qr, svd +from scipy.sparse import csc_matrix + +from ..base import BaseEstimator, ClusterMixin +from ..utils._param_validation import Interval, StrOptions +from ..utils import check_random_state, as_float_array +from ..metrics.pairwise import pairwise_kernels, KERNEL_PARAMS +from ..neighbors import kneighbors_graph, NearestNeighbors +from ..manifold import spectral_embedding +from ._kmeans import k_means + + +def cluster_qr(vectors): + """Find the discrete partition closest to the eigenvector embedding. + + This implementation was proposed in [1]_. + + .. versionadded:: 1.1 + + Parameters + ---------- + vectors : array-like, shape: (n_samples, n_clusters) + The embedding space of the samples. + + Returns + ------- + labels : array of integers, shape: n_samples + The cluster labels of vectors. + + References + ---------- + .. [1] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019 + Anil Damle, Victor Minden, Lexing Ying + <10.1093/imaiai/iay008>` + + """ + + k = vectors.shape[1] + _, _, piv = qr(vectors.T, pivoting=True) + ut, _, v = svd(vectors[piv[:k], :].T) + vectors = abs(np.dot(vectors, np.dot(ut, v.conj()))) + return vectors.argmax(axis=1) + + +def discretize( + vectors, *, copy=True, max_svd_restarts=30, n_iter_max=20, random_state=None +): + """Search for a partition matrix which is closest to the eigenvector embedding. + + This implementation was proposed in [1]_. + + Parameters + ---------- + vectors : array-like of shape (n_samples, n_clusters) + The embedding space of the samples. + + copy : bool, default=True + Whether to copy vectors, or perform in-place normalization. + + max_svd_restarts : int, default=30 + Maximum number of attempts to restart SVD if convergence fails + + n_iter_max : int, default=30 + Maximum number of iterations to attempt in rotation and partition + matrix search if machine precision convergence is not reached + + random_state : int, RandomState instance, default=None + Determines random number generation for rotation matrix initialization. + Use an int to make the randomness deterministic. + See :term:`Glossary `. + + Returns + ------- + labels : array of integers, shape: n_samples + The labels of the clusters. + + References + ---------- + + .. [1] `Multiclass spectral clustering, 2003 + Stella X. Yu, Jianbo Shi + `_ + + Notes + ----- + + The eigenvector embedding is used to iteratively search for the + closest discrete partition. First, the eigenvector embedding is + normalized to the space of partition matrices. An optimal discrete + partition matrix closest to this normalized embedding multiplied by + an initial rotation is calculated. Fixing this discrete partition + matrix, an optimal rotation matrix is calculated. These two + calculations are performed until convergence. The discrete partition + matrix is returned as the clustering solution. Used in spectral + clustering, this method tends to be faster and more robust to random + initialization than k-means. + + """ + + random_state = check_random_state(random_state) + + vectors = as_float_array(vectors, copy=copy) + + eps = np.finfo(float).eps + n_samples, n_components = vectors.shape + + # Normalize the eigenvectors to an equal length of a vector of ones. + # Reorient the eigenvectors to point in the negative direction with respect + # to the first element. This may have to do with constraining the + # eigenvectors to lie in a specific quadrant to make the discretization + # search easier. + norm_ones = np.sqrt(n_samples) + for i in range(vectors.shape[1]): + vectors[:, i] = (vectors[:, i] / np.linalg.norm(vectors[:, i])) * norm_ones + if vectors[0, i] != 0: + vectors[:, i] = -1 * vectors[:, i] * np.sign(vectors[0, i]) + + # Normalize the rows of the eigenvectors. Samples should lie on the unit + # hypersphere centered at the origin. This transforms the samples in the + # embedding space to the space of partition matrices. + vectors = vectors / np.sqrt((vectors**2).sum(axis=1))[:, np.newaxis] + + svd_restarts = 0 + has_converged = False + + # If there is an exception we try to randomize and rerun SVD again + # do this max_svd_restarts times. + while (svd_restarts < max_svd_restarts) and not has_converged: + + # Initialize first column of rotation matrix with a row of the + # eigenvectors + rotation = np.zeros((n_components, n_components)) + rotation[:, 0] = vectors[random_state.randint(n_samples), :].T + + # To initialize the rest of the rotation matrix, find the rows + # of the eigenvectors that are as orthogonal to each other as + # possible + c = np.zeros(n_samples) + for j in range(1, n_components): + # Accumulate c to ensure row is as orthogonal as possible to + # previous picks as well as current one + c += np.abs(np.dot(vectors, rotation[:, j - 1])) + rotation[:, j] = vectors[c.argmin(), :].T + + last_objective_value = 0.0 + n_iter = 0 + + while not has_converged: + n_iter += 1 + + t_discrete = np.dot(vectors, rotation) + + labels = t_discrete.argmax(axis=1) + vectors_discrete = csc_matrix( + (np.ones(len(labels)), (np.arange(0, n_samples), labels)), + shape=(n_samples, n_components), + ) + + t_svd = vectors_discrete.T * vectors + + try: + U, S, Vh = np.linalg.svd(t_svd) + except LinAlgError: + svd_restarts += 1 + print("SVD did not converge, randomizing and trying again") + break + + ncut_value = 2.0 * (n_samples - S.sum()) + if (abs(ncut_value - last_objective_value) < eps) or (n_iter > n_iter_max): + has_converged = True + else: + # otherwise calculate rotation and continue + last_objective_value = ncut_value + rotation = np.dot(Vh.T, U.T) + + if not has_converged: + raise LinAlgError("SVD did not converge") + return labels + + +def spectral_clustering( + affinity, + *, + n_clusters=8, + n_components=None, + eigen_solver=None, + random_state=None, + n_init=10, + eigen_tol="auto", + assign_labels="kmeans", + verbose=False, +): + """Apply clustering to a projection of the normalized Laplacian. + + In practice Spectral Clustering is very useful when the structure of + the individual clusters is highly non-convex or more generally when + a measure of the center and spread of the cluster is not a suitable + description of the complete cluster. For instance, when clusters are + nested circles on the 2D plane. + + If affinity is the adjacency matrix of a graph, this method can be + used to find normalized graph cuts [1]_, [2]_. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + affinity : {array-like, sparse matrix} of shape (n_samples, n_samples) + The affinity matrix describing the relationship of the samples to + embed. **Must be symmetric**. + + Possible examples: + - adjacency matrix of a graph, + - heat kernel of the pairwise distance matrix of the samples, + - symmetric k-nearest neighbours connectivity matrix of the samples. + + n_clusters : int, default=None + Number of clusters to extract. + + n_components : int, default=n_clusters + Number of eigenvectors to use for the spectral embedding. + + eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'} + The eigenvalue decomposition method. If None then ``'arpack'`` is used. + See [4]_ for more details regarding ``'lobpcg'``. + Eigensolver ``'amg'`` runs ``'lobpcg'`` with optional + Algebraic MultiGrid preconditioning and requires pyamg to be installed. + It can be faster on very large sparse problems [6]_ and [7]_. + + random_state : int, RandomState instance, default=None + A pseudo random number generator used for the initialization + of the lobpcg eigenvectors decomposition when `eigen_solver == + 'amg'`, and for the K-Means initialization. Use an int to make + the results deterministic across calls (See + :term:`Glossary `). + + .. note:: + When using `eigen_solver == 'amg'`, + it is necessary to also fix the global numpy seed with + `np.random.seed(int)` to get deterministic results. See + https://github.com/pyamg/pyamg/issues/139 for further + information. + + n_init : int, default=10 + Number of time the k-means algorithm will be run with different + centroid seeds. The final results will be the best output of n_init + consecutive runs in terms of inertia. Only used if + ``assign_labels='kmeans'``. + + eigen_tol : float, default="auto" + Stopping criterion for eigendecomposition of the Laplacian matrix. + If `eigen_tol="auto"` then the passed tolerance will depend on the + `eigen_solver`: + + - If `eigen_solver="arpack"`, then `eigen_tol=0.0`; + - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then + `eigen_tol=None` which configures the underlying `lobpcg` solver to + automatically resolve the value according to their heuristics. See, + :func:`scipy.sparse.linalg.lobpcg` for details. + + Note that when using `eigen_solver="lobpcg"` or `eigen_solver="amg"` + values of `tol<1e-5` may lead to convergence issues and should be + avoided. + + .. versionadded:: 1.2 + Added 'auto' option. + + assign_labels : {'kmeans', 'discretize', 'cluster_qr'}, default='kmeans' + The strategy to use to assign labels in the embedding + space. There are three ways to assign labels after the Laplacian + embedding. k-means can be applied and is a popular choice. But it can + also be sensitive to initialization. Discretization is another + approach which is less sensitive to random initialization [3]_. + The cluster_qr method [5]_ directly extracts clusters from eigenvectors + in spectral clustering. In contrast to k-means and discretization, cluster_qr + has no tuning parameters and is not an iterative method, yet may outperform + k-means and discretization in terms of both quality and speed. + + .. versionchanged:: 1.1 + Added new labeling method 'cluster_qr'. + + verbose : bool, default=False + Verbosity mode. + + .. versionadded:: 0.24 + + Returns + ------- + labels : array of integers, shape: n_samples + The labels of the clusters. + + Notes + ----- + The graph should contain only one connected component, elsewhere + the results make little sense. + + This algorithm solves the normalized cut for `k=2`: it is a + normalized spectral clustering. + + References + ---------- + + .. [1] :doi:`Normalized cuts and image segmentation, 2000 + Jianbo Shi, Jitendra Malik + <10.1109/34.868688>` + + .. [2] :doi:`A Tutorial on Spectral Clustering, 2007 + Ulrike von Luxburg + <10.1007/s11222-007-9033-z>` + + .. [3] `Multiclass spectral clustering, 2003 + Stella X. Yu, Jianbo Shi + `_ + + .. [4] :doi:`Toward the Optimal Preconditioned Eigensolver: + Locally Optimal Block Preconditioned Conjugate Gradient Method, 2001 + A. V. Knyazev + SIAM Journal on Scientific Computing 23, no. 2, pp. 517-541. + <10.1137/S1064827500366124>` + + .. [5] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019 + Anil Damle, Victor Minden, Lexing Ying + <10.1093/imaiai/iay008>` + + .. [6] :doi:`Multiscale Spectral Image Segmentation Multiscale preconditioning + for computing eigenvalues of graph Laplacians in image segmentation, 2006 + Andrew Knyazev + <10.13140/RG.2.2.35280.02565>` + + .. [7] :doi:`Preconditioned spectral clustering for stochastic block partition + streaming graph challenge (Preliminary version at arXiv.) + David Zhuzhunashvili, Andrew Knyazev + <10.1109/HPEC.2017.8091045>` + """ + if assign_labels not in ("kmeans", "discretize", "cluster_qr"): + raise ValueError( + "The 'assign_labels' parameter should be " + "'kmeans' or 'discretize', or 'cluster_qr', " + f"but {assign_labels!r} was given" + ) + if isinstance(affinity, np.matrix): + raise TypeError( + "spectral_clustering does not support passing in affinity as an " + "np.matrix. Please convert to a numpy array with np.asarray. For " + "more information see: " + "https://numpy.org/doc/stable/reference/generated/numpy.matrix.html", # noqa + ) + + random_state = check_random_state(random_state) + n_components = n_clusters if n_components is None else n_components + + # We now obtain the real valued solution matrix to the + # relaxed Ncut problem, solving the eigenvalue problem + # L_sym x = lambda x and recovering u = D^-1/2 x. + # The first eigenvector is constant only for fully connected graphs + # and should be kept for spectral clustering (drop_first = False) + # See spectral_embedding documentation. + maps = spectral_embedding( + affinity, + n_components=n_components, + eigen_solver=eigen_solver, + random_state=random_state, + eigen_tol=eigen_tol, + drop_first=False, + ) + if verbose: + print(f"Computing label assignment using {assign_labels}") + + if assign_labels == "kmeans": + _, labels, _ = k_means( + maps, n_clusters, random_state=random_state, n_init=n_init, verbose=verbose + ) + elif assign_labels == "cluster_qr": + labels = cluster_qr(maps) + else: + labels = discretize(maps, random_state=random_state) + + return labels + + +class SpectralClustering(ClusterMixin, BaseEstimator): + """Apply clustering to a projection of the normalized Laplacian. + + In practice Spectral Clustering is very useful when the structure of + the individual clusters is highly non-convex, or more generally when + a measure of the center and spread of the cluster is not a suitable + description of the complete cluster, such as when clusters are + nested circles on the 2D plane. + + If the affinity matrix is the adjacency matrix of a graph, this method + can be used to find normalized graph cuts [1]_, [2]_. + + When calling ``fit``, an affinity matrix is constructed using either + a kernel function such the Gaussian (aka RBF) kernel with Euclidean + distance ``d(X, X)``:: + + np.exp(-gamma * d(X,X) ** 2) + + or a k-nearest neighbors connectivity matrix. + + Alternatively, a user-provided affinity matrix can be specified by + setting ``affinity='precomputed'``. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_clusters : int, default=8 + The dimension of the projection subspace. + + eigen_solver : {'arpack', 'lobpcg', 'amg'}, default=None + The eigenvalue decomposition strategy to use. AMG requires pyamg + to be installed. It can be faster on very large, sparse problems, + but may also lead to instabilities. If None, then ``'arpack'`` is + used. See [4]_ for more details regarding `'lobpcg'`. + + n_components : int, default=None + Number of eigenvectors to use for the spectral embedding. If None, + defaults to `n_clusters`. + + random_state : int, RandomState instance, default=None + A pseudo random number generator used for the initialization + of the lobpcg eigenvectors decomposition when `eigen_solver == + 'amg'`, and for the K-Means initialization. Use an int to make + the results deterministic across calls (See + :term:`Glossary `). + + .. note:: + When using `eigen_solver == 'amg'`, + it is necessary to also fix the global numpy seed with + `np.random.seed(int)` to get deterministic results. See + https://github.com/pyamg/pyamg/issues/139 for further + information. + + n_init : int, default=10 + Number of time the k-means algorithm will be run with different + centroid seeds. The final results will be the best output of n_init + consecutive runs in terms of inertia. Only used if + ``assign_labels='kmeans'``. + + gamma : float, default=1.0 + Kernel coefficient for rbf, poly, sigmoid, laplacian and chi2 kernels. + Ignored for ``affinity='nearest_neighbors'``. + + affinity : str or callable, default='rbf' + How to construct the affinity matrix. + - 'nearest_neighbors': construct the affinity matrix by computing a + graph of nearest neighbors. + - 'rbf': construct the affinity matrix using a radial basis function + (RBF) kernel. + - 'precomputed': interpret ``X`` as a precomputed affinity matrix, + where larger values indicate greater similarity between instances. + - 'precomputed_nearest_neighbors': interpret ``X`` as a sparse graph + of precomputed distances, and construct a binary affinity matrix + from the ``n_neighbors`` nearest neighbors of each instance. + - one of the kernels supported by + :func:`~sklearn.metrics.pairwise_kernels`. + + Only kernels that produce similarity scores (non-negative values that + increase with similarity) should be used. This property is not checked + by the clustering algorithm. + + n_neighbors : int, default=10 + Number of neighbors to use when constructing the affinity matrix using + the nearest neighbors method. Ignored for ``affinity='rbf'``. + + eigen_tol : float, default="auto" + Stopping criterion for eigendecomposition of the Laplacian matrix. + If `eigen_tol="auto"` then the passed tolerance will depend on the + `eigen_solver`: + + - If `eigen_solver="arpack"`, then `eigen_tol=0.0`; + - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then + `eigen_tol=None` which configures the underlying `lobpcg` solver to + automatically resolve the value according to their heuristics. See, + :func:`scipy.sparse.linalg.lobpcg` for details. + + Note that when using `eigen_solver="lobpcg"` or `eigen_solver="amg"` + values of `tol<1e-5` may lead to convergence issues and should be + avoided. + + .. versionadded:: 1.2 + Added 'auto' option. + + assign_labels : {'kmeans', 'discretize', 'cluster_qr'}, default='kmeans' + The strategy for assigning labels in the embedding space. There are two + ways to assign labels after the Laplacian embedding. k-means is a + popular choice, but it can be sensitive to initialization. + Discretization is another approach which is less sensitive to random + initialization [3]_. + The cluster_qr method [5]_ directly extract clusters from eigenvectors + in spectral clustering. In contrast to k-means and discretization, cluster_qr + has no tuning parameters and runs no iterations, yet may outperform + k-means and discretization in terms of both quality and speed. + + .. versionchanged:: 1.1 + Added new labeling method 'cluster_qr'. + + degree : float, default=3 + Degree of the polynomial kernel. Ignored by other kernels. + + coef0 : float, default=1 + Zero coefficient for polynomial and sigmoid kernels. + Ignored by other kernels. + + kernel_params : dict of str to any, default=None + Parameters (keyword arguments) and values for kernel passed as + callable object. Ignored by other kernels. + + n_jobs : int, default=None + The number of parallel jobs to run when `affinity='nearest_neighbors'` + or `affinity='precomputed_nearest_neighbors'`. The neighbors search + will be done in parallel. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + verbose : bool, default=False + Verbosity mode. + + .. versionadded:: 0.24 + + Attributes + ---------- + affinity_matrix_ : array-like of shape (n_samples, n_samples) + Affinity matrix used for clustering. Available only after calling + ``fit``. + + labels_ : ndarray of shape (n_samples,) + Labels of each point + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + sklearn.cluster.KMeans : K-Means clustering. + sklearn.cluster.DBSCAN : Density-Based Spatial Clustering of + Applications with Noise. + + Notes + ----- + A distance matrix for which 0 indicates identical elements and high values + indicate very dissimilar elements can be transformed into an affinity / + similarity matrix that is well-suited for the algorithm by + applying the Gaussian (aka RBF, heat) kernel:: + + np.exp(- dist_matrix ** 2 / (2. * delta ** 2)) + + where ``delta`` is a free parameter representing the width of the Gaussian + kernel. + + An alternative is to take a symmetric version of the k-nearest neighbors + connectivity matrix of the points. + + If the pyamg package is installed, it is used: this greatly + speeds up computation. + + References + ---------- + .. [1] :doi:`Normalized cuts and image segmentation, 2000 + Jianbo Shi, Jitendra Malik + <10.1109/34.868688>` + + .. [2] :doi:`A Tutorial on Spectral Clustering, 2007 + Ulrike von Luxburg + <10.1007/s11222-007-9033-z>` + + .. [3] `Multiclass spectral clustering, 2003 + Stella X. Yu, Jianbo Shi + `_ + + .. [4] :doi:`Toward the Optimal Preconditioned Eigensolver: + Locally Optimal Block Preconditioned Conjugate Gradient Method, 2001 + A. V. Knyazev + SIAM Journal on Scientific Computing 23, no. 2, pp. 517-541. + <10.1137/S1064827500366124>` + + .. [5] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019 + Anil Damle, Victor Minden, Lexing Ying + <10.1093/imaiai/iay008>` + + Examples + -------- + >>> from sklearn.cluster import SpectralClustering + >>> import numpy as np + >>> X = np.array([[1, 1], [2, 1], [1, 0], + ... [4, 7], [3, 5], [3, 6]]) + >>> clustering = SpectralClustering(n_clusters=2, + ... assign_labels='discretize', + ... random_state=0).fit(X) + >>> clustering.labels_ + array([1, 1, 1, 0, 0, 0]) + >>> clustering + SpectralClustering(assign_labels='discretize', n_clusters=2, + random_state=0) + """ + + _parameter_constraints: dict = { + "n_clusters": [Interval(Integral, 1, None, closed="left")], + "eigen_solver": [StrOptions({"arpack", "lobpcg", "amg"}), None], + "n_components": [Interval(Integral, 1, None, closed="left"), None], + "random_state": ["random_state"], + "n_init": [Interval(Integral, 1, None, closed="left")], + "gamma": [Interval(Real, 0, None, closed="left")], + "affinity": [ + callable, + StrOptions( + set(KERNEL_PARAMS) + | {"nearest_neighbors", "precomputed", "precomputed_nearest_neighbors"} + ), + ], + "n_neighbors": [Interval(Integral, 1, None, closed="left")], + "eigen_tol": [ + Interval(Real, 0.0, None, closed="left"), + StrOptions({"auto"}), + ], + "assign_labels": [StrOptions({"kmeans", "discretize", "cluster_qr"})], + "degree": [Interval(Integral, 0, None, closed="left")], + "coef0": [Interval(Real, None, None, closed="neither")], + "kernel_params": [dict, None], + "n_jobs": [Integral, None], + "verbose": ["verbose"], + } + + def __init__( + self, + n_clusters=8, + *, + eigen_solver=None, + n_components=None, + random_state=None, + n_init=10, + gamma=1.0, + affinity="rbf", + n_neighbors=10, + eigen_tol="auto", + assign_labels="kmeans", + degree=3, + coef0=1, + kernel_params=None, + n_jobs=None, + verbose=False, + ): + self.n_clusters = n_clusters + self.eigen_solver = eigen_solver + self.n_components = n_components + self.random_state = random_state + self.n_init = n_init + self.gamma = gamma + self.affinity = affinity + self.n_neighbors = n_neighbors + self.eigen_tol = eigen_tol + self.assign_labels = assign_labels + self.degree = degree + self.coef0 = coef0 + self.kernel_params = kernel_params + self.n_jobs = n_jobs + self.verbose = verbose + + def fit(self, X, y=None): + """Perform spectral clustering from features, or affinity matrix. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) + Training instances to cluster, similarities / affinities between + instances if ``affinity='precomputed'``, or distances between + instances if ``affinity='precomputed_nearest_neighbors``. If a + sparse matrix is provided in a format other than ``csr_matrix``, + ``csc_matrix``, or ``coo_matrix``, it will be converted into a + sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + A fitted instance of the estimator. + """ + self._validate_params() + + X = self._validate_data( + X, + accept_sparse=["csr", "csc", "coo"], + dtype=np.float64, + ensure_min_samples=2, + ) + allow_squared = self.affinity in [ + "precomputed", + "precomputed_nearest_neighbors", + ] + if X.shape[0] == X.shape[1] and not allow_squared: + warnings.warn( + "The spectral clustering API has changed. ``fit``" + "now constructs an affinity matrix from data. To use" + " a custom affinity matrix, " + "set ``affinity=precomputed``." + ) + + if self.affinity == "nearest_neighbors": + connectivity = kneighbors_graph( + X, n_neighbors=self.n_neighbors, include_self=True, n_jobs=self.n_jobs + ) + self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T) + elif self.affinity == "precomputed_nearest_neighbors": + estimator = NearestNeighbors( + n_neighbors=self.n_neighbors, n_jobs=self.n_jobs, metric="precomputed" + ).fit(X) + connectivity = estimator.kneighbors_graph(X=X, mode="connectivity") + self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T) + elif self.affinity == "precomputed": + self.affinity_matrix_ = X + else: + params = self.kernel_params + if params is None: + params = {} + if not callable(self.affinity): + params["gamma"] = self.gamma + params["degree"] = self.degree + params["coef0"] = self.coef0 + self.affinity_matrix_ = pairwise_kernels( + X, metric=self.affinity, filter_params=True, **params + ) + + random_state = check_random_state(self.random_state) + self.labels_ = spectral_clustering( + self.affinity_matrix_, + n_clusters=self.n_clusters, + n_components=self.n_components, + eigen_solver=self.eigen_solver, + random_state=random_state, + n_init=self.n_init, + eigen_tol=self.eigen_tol, + assign_labels=self.assign_labels, + verbose=self.verbose, + ) + return self + + def fit_predict(self, X, y=None): + """Perform spectral clustering on `X` and return cluster labels. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) + Training instances to cluster, similarities / affinities between + instances if ``affinity='precomputed'``, or distances between + instances if ``affinity='precomputed_nearest_neighbors``. If a + sparse matrix is provided in a format other than ``csr_matrix``, + ``csc_matrix``, or ``coo_matrix``, it will be converted into a + sparse ``csr_matrix``. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + labels : ndarray of shape (n_samples,) + Cluster labels. + """ + return super().fit_predict(X, y) + + def _more_tags(self): + return { + "pairwise": self.affinity + in ["precomputed", "precomputed_nearest_neighbors"] + } diff --git a/videollama2/lib/python3.10/site-packages/sklearn/ensemble/__pycache__/_base.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/ensemble/__pycache__/_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fb55dccb77bf4193f614261d8135e31c0e4388c Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/ensemble/__pycache__/_base.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/ensemble/__pycache__/_iforest.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/ensemble/__pycache__/_iforest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f87c64e765dd5f14ad29e13024d4dae422a223c5 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/ensemble/__pycache__/_iforest.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/__init__.py b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ce5fbc10ee45958ea0bbc405d134a8bc274b22f0 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/__init__.py @@ -0,0 +1,53 @@ +""" +The :mod:`sklearn.feature_selection` module implements feature selection +algorithms. It currently includes univariate filter selection methods and the +recursive feature elimination algorithm. +""" + +from ._univariate_selection import chi2 +from ._univariate_selection import f_classif +from ._univariate_selection import f_oneway +from ._univariate_selection import f_regression +from ._univariate_selection import r_regression +from ._univariate_selection import SelectPercentile +from ._univariate_selection import SelectKBest +from ._univariate_selection import SelectFpr +from ._univariate_selection import SelectFdr +from ._univariate_selection import SelectFwe +from ._univariate_selection import GenericUnivariateSelect + +from ._variance_threshold import VarianceThreshold + +from ._rfe import RFE +from ._rfe import RFECV + +from ._from_model import SelectFromModel + +from ._sequential import SequentialFeatureSelector + +from ._mutual_info import mutual_info_regression, mutual_info_classif + +from ._base import SelectorMixin + + +__all__ = [ + "GenericUnivariateSelect", + "SequentialFeatureSelector", + "RFE", + "RFECV", + "SelectFdr", + "SelectFpr", + "SelectFwe", + "SelectKBest", + "SelectFromModel", + "SelectPercentile", + "VarianceThreshold", + "chi2", + "f_classif", + "f_oneway", + "f_regression", + "r_regression", + "mutual_info_classif", + "mutual_info_regression", + "SelectorMixin", +] diff --git a/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_from_model.py b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_from_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7b8de4ae03585586763d75c7c2f6bde0d96021fa --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_from_model.py @@ -0,0 +1,444 @@ +# Authors: Gilles Louppe, Mathieu Blondel, Maheshakya Wijewardena +# License: BSD 3 clause + +from copy import deepcopy + +import numpy as np +from numbers import Integral, Real + +from ._base import SelectorMixin +from ._base import _get_feature_importances +from ..base import BaseEstimator, clone, MetaEstimatorMixin +from ..utils._tags import _safe_tags +from ..utils.validation import check_is_fitted, check_scalar, _num_features +from ..utils._param_validation import HasMethods, Interval, Options + +from ..exceptions import NotFittedError +from ..utils.metaestimators import available_if + + +def _calculate_threshold(estimator, importances, threshold): + """Interpret the threshold value""" + + if threshold is None: + # determine default from estimator + est_name = estimator.__class__.__name__ + is_l1_penalized = hasattr(estimator, "penalty") and estimator.penalty == "l1" + is_lasso = "Lasso" in est_name + is_elasticnet_l1_penalized = "ElasticNet" in est_name and ( + (hasattr(estimator, "l1_ratio_") and np.isclose(estimator.l1_ratio_, 1.0)) + or (hasattr(estimator, "l1_ratio") and np.isclose(estimator.l1_ratio, 1.0)) + ) + if is_l1_penalized or is_lasso or is_elasticnet_l1_penalized: + # the natural default threshold is 0 when l1 penalty was used + threshold = 1e-5 + else: + threshold = "mean" + + if isinstance(threshold, str): + if "*" in threshold: + scale, reference = threshold.split("*") + scale = float(scale.strip()) + reference = reference.strip() + + if reference == "median": + reference = np.median(importances) + elif reference == "mean": + reference = np.mean(importances) + else: + raise ValueError("Unknown reference: " + reference) + + threshold = scale * reference + + elif threshold == "median": + threshold = np.median(importances) + + elif threshold == "mean": + threshold = np.mean(importances) + + else: + raise ValueError( + "Expected threshold='mean' or threshold='median' got %s" % threshold + ) + + else: + threshold = float(threshold) + + return threshold + + +def _estimator_has(attr): + """Check if we can delegate a method to the underlying estimator. + + First, we check the fitted estimator if available, otherwise we + check the unfitted estimator. + """ + return lambda self: ( + hasattr(self.estimator_, attr) + if hasattr(self, "estimator_") + else hasattr(self.estimator, attr) + ) + + +class SelectFromModel(MetaEstimatorMixin, SelectorMixin, BaseEstimator): + """Meta-transformer for selecting features based on importance weights. + + .. versionadded:: 0.17 + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : object + The base estimator from which the transformer is built. + This can be both a fitted (if ``prefit`` is set to True) + or a non-fitted estimator. The estimator should have a + ``feature_importances_`` or ``coef_`` attribute after fitting. + Otherwise, the ``importance_getter`` parameter should be used. + + threshold : str or float, default=None + The threshold value to use for feature selection. Features whose + absolute importance value is greater or equal are kept while the others + are discarded. If "median" (resp. "mean"), then the ``threshold`` value + is the median (resp. the mean) of the feature importances. A scaling + factor (e.g., "1.25*mean") may also be used. If None and if the + estimator has a parameter penalty set to l1, either explicitly + or implicitly (e.g, Lasso), the threshold used is 1e-5. + Otherwise, "mean" is used by default. + + prefit : bool, default=False + Whether a prefit model is expected to be passed into the constructor + directly or not. + If `True`, `estimator` must be a fitted estimator. + If `False`, `estimator` is fitted and updated by calling + `fit` and `partial_fit`, respectively. + + norm_order : non-zero int, inf, -inf, default=1 + Order of the norm used to filter the vectors of coefficients below + ``threshold`` in the case where the ``coef_`` attribute of the + estimator is of dimension 2. + + max_features : int, callable, default=None + The maximum number of features to select. + + - If an integer, then it specifies the maximum number of features to + allow. + - If a callable, then it specifies how to calculate the maximum number of + features allowed by using the output of `max_features(X)`. + - If `None`, then all features are kept. + + To only select based on ``max_features``, set ``threshold=-np.inf``. + + .. versionadded:: 0.20 + .. versionchanged:: 1.1 + `max_features` accepts a callable. + + importance_getter : str or callable, default='auto' + If 'auto', uses the feature importance either through a ``coef_`` + attribute or ``feature_importances_`` attribute of estimator. + + Also accepts a string that specifies an attribute name/path + for extracting feature importance (implemented with `attrgetter`). + For example, give `regressor_.coef_` in case of + :class:`~sklearn.compose.TransformedTargetRegressor` or + `named_steps.clf.feature_importances_` in case of + :class:`~sklearn.pipeline.Pipeline` with its last step named `clf`. + + If `callable`, overrides the default feature importance getter. + The callable is passed with the fitted estimator and it should + return importance for each feature. + + .. versionadded:: 0.24 + + Attributes + ---------- + estimator_ : estimator + The base estimator from which the transformer is built. This attribute + exist only when `fit` has been called. + + - If `prefit=True`, it is a deep copy of `estimator`. + - If `prefit=False`, it is a clone of `estimator` and fit on the data + passed to `fit` or `partial_fit`. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + .. versionadded:: 0.24 + + max_features_ : int + Maximum number of features calculated during :term:`fit`. Only defined + if the ``max_features`` is not `None`. + + - If `max_features` is an `int`, then `max_features_ = max_features`. + - If `max_features` is a callable, then `max_features_ = max_features(X)`. + + .. versionadded:: 1.1 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + threshold_ : float + The threshold value used for feature selection. + + See Also + -------- + RFE : Recursive feature elimination based on importance weights. + RFECV : Recursive feature elimination with built-in cross-validated + selection of the best number of features. + SequentialFeatureSelector : Sequential cross-validation based feature + selection. Does not rely on importance weights. + + Notes + ----- + Allows NaN/Inf in the input if the underlying estimator does as well. + + Examples + -------- + >>> from sklearn.feature_selection import SelectFromModel + >>> from sklearn.linear_model import LogisticRegression + >>> X = [[ 0.87, -1.34, 0.31 ], + ... [-2.79, -0.02, -0.85 ], + ... [-1.34, -0.48, -2.55 ], + ... [ 1.92, 1.48, 0.65 ]] + >>> y = [0, 1, 0, 1] + >>> selector = SelectFromModel(estimator=LogisticRegression()).fit(X, y) + >>> selector.estimator_.coef_ + array([[-0.3252302 , 0.83462377, 0.49750423]]) + >>> selector.threshold_ + 0.55245... + >>> selector.get_support() + array([False, True, False]) + >>> selector.transform(X) + array([[-1.34], + [-0.02], + [-0.48], + [ 1.48]]) + + Using a callable to create a selector that can use no more than half + of the input features. + + >>> def half_callable(X): + ... return round(len(X[0]) / 2) + >>> half_selector = SelectFromModel(estimator=LogisticRegression(), + ... max_features=half_callable) + >>> _ = half_selector.fit(X, y) + >>> half_selector.max_features_ + 2 + """ + + _parameter_constraints: dict = { + "estimator": [HasMethods("fit")], + "threshold": [Interval(Real, None, None, closed="both"), str, None], + "prefit": ["boolean"], + "norm_order": [ + Interval(Integral, None, -1, closed="right"), + Interval(Integral, 1, None, closed="left"), + Options(Real, {np.inf, -np.inf}), + ], + "max_features": [Interval(Integral, 0, None, closed="left"), callable, None], + "importance_getter": [str, callable], + } + + def __init__( + self, + estimator, + *, + threshold=None, + prefit=False, + norm_order=1, + max_features=None, + importance_getter="auto", + ): + self.estimator = estimator + self.threshold = threshold + self.prefit = prefit + self.importance_getter = importance_getter + self.norm_order = norm_order + self.max_features = max_features + + def _get_support_mask(self): + estimator = getattr(self, "estimator_", self.estimator) + max_features = getattr(self, "max_features_", self.max_features) + + if self.prefit: + try: + check_is_fitted(self.estimator) + except NotFittedError as exc: + raise NotFittedError( + "When `prefit=True`, `estimator` is expected to be a fitted " + "estimator." + ) from exc + if callable(max_features): + # This branch is executed when `transform` is called directly and thus + # `max_features_` is not set and we fallback using `self.max_features` + # that is not validated + raise NotFittedError( + "When `prefit=True` and `max_features` is a callable, call `fit` " + "before calling `transform`." + ) + elif max_features is not None and not isinstance(max_features, Integral): + raise ValueError( + f"`max_features` must be an integer. Got `max_features={max_features}` " + "instead." + ) + + scores = _get_feature_importances( + estimator=estimator, + getter=self.importance_getter, + transform_func="norm", + norm_order=self.norm_order, + ) + threshold = _calculate_threshold(estimator, scores, self.threshold) + if self.max_features is not None: + mask = np.zeros_like(scores, dtype=bool) + candidate_indices = np.argsort(-scores, kind="mergesort")[:max_features] + mask[candidate_indices] = True + else: + mask = np.ones_like(scores, dtype=bool) + mask[scores < threshold] = False + return mask + + def _check_max_features(self, X): + if self.max_features is not None: + n_features = _num_features(X) + + if callable(self.max_features): + max_features = self.max_features(X) + else: # int + max_features = self.max_features + + check_scalar( + max_features, + "max_features", + Integral, + min_val=0, + max_val=n_features, + ) + self.max_features_ = max_features + + def fit(self, X, y=None, **fit_params): + """Fit the SelectFromModel meta-transformer. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The training input samples. + + y : array-like of shape (n_samples,), default=None + The target values (integers that correspond to classes in + classification, real numbers in regression). + + **fit_params : dict + Other estimator specific parameters. + + Returns + ------- + self : object + Fitted estimator. + """ + self._validate_params() + self._check_max_features(X) + + if self.prefit: + try: + check_is_fitted(self.estimator) + except NotFittedError as exc: + raise NotFittedError( + "When `prefit=True`, `estimator` is expected to be a fitted " + "estimator." + ) from exc + self.estimator_ = deepcopy(self.estimator) + else: + self.estimator_ = clone(self.estimator) + self.estimator_.fit(X, y, **fit_params) + + if hasattr(self.estimator_, "feature_names_in_"): + self.feature_names_in_ = self.estimator_.feature_names_in_ + else: + self._check_feature_names(X, reset=True) + + return self + + @property + def threshold_(self): + """Threshold value used for feature selection.""" + scores = _get_feature_importances( + estimator=self.estimator_, + getter=self.importance_getter, + transform_func="norm", + norm_order=self.norm_order, + ) + return _calculate_threshold(self.estimator, scores, self.threshold) + + @available_if(_estimator_has("partial_fit")) + def partial_fit(self, X, y=None, **fit_params): + """Fit the SelectFromModel meta-transformer only once. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The training input samples. + + y : array-like of shape (n_samples,), default=None + The target values (integers that correspond to classes in + classification, real numbers in regression). + + **fit_params : dict + Other estimator specific parameters. + + Returns + ------- + self : object + Fitted estimator. + """ + first_call = not hasattr(self, "estimator_") + + if first_call: + self._validate_params() + self._check_max_features(X) + + if self.prefit: + if first_call: + try: + check_is_fitted(self.estimator) + except NotFittedError as exc: + raise NotFittedError( + "When `prefit=True`, `estimator` is expected to be a fitted " + "estimator." + ) from exc + self.estimator_ = deepcopy(self.estimator) + return self + + if first_call: + self.estimator_ = clone(self.estimator) + self.estimator_.partial_fit(X, y, **fit_params) + + if hasattr(self.estimator_, "feature_names_in_"): + self.feature_names_in_ = self.estimator_.feature_names_in_ + else: + self._check_feature_names(X, reset=first_call) + + return self + + @property + def n_features_in_(self): + """Number of features seen during `fit`.""" + # For consistency with other estimators we raise a AttributeError so + # that hasattr() fails if the estimator isn't fitted. + try: + check_is_fitted(self) + except NotFittedError as nfe: + raise AttributeError( + "{} object has no n_features_in_ attribute.".format( + self.__class__.__name__ + ) + ) from nfe + + return self.estimator_.n_features_in_ + + def _more_tags(self): + return {"allow_nan": _safe_tags(self.estimator, key="allow_nan")} diff --git a/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_mutual_info.py b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_mutual_info.py new file mode 100644 index 0000000000000000000000000000000000000000..2a03eb7dfd2fe98df56dd3e48f41b7142260368c --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_mutual_info.py @@ -0,0 +1,468 @@ +# Author: Nikolay Mayorov +# License: 3-clause BSD + +import numpy as np +from scipy.sparse import issparse +from scipy.special import digamma + +from ..metrics.cluster import mutual_info_score +from ..neighbors import NearestNeighbors, KDTree +from ..preprocessing import scale +from ..utils import check_random_state +from ..utils.validation import check_array, check_X_y +from ..utils.multiclass import check_classification_targets + + +def _compute_mi_cc(x, y, n_neighbors): + """Compute mutual information between two continuous variables. + + Parameters + ---------- + x, y : ndarray, shape (n_samples,) + Samples of two continuous random variables, must have an identical + shape. + + n_neighbors : int + Number of nearest neighbors to search for each point, see [1]_. + + Returns + ------- + mi : float + Estimated mutual information. If it turned out to be negative it is + replace by 0. + + Notes + ----- + True mutual information can't be negative. If its estimate by a numerical + method is negative, it means (providing the method is adequate) that the + mutual information is close to 0 and replacing it by 0 is a reasonable + strategy. + + References + ---------- + .. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual + information". Phys. Rev. E 69, 2004. + """ + n_samples = x.size + + x = x.reshape((-1, 1)) + y = y.reshape((-1, 1)) + xy = np.hstack((x, y)) + + # Here we rely on NearestNeighbors to select the fastest algorithm. + nn = NearestNeighbors(metric="chebyshev", n_neighbors=n_neighbors) + + nn.fit(xy) + radius = nn.kneighbors()[0] + radius = np.nextafter(radius[:, -1], 0) + + # KDTree is explicitly fit to allow for the querying of number of + # neighbors within a specified radius + kd = KDTree(x, metric="chebyshev") + nx = kd.query_radius(x, radius, count_only=True, return_distance=False) + nx = np.array(nx) - 1.0 + + kd = KDTree(y, metric="chebyshev") + ny = kd.query_radius(y, radius, count_only=True, return_distance=False) + ny = np.array(ny) - 1.0 + + mi = ( + digamma(n_samples) + + digamma(n_neighbors) + - np.mean(digamma(nx + 1)) + - np.mean(digamma(ny + 1)) + ) + + return max(0, mi) + + +def _compute_mi_cd(c, d, n_neighbors): + """Compute mutual information between continuous and discrete variables. + + Parameters + ---------- + c : ndarray, shape (n_samples,) + Samples of a continuous random variable. + + d : ndarray, shape (n_samples,) + Samples of a discrete random variable. + + n_neighbors : int + Number of nearest neighbors to search for each point, see [1]_. + + Returns + ------- + mi : float + Estimated mutual information. If it turned out to be negative it is + replace by 0. + + Notes + ----- + True mutual information can't be negative. If its estimate by a numerical + method is negative, it means (providing the method is adequate) that the + mutual information is close to 0 and replacing it by 0 is a reasonable + strategy. + + References + ---------- + .. [1] B. C. Ross "Mutual Information between Discrete and Continuous + Data Sets". PLoS ONE 9(2), 2014. + """ + n_samples = c.shape[0] + c = c.reshape((-1, 1)) + + radius = np.empty(n_samples) + label_counts = np.empty(n_samples) + k_all = np.empty(n_samples) + nn = NearestNeighbors() + for label in np.unique(d): + mask = d == label + count = np.sum(mask) + if count > 1: + k = min(n_neighbors, count - 1) + nn.set_params(n_neighbors=k) + nn.fit(c[mask]) + r = nn.kneighbors()[0] + radius[mask] = np.nextafter(r[:, -1], 0) + k_all[mask] = k + label_counts[mask] = count + + # Ignore points with unique labels. + mask = label_counts > 1 + n_samples = np.sum(mask) + label_counts = label_counts[mask] + k_all = k_all[mask] + c = c[mask] + radius = radius[mask] + + kd = KDTree(c) + m_all = kd.query_radius(c, radius, count_only=True, return_distance=False) + m_all = np.array(m_all) + + mi = ( + digamma(n_samples) + + np.mean(digamma(k_all)) + - np.mean(digamma(label_counts)) + - np.mean(digamma(m_all)) + ) + + return max(0, mi) + + +def _compute_mi(x, y, x_discrete, y_discrete, n_neighbors=3): + """Compute mutual information between two variables. + + This is a simple wrapper which selects a proper function to call based on + whether `x` and `y` are discrete or not. + """ + if x_discrete and y_discrete: + return mutual_info_score(x, y) + elif x_discrete and not y_discrete: + return _compute_mi_cd(y, x, n_neighbors) + elif not x_discrete and y_discrete: + return _compute_mi_cd(x, y, n_neighbors) + else: + return _compute_mi_cc(x, y, n_neighbors) + + +def _iterate_columns(X, columns=None): + """Iterate over columns of a matrix. + + Parameters + ---------- + X : ndarray or csc_matrix, shape (n_samples, n_features) + Matrix over which to iterate. + + columns : iterable or None, default=None + Indices of columns to iterate over. If None, iterate over all columns. + + Yields + ------ + x : ndarray, shape (n_samples,) + Columns of `X` in dense format. + """ + if columns is None: + columns = range(X.shape[1]) + + if issparse(X): + for i in columns: + x = np.zeros(X.shape[0]) + start_ptr, end_ptr = X.indptr[i], X.indptr[i + 1] + x[X.indices[start_ptr:end_ptr]] = X.data[start_ptr:end_ptr] + yield x + else: + for i in columns: + yield X[:, i] + + +def _estimate_mi( + X, + y, + discrete_features="auto", + discrete_target=False, + n_neighbors=3, + copy=True, + random_state=None, +): + """Estimate mutual information between the features and the target. + + Parameters + ---------- + X : array-like or sparse matrix, shape (n_samples, n_features) + Feature matrix. + + y : array-like of shape (n_samples,) + Target vector. + + discrete_features : {'auto', bool, array-like}, default='auto' + If bool, then determines whether to consider all features discrete + or continuous. If array, then it should be either a boolean mask + with shape (n_features,) or array with indices of discrete features. + If 'auto', it is assigned to False for dense `X` and to True for + sparse `X`. + + discrete_target : bool, default=False + Whether to consider `y` as a discrete variable. + + n_neighbors : int, default=3 + Number of neighbors to use for MI estimation for continuous variables, + see [1]_ and [2]_. Higher values reduce variance of the estimation, but + could introduce a bias. + + copy : bool, default=True + Whether to make a copy of the given data. If set to False, the initial + data will be overwritten. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for adding small noise to + continuous variables in order to remove repeated values. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + Returns + ------- + mi : ndarray, shape (n_features,) + Estimated mutual information between each feature and the target. + A negative value will be replaced by 0. + + References + ---------- + .. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual + information". Phys. Rev. E 69, 2004. + .. [2] B. C. Ross "Mutual Information between Discrete and Continuous + Data Sets". PLoS ONE 9(2), 2014. + """ + X, y = check_X_y(X, y, accept_sparse="csc", y_numeric=not discrete_target) + n_samples, n_features = X.shape + + if isinstance(discrete_features, (str, bool)): + if isinstance(discrete_features, str): + if discrete_features == "auto": + discrete_features = issparse(X) + else: + raise ValueError("Invalid string value for discrete_features.") + discrete_mask = np.empty(n_features, dtype=bool) + discrete_mask.fill(discrete_features) + else: + discrete_features = check_array(discrete_features, ensure_2d=False) + if discrete_features.dtype != "bool": + discrete_mask = np.zeros(n_features, dtype=bool) + discrete_mask[discrete_features] = True + else: + discrete_mask = discrete_features + + continuous_mask = ~discrete_mask + if np.any(continuous_mask) and issparse(X): + raise ValueError("Sparse matrix `X` can't have continuous features.") + + rng = check_random_state(random_state) + if np.any(continuous_mask): + if copy: + X = X.copy() + + X[:, continuous_mask] = scale( + X[:, continuous_mask], with_mean=False, copy=False + ) + + # Add small noise to continuous features as advised in Kraskov et. al. + X = X.astype(np.float64, copy=False) + means = np.maximum(1, np.mean(np.abs(X[:, continuous_mask]), axis=0)) + X[:, continuous_mask] += ( + 1e-10 + * means + * rng.standard_normal(size=(n_samples, np.sum(continuous_mask))) + ) + + if not discrete_target: + y = scale(y, with_mean=False) + y += ( + 1e-10 + * np.maximum(1, np.mean(np.abs(y))) + * rng.standard_normal(size=n_samples) + ) + + mi = [ + _compute_mi(x, y, discrete_feature, discrete_target, n_neighbors) + for x, discrete_feature in zip(_iterate_columns(X), discrete_mask) + ] + + return np.array(mi) + + +def mutual_info_regression( + X, y, *, discrete_features="auto", n_neighbors=3, copy=True, random_state=None +): + """Estimate mutual information for a continuous target variable. + + Mutual information (MI) [1]_ between two random variables is a non-negative + value, which measures the dependency between the variables. It is equal + to zero if and only if two random variables are independent, and higher + values mean higher dependency. + + The function relies on nonparametric methods based on entropy estimation + from k-nearest neighbors distances as described in [2]_ and [3]_. Both + methods are based on the idea originally proposed in [4]_. + + It can be used for univariate features selection, read more in the + :ref:`User Guide `. + + Parameters + ---------- + X : array-like or sparse matrix, shape (n_samples, n_features) + Feature matrix. + + y : array-like of shape (n_samples,) + Target vector. + + discrete_features : {'auto', bool, array-like}, default='auto' + If bool, then determines whether to consider all features discrete + or continuous. If array, then it should be either a boolean mask + with shape (n_features,) or array with indices of discrete features. + If 'auto', it is assigned to False for dense `X` and to True for + sparse `X`. + + n_neighbors : int, default=3 + Number of neighbors to use for MI estimation for continuous variables, + see [2]_ and [3]_. Higher values reduce variance of the estimation, but + could introduce a bias. + + copy : bool, default=True + Whether to make a copy of the given data. If set to False, the initial + data will be overwritten. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for adding small noise to + continuous variables in order to remove repeated values. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + Returns + ------- + mi : ndarray, shape (n_features,) + Estimated mutual information between each feature and the target. + + Notes + ----- + 1. The term "discrete features" is used instead of naming them + "categorical", because it describes the essence more accurately. + For example, pixel intensities of an image are discrete features + (but hardly categorical) and you will get better results if mark them + as such. Also note, that treating a continuous variable as discrete and + vice versa will usually give incorrect results, so be attentive about + that. + 2. True mutual information can't be negative. If its estimate turns out + to be negative, it is replaced by zero. + + References + ---------- + .. [1] `Mutual Information + `_ + on Wikipedia. + .. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual + information". Phys. Rev. E 69, 2004. + .. [3] B. C. Ross "Mutual Information between Discrete and Continuous + Data Sets". PLoS ONE 9(2), 2014. + .. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy + of a Random Vector", Probl. Peredachi Inf., 23:2 (1987), 9-16 + """ + return _estimate_mi(X, y, discrete_features, False, n_neighbors, copy, random_state) + + +def mutual_info_classif( + X, y, *, discrete_features="auto", n_neighbors=3, copy=True, random_state=None +): + """Estimate mutual information for a discrete target variable. + + Mutual information (MI) [1]_ between two random variables is a non-negative + value, which measures the dependency between the variables. It is equal + to zero if and only if two random variables are independent, and higher + values mean higher dependency. + + The function relies on nonparametric methods based on entropy estimation + from k-nearest neighbors distances as described in [2]_ and [3]_. Both + methods are based on the idea originally proposed in [4]_. + + It can be used for univariate features selection, read more in the + :ref:`User Guide `. + + Parameters + ---------- + X : array-like or sparse matrix, shape (n_samples, n_features) + Feature matrix. + + y : array-like of shape (n_samples,) + Target vector. + + discrete_features : {'auto', bool, array-like}, default='auto' + If bool, then determines whether to consider all features discrete + or continuous. If array, then it should be either a boolean mask + with shape (n_features,) or array with indices of discrete features. + If 'auto', it is assigned to False for dense `X` and to True for + sparse `X`. + + n_neighbors : int, default=3 + Number of neighbors to use for MI estimation for continuous variables, + see [2]_ and [3]_. Higher values reduce variance of the estimation, but + could introduce a bias. + + copy : bool, default=True + Whether to make a copy of the given data. If set to False, the initial + data will be overwritten. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for adding small noise to + continuous variables in order to remove repeated values. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + Returns + ------- + mi : ndarray, shape (n_features,) + Estimated mutual information between each feature and the target. + + Notes + ----- + 1. The term "discrete features" is used instead of naming them + "categorical", because it describes the essence more accurately. + For example, pixel intensities of an image are discrete features + (but hardly categorical) and you will get better results if mark them + as such. Also note, that treating a continuous variable as discrete and + vice versa will usually give incorrect results, so be attentive about + that. + 2. True mutual information can't be negative. If its estimate turns out + to be negative, it is replaced by zero. + + References + ---------- + .. [1] `Mutual Information + `_ + on Wikipedia. + .. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual + information". Phys. Rev. E 69, 2004. + .. [3] B. C. Ross "Mutual Information between Discrete and Continuous + Data Sets". PLoS ONE 9(2), 2014. + .. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy + of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16 + """ + check_classification_targets(y) + return _estimate_mi(X, y, discrete_features, True, n_neighbors, copy, random_state) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_rfe.py b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_rfe.py new file mode 100644 index 0000000000000000000000000000000000000000..d105ba1ae3567173e87208128f41c48b1761a74c --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_rfe.py @@ -0,0 +1,765 @@ +# Authors: Alexandre Gramfort +# Vincent Michel +# Gilles Louppe +# +# License: BSD 3 clause + +"""Recursive feature elimination for feature ranking""" + +import numpy as np +from numbers import Integral, Real +from joblib import effective_n_jobs + + +from ..utils.metaestimators import available_if +from ..utils.metaestimators import _safe_split +from ..utils._param_validation import HasMethods, Interval +from ..utils._tags import _safe_tags +from ..utils.validation import check_is_fitted +from ..utils.parallel import delayed, Parallel +from ..base import BaseEstimator +from ..base import MetaEstimatorMixin +from ..base import clone +from ..base import is_classifier +from ..model_selection import check_cv +from ..model_selection._validation import _score +from ..metrics import check_scoring +from ._base import SelectorMixin +from ._base import _get_feature_importances + + +def _rfe_single_fit(rfe, estimator, X, y, train, test, scorer): + """ + Return the score for a fit across one fold. + """ + X_train, y_train = _safe_split(estimator, X, y, train) + X_test, y_test = _safe_split(estimator, X, y, test, train) + return rfe._fit( + X_train, + y_train, + lambda estimator, features: _score( + estimator, X_test[:, features], y_test, scorer + ), + ).scores_ + + +def _estimator_has(attr): + """Check if we can delegate a method to the underlying estimator. + + First, we check the first fitted estimator if available, otherwise we + check the unfitted estimator. + """ + return lambda self: ( + hasattr(self.estimator_, attr) + if hasattr(self, "estimator_") + else hasattr(self.estimator, attr) + ) + + +class RFE(SelectorMixin, MetaEstimatorMixin, BaseEstimator): + """Feature ranking with recursive feature elimination. + + Given an external estimator that assigns weights to features (e.g., the + coefficients of a linear model), the goal of recursive feature elimination + (RFE) is to select features by recursively considering smaller and smaller + sets of features. First, the estimator is trained on the initial set of + features and the importance of each feature is obtained either through + any specific attribute or callable. + Then, the least important features are pruned from current set of features. + That procedure is recursively repeated on the pruned set until the desired + number of features to select is eventually reached. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : ``Estimator`` instance + A supervised learning estimator with a ``fit`` method that provides + information about feature importance + (e.g. `coef_`, `feature_importances_`). + + n_features_to_select : int or float, default=None + The number of features to select. If `None`, half of the features are + selected. If integer, the parameter is the absolute number of features + to select. If float between 0 and 1, it is the fraction of features to + select. + + .. versionchanged:: 0.24 + Added float values for fractions. + + step : int or float, default=1 + If greater than or equal to 1, then ``step`` corresponds to the + (integer) number of features to remove at each iteration. + If within (0.0, 1.0), then ``step`` corresponds to the percentage + (rounded down) of features to remove at each iteration. + + verbose : int, default=0 + Controls verbosity of output. + + importance_getter : str or callable, default='auto' + If 'auto', uses the feature importance either through a `coef_` + or `feature_importances_` attributes of estimator. + + Also accepts a string that specifies an attribute name/path + for extracting feature importance (implemented with `attrgetter`). + For example, give `regressor_.coef_` in case of + :class:`~sklearn.compose.TransformedTargetRegressor` or + `named_steps.clf.feature_importances_` in case of + class:`~sklearn.pipeline.Pipeline` with its last step named `clf`. + + If `callable`, overrides the default feature importance getter. + The callable is passed with the fitted estimator and it should + return importance for each feature. + + .. versionadded:: 0.24 + + Attributes + ---------- + classes_ : ndarray of shape (n_classes,) + The classes labels. Only available when `estimator` is a classifier. + + estimator_ : ``Estimator`` instance + The fitted estimator used to select features. + + n_features_ : int + The number of selected features. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + ranking_ : ndarray of shape (n_features,) + The feature ranking, such that ``ranking_[i]`` corresponds to the + ranking position of the i-th feature. Selected (i.e., estimated + best) features are assigned rank 1. + + support_ : ndarray of shape (n_features,) + The mask of selected features. + + See Also + -------- + RFECV : Recursive feature elimination with built-in cross-validated + selection of the best number of features. + SelectFromModel : Feature selection based on thresholds of importance + weights. + SequentialFeatureSelector : Sequential cross-validation based feature + selection. Does not rely on importance weights. + + Notes + ----- + Allows NaN/Inf in the input if the underlying estimator does as well. + + References + ---------- + + .. [1] Guyon, I., Weston, J., Barnhill, S., & Vapnik, V., "Gene selection + for cancer classification using support vector machines", + Mach. Learn., 46(1-3), 389--422, 2002. + + Examples + -------- + The following example shows how to retrieve the 5 most informative + features in the Friedman #1 dataset. + + >>> from sklearn.datasets import make_friedman1 + >>> from sklearn.feature_selection import RFE + >>> from sklearn.svm import SVR + >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0) + >>> estimator = SVR(kernel="linear") + >>> selector = RFE(estimator, n_features_to_select=5, step=1) + >>> selector = selector.fit(X, y) + >>> selector.support_ + array([ True, True, True, True, True, False, False, False, False, + False]) + >>> selector.ranking_ + array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5]) + """ + + _parameter_constraints: dict = { + "estimator": [HasMethods(["fit"])], + "n_features_to_select": [ + None, + Interval(Real, 0, 1, closed="right"), + Interval(Integral, 0, None, closed="neither"), + ], + "step": [ + Interval(Integral, 0, None, closed="neither"), + Interval(Real, 0, 1, closed="neither"), + ], + "verbose": ["verbose"], + "importance_getter": [str, callable], + } + + def __init__( + self, + estimator, + *, + n_features_to_select=None, + step=1, + verbose=0, + importance_getter="auto", + ): + self.estimator = estimator + self.n_features_to_select = n_features_to_select + self.step = step + self.importance_getter = importance_getter + self.verbose = verbose + + @property + def _estimator_type(self): + return self.estimator._estimator_type + + @property + def classes_(self): + """Classes labels available when `estimator` is a classifier. + + Returns + ------- + ndarray of shape (n_classes,) + """ + return self.estimator_.classes_ + + def fit(self, X, y, **fit_params): + """Fit the RFE model and then the underlying estimator on the selected features. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The training input samples. + + y : array-like of shape (n_samples,) + The target values. + + **fit_params : dict + Additional parameters passed to the `fit` method of the underlying + estimator. + + Returns + ------- + self : object + Fitted estimator. + """ + self._validate_params() + return self._fit(X, y, **fit_params) + + def _fit(self, X, y, step_score=None, **fit_params): + # Parameter step_score controls the calculation of self.scores_ + # step_score is not exposed to users + # and is used when implementing RFECV + # self.scores_ will not be calculated when calling _fit through fit + + tags = self._get_tags() + X, y = self._validate_data( + X, + y, + accept_sparse="csc", + ensure_min_features=2, + force_all_finite=not tags.get("allow_nan", True), + multi_output=True, + ) + + # Initialization + n_features = X.shape[1] + if self.n_features_to_select is None: + n_features_to_select = n_features // 2 + elif isinstance(self.n_features_to_select, Integral): # int + n_features_to_select = self.n_features_to_select + else: # float + n_features_to_select = int(n_features * self.n_features_to_select) + + if 0.0 < self.step < 1.0: + step = int(max(1, self.step * n_features)) + else: + step = int(self.step) + + support_ = np.ones(n_features, dtype=bool) + ranking_ = np.ones(n_features, dtype=int) + + if step_score: + self.scores_ = [] + + # Elimination + while np.sum(support_) > n_features_to_select: + # Remaining features + features = np.arange(n_features)[support_] + + # Rank the remaining features + estimator = clone(self.estimator) + if self.verbose > 0: + print("Fitting estimator with %d features." % np.sum(support_)) + + estimator.fit(X[:, features], y, **fit_params) + + # Get importance and rank them + importances = _get_feature_importances( + estimator, + self.importance_getter, + transform_func="square", + ) + ranks = np.argsort(importances) + + # for sparse case ranks is matrix + ranks = np.ravel(ranks) + + # Eliminate the worse features + threshold = min(step, np.sum(support_) - n_features_to_select) + + # Compute step score on the previous selection iteration + # because 'estimator' must use features + # that have not been eliminated yet + if step_score: + self.scores_.append(step_score(estimator, features)) + support_[features[ranks][:threshold]] = False + ranking_[np.logical_not(support_)] += 1 + + # Set final attributes + features = np.arange(n_features)[support_] + self.estimator_ = clone(self.estimator) + self.estimator_.fit(X[:, features], y, **fit_params) + + # Compute step score when only n_features_to_select features left + if step_score: + self.scores_.append(step_score(self.estimator_, features)) + self.n_features_ = support_.sum() + self.support_ = support_ + self.ranking_ = ranking_ + + return self + + @available_if(_estimator_has("predict")) + def predict(self, X): + """Reduce X to the selected features and predict using the estimator. + + Parameters + ---------- + X : array of shape [n_samples, n_features] + The input samples. + + Returns + ------- + y : array of shape [n_samples] + The predicted target values. + """ + check_is_fitted(self) + return self.estimator_.predict(self.transform(X)) + + @available_if(_estimator_has("score")) + def score(self, X, y, **fit_params): + """Reduce X to the selected features and return the score of the estimator. + + Parameters + ---------- + X : array of shape [n_samples, n_features] + The input samples. + + y : array of shape [n_samples] + The target values. + + **fit_params : dict + Parameters to pass to the `score` method of the underlying + estimator. + + .. versionadded:: 1.0 + + Returns + ------- + score : float + Score of the underlying base estimator computed with the selected + features returned by `rfe.transform(X)` and `y`. + """ + check_is_fitted(self) + return self.estimator_.score(self.transform(X), y, **fit_params) + + def _get_support_mask(self): + check_is_fitted(self) + return self.support_ + + @available_if(_estimator_has("decision_function")) + def decision_function(self, X): + """Compute the decision function of ``X``. + + Parameters + ---------- + X : {array-like or sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + Returns + ------- + score : array, shape = [n_samples, n_classes] or [n_samples] + The decision function of the input samples. The order of the + classes corresponds to that in the attribute :term:`classes_`. + Regression and binary classification produce an array of shape + [n_samples]. + """ + check_is_fitted(self) + return self.estimator_.decision_function(self.transform(X)) + + @available_if(_estimator_has("predict_proba")) + def predict_proba(self, X): + """Predict class probabilities for X. + + Parameters + ---------- + X : {array-like or sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + Returns + ------- + p : array of shape (n_samples, n_classes) + The class probabilities of the input samples. The order of the + classes corresponds to that in the attribute :term:`classes_`. + """ + check_is_fitted(self) + return self.estimator_.predict_proba(self.transform(X)) + + @available_if(_estimator_has("predict_log_proba")) + def predict_log_proba(self, X): + """Predict class log-probabilities for X. + + Parameters + ---------- + X : array of shape [n_samples, n_features] + The input samples. + + Returns + ------- + p : array of shape (n_samples, n_classes) + The class log-probabilities of the input samples. The order of the + classes corresponds to that in the attribute :term:`classes_`. + """ + check_is_fitted(self) + return self.estimator_.predict_log_proba(self.transform(X)) + + def _more_tags(self): + return { + "poor_score": True, + "allow_nan": _safe_tags(self.estimator, key="allow_nan"), + "requires_y": True, + } + + +class RFECV(RFE): + """Recursive feature elimination with cross-validation to select features. + + See glossary entry for :term:`cross-validation estimator`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : ``Estimator`` instance + A supervised learning estimator with a ``fit`` method that provides + information about feature importance either through a ``coef_`` + attribute or through a ``feature_importances_`` attribute. + + step : int or float, default=1 + If greater than or equal to 1, then ``step`` corresponds to the + (integer) number of features to remove at each iteration. + If within (0.0, 1.0), then ``step`` corresponds to the percentage + (rounded down) of features to remove at each iteration. + Note that the last iteration may remove fewer than ``step`` features in + order to reach ``min_features_to_select``. + + min_features_to_select : int, default=1 + The minimum number of features to be selected. This number of features + will always be scored, even if the difference between the original + feature count and ``min_features_to_select`` isn't divisible by + ``step``. + + .. versionadded:: 0.20 + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross-validation, + - integer, to specify the number of folds. + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For integer/None inputs, if ``y`` is binary or multiclass, + :class:`~sklearn.model_selection.StratifiedKFold` is used. If the + estimator is a classifier or if ``y`` is neither binary nor multiclass, + :class:`~sklearn.model_selection.KFold` is used. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value of None changed from 3-fold to 5-fold. + + scoring : str, callable or None, default=None + A string (see model evaluation documentation) or + a scorer callable object / function with signature + ``scorer(estimator, X, y)``. + + verbose : int, default=0 + Controls verbosity of output. + + n_jobs : int or None, default=None + Number of cores to run in parallel while fitting across folds. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + .. versionadded:: 0.18 + + importance_getter : str or callable, default='auto' + If 'auto', uses the feature importance either through a `coef_` + or `feature_importances_` attributes of estimator. + + Also accepts a string that specifies an attribute name/path + for extracting feature importance. + For example, give `regressor_.coef_` in case of + :class:`~sklearn.compose.TransformedTargetRegressor` or + `named_steps.clf.feature_importances_` in case of + :class:`~sklearn.pipeline.Pipeline` with its last step named `clf`. + + If `callable`, overrides the default feature importance getter. + The callable is passed with the fitted estimator and it should + return importance for each feature. + + .. versionadded:: 0.24 + + Attributes + ---------- + classes_ : ndarray of shape (n_classes,) + The classes labels. Only available when `estimator` is a classifier. + + estimator_ : ``Estimator`` instance + The fitted estimator used to select features. + + cv_results_ : dict of ndarrays + A dict with keys: + + split(k)_test_score : ndarray of shape (n_subsets_of_features,) + The cross-validation scores across (k)th fold. + + mean_test_score : ndarray of shape (n_subsets_of_features,) + Mean of scores over the folds. + + std_test_score : ndarray of shape (n_subsets_of_features,) + Standard deviation of scores over the folds. + + .. versionadded:: 1.0 + + n_features_ : int + The number of selected features with cross-validation. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + ranking_ : narray of shape (n_features,) + The feature ranking, such that `ranking_[i]` + corresponds to the ranking + position of the i-th feature. + Selected (i.e., estimated best) + features are assigned rank 1. + + support_ : ndarray of shape (n_features,) + The mask of selected features. + + See Also + -------- + RFE : Recursive feature elimination. + + Notes + ----- + The size of all values in ``cv_results_`` is equal to + ``ceil((n_features - min_features_to_select) / step) + 1``, + where step is the number of features removed at each iteration. + + Allows NaN/Inf in the input if the underlying estimator does as well. + + References + ---------- + + .. [1] Guyon, I., Weston, J., Barnhill, S., & Vapnik, V., "Gene selection + for cancer classification using support vector machines", + Mach. Learn., 46(1-3), 389--422, 2002. + + Examples + -------- + The following example shows how to retrieve the a-priori not known 5 + informative features in the Friedman #1 dataset. + + >>> from sklearn.datasets import make_friedman1 + >>> from sklearn.feature_selection import RFECV + >>> from sklearn.svm import SVR + >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0) + >>> estimator = SVR(kernel="linear") + >>> selector = RFECV(estimator, step=1, cv=5) + >>> selector = selector.fit(X, y) + >>> selector.support_ + array([ True, True, True, True, True, False, False, False, False, + False]) + >>> selector.ranking_ + array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5]) + """ + + _parameter_constraints: dict = { + **RFE._parameter_constraints, + "min_features_to_select": [Interval(Integral, 0, None, closed="neither")], + "cv": ["cv_object"], + "scoring": [None, str, callable], + "n_jobs": [None, Integral], + } + _parameter_constraints.pop("n_features_to_select") + + def __init__( + self, + estimator, + *, + step=1, + min_features_to_select=1, + cv=None, + scoring=None, + verbose=0, + n_jobs=None, + importance_getter="auto", + ): + self.estimator = estimator + self.step = step + self.importance_getter = importance_getter + self.cv = cv + self.scoring = scoring + self.verbose = verbose + self.n_jobs = n_jobs + self.min_features_to_select = min_features_to_select + + def fit(self, X, y, groups=None): + """Fit the RFE model and automatically tune the number of selected features. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples and + `n_features` is the total number of features. + + y : array-like of shape (n_samples,) + Target values (integers for classification, real numbers for + regression). + + groups : array-like of shape (n_samples,) or None, default=None + Group labels for the samples used while splitting the dataset into + train/test set. Only used in conjunction with a "Group" :term:`cv` + instance (e.g., :class:`~sklearn.model_selection.GroupKFold`). + + .. versionadded:: 0.20 + + Returns + ------- + self : object + Fitted estimator. + """ + self._validate_params() + tags = self._get_tags() + X, y = self._validate_data( + X, + y, + accept_sparse="csr", + ensure_min_features=2, + force_all_finite=not tags.get("allow_nan", True), + multi_output=True, + ) + + # Initialization + cv = check_cv(self.cv, y, classifier=is_classifier(self.estimator)) + scorer = check_scoring(self.estimator, scoring=self.scoring) + n_features = X.shape[1] + + if 0.0 < self.step < 1.0: + step = int(max(1, self.step * n_features)) + else: + step = int(self.step) + + # Build an RFE object, which will evaluate and score each possible + # feature count, down to self.min_features_to_select + rfe = RFE( + estimator=self.estimator, + n_features_to_select=self.min_features_to_select, + importance_getter=self.importance_getter, + step=self.step, + verbose=self.verbose, + ) + + # Determine the number of subsets of features by fitting across + # the train folds and choosing the "features_to_select" parameter + # that gives the least averaged error across all folds. + + # Note that joblib raises a non-picklable error for bound methods + # even if n_jobs is set to 1 with the default multiprocessing + # backend. + # This branching is done so that to + # make sure that user code that sets n_jobs to 1 + # and provides bound methods as scorers is not broken with the + # addition of n_jobs parameter in version 0.18. + + if effective_n_jobs(self.n_jobs) == 1: + parallel, func = list, _rfe_single_fit + else: + parallel = Parallel(n_jobs=self.n_jobs) + func = delayed(_rfe_single_fit) + + scores = parallel( + func(rfe, self.estimator, X, y, train, test, scorer) + for train, test in cv.split(X, y, groups) + ) + + scores = np.array(scores) + scores_sum = np.sum(scores, axis=0) + scores_sum_rev = scores_sum[::-1] + argmax_idx = len(scores_sum) - np.argmax(scores_sum_rev) - 1 + n_features_to_select = max( + n_features - (argmax_idx * step), self.min_features_to_select + ) + + # Re-execute an elimination with best_k over the whole set + rfe = RFE( + estimator=self.estimator, + n_features_to_select=n_features_to_select, + step=self.step, + importance_getter=self.importance_getter, + verbose=self.verbose, + ) + + rfe.fit(X, y) + + # Set final attributes + self.support_ = rfe.support_ + self.n_features_ = rfe.n_features_ + self.ranking_ = rfe.ranking_ + self.estimator_ = clone(self.estimator) + self.estimator_.fit(self._transform(X), y) + + # reverse to stay consistent with before + scores_rev = scores[:, ::-1] + self.cv_results_ = {} + self.cv_results_["mean_test_score"] = np.mean(scores_rev, axis=0) + self.cv_results_["std_test_score"] = np.std(scores_rev, axis=0) + + for i in range(scores.shape[0]): + self.cv_results_[f"split{i}_test_score"] = scores_rev[i] + + return self diff --git a/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_sequential.py b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_sequential.py new file mode 100644 index 0000000000000000000000000000000000000000..91ea7bdc719b9a3449659cfad11798b3e2e6cd6c --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_sequential.py @@ -0,0 +1,325 @@ +""" +Sequential feature selection +""" +from numbers import Integral, Real + +import numpy as np + +import warnings + +from ._base import SelectorMixin +from ..base import BaseEstimator, MetaEstimatorMixin, clone +from ..utils._param_validation import HasMethods, Hidden, Interval, StrOptions +from ..utils._tags import _safe_tags +from ..utils.validation import check_is_fitted +from ..model_selection import cross_val_score +from ..metrics import get_scorer_names + + +class SequentialFeatureSelector(SelectorMixin, MetaEstimatorMixin, BaseEstimator): + """Transformer that performs Sequential Feature Selection. + + This Sequential Feature Selector adds (forward selection) or + removes (backward selection) features to form a feature subset in a + greedy fashion. At each stage, this estimator chooses the best feature to + add or remove based on the cross-validation score of an estimator. In + the case of unsupervised learning, this Sequential Feature Selector + looks only at the features (X), not the desired outputs (y). + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.24 + + Parameters + ---------- + estimator : estimator instance + An unfitted estimator. + + n_features_to_select : "auto", int or float, default='warn' + If `"auto"`, the behaviour depends on the `tol` parameter: + + - if `tol` is not `None`, then features are selected until the score + improvement does not exceed `tol`. + - otherwise, half of the features are selected. + + If integer, the parameter is the absolute number of features to select. + If float between 0 and 1, it is the fraction of features to select. + + .. versionadded:: 1.1 + The option `"auto"` was added in version 1.1. + + .. deprecated:: 1.1 + The default changed from `None` to `"warn"` in 1.1 and will become + `"auto"` in 1.3. `None` and `'warn'` will be removed in 1.3. + To keep the same behaviour as `None`, set + `n_features_to_select="auto" and `tol=None`. + + tol : float, default=None + If the score is not incremented by at least `tol` between two + consecutive feature additions or removals, stop adding or removing. + + `tol` can be negative when removing features using `direction="backward"`. + It can be useful to reduce the number of features at the cost of a small + decrease in the score. + + `tol` is enabled only when `n_features_to_select` is `"auto"`. + + .. versionadded:: 1.1 + + direction : {'forward', 'backward'}, default='forward' + Whether to perform forward selection or backward selection. + + scoring : str or callable, default=None + A single str (see :ref:`scoring_parameter`) or a callable + (see :ref:`scoring`) to evaluate the predictions on the test set. + + NOTE that when using a custom scorer, it should return a single + value. + + If None, the estimator's score method is used. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross validation, + - integer, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For integer/None inputs, if the estimator is a classifier and ``y`` is + either binary or multiclass, :class:`StratifiedKFold` is used. In all + other cases, :class:`KFold` is used. These splitters are instantiated + with `shuffle=False` so the splits will be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + n_jobs : int, default=None + Number of jobs to run in parallel. When evaluating a new feature to + add or remove, the cross-validation procedure is parallel over the + folds. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Attributes + ---------- + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_features_to_select_ : int + The number of features that were selected. + + support_ : ndarray of shape (n_features,), dtype=bool + The mask of selected features. + + See Also + -------- + GenericUnivariateSelect : Univariate feature selector with configurable + strategy. + RFE : Recursive feature elimination based on importance weights. + RFECV : Recursive feature elimination based on importance weights, with + automatic selection of the number of features. + SelectFromModel : Feature selection based on thresholds of importance + weights. + + Examples + -------- + >>> from sklearn.feature_selection import SequentialFeatureSelector + >>> from sklearn.neighbors import KNeighborsClassifier + >>> from sklearn.datasets import load_iris + >>> X, y = load_iris(return_X_y=True) + >>> knn = KNeighborsClassifier(n_neighbors=3) + >>> sfs = SequentialFeatureSelector(knn, n_features_to_select=3) + >>> sfs.fit(X, y) + SequentialFeatureSelector(estimator=KNeighborsClassifier(n_neighbors=3), + n_features_to_select=3) + >>> sfs.get_support() + array([ True, False, True, True]) + >>> sfs.transform(X).shape + (150, 3) + """ + + _parameter_constraints: dict = { + "estimator": [HasMethods(["fit"])], + "n_features_to_select": [ + StrOptions({"auto", "warn"}, deprecated={"warn"}), + Interval(Real, 0, 1, closed="right"), + Interval(Integral, 0, None, closed="neither"), + Hidden(None), + ], + "tol": [None, Interval(Real, None, None, closed="neither")], + "direction": [StrOptions({"forward", "backward"})], + "scoring": [None, StrOptions(set(get_scorer_names())), callable], + "cv": ["cv_object"], + "n_jobs": [None, Integral], + } + + def __init__( + self, + estimator, + *, + n_features_to_select="warn", + tol=None, + direction="forward", + scoring=None, + cv=5, + n_jobs=None, + ): + + self.estimator = estimator + self.n_features_to_select = n_features_to_select + self.tol = tol + self.direction = direction + self.scoring = scoring + self.cv = cv + self.n_jobs = n_jobs + + def fit(self, X, y=None): + """Learn the features to select from X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training vectors, where `n_samples` is the number of samples and + `n_features` is the number of predictors. + + y : array-like of shape (n_samples,), default=None + Target values. This parameter may be ignored for + unsupervised learning. + + Returns + ------- + self : object + Returns the instance itself. + """ + self._validate_params() + + # FIXME: to be removed in 1.3 + if self.n_features_to_select in ("warn", None): + # for backwards compatibility + warnings.warn( + "Leaving `n_features_to_select` to " + "None is deprecated in 1.0 and will become 'auto' " + "in 1.3. To keep the same behaviour as with None " + "(i.e. select half of the features) and avoid " + "this warning, you should manually set " + "`n_features_to_select='auto'` and set tol=None " + "when creating an instance.", + FutureWarning, + ) + + tags = self._get_tags() + X = self._validate_data( + X, + accept_sparse="csc", + ensure_min_features=2, + force_all_finite=not tags.get("allow_nan", True), + ) + n_features = X.shape[1] + + # FIXME: to be fixed in 1.3 + error_msg = ( + "n_features_to_select must be either 'auto', 'warn', " + "None, an integer in [1, n_features - 1] " + "representing the absolute " + "number of features, or a float in (0, 1] " + "representing a percentage of features to " + f"select. Got {self.n_features_to_select}" + ) + if self.n_features_to_select in ("warn", None): + if self.tol is not None: + raise ValueError("tol is only enabled if `n_features_to_select='auto'`") + self.n_features_to_select_ = n_features // 2 + elif self.n_features_to_select == "auto": + if self.tol is not None: + # With auto feature selection, `n_features_to_select_` will be updated + # to `support_.sum()` after features are selected. + self.n_features_to_select_ = n_features - 1 + else: + self.n_features_to_select_ = n_features // 2 + elif isinstance(self.n_features_to_select, Integral): + if not 0 < self.n_features_to_select < n_features: + raise ValueError(error_msg) + self.n_features_to_select_ = self.n_features_to_select + elif isinstance(self.n_features_to_select, Real): + self.n_features_to_select_ = int(n_features * self.n_features_to_select) + + if self.tol is not None and self.tol < 0 and self.direction == "forward": + raise ValueError("tol must be positive when doing forward selection") + + cloned_estimator = clone(self.estimator) + + # the current mask corresponds to the set of features: + # - that we have already *selected* if we do forward selection + # - that we have already *excluded* if we do backward selection + current_mask = np.zeros(shape=n_features, dtype=bool) + n_iterations = ( + self.n_features_to_select_ + if self.n_features_to_select == "auto" or self.direction == "forward" + else n_features - self.n_features_to_select_ + ) + + old_score = -np.inf + is_auto_select = self.tol is not None and self.n_features_to_select == "auto" + for _ in range(n_iterations): + new_feature_idx, new_score = self._get_best_new_feature_score( + cloned_estimator, X, y, current_mask + ) + if is_auto_select and ((new_score - old_score) < self.tol): + break + + old_score = new_score + current_mask[new_feature_idx] = True + + if self.direction == "backward": + current_mask = ~current_mask + + self.support_ = current_mask + self.n_features_to_select_ = self.support_.sum() + + return self + + def _get_best_new_feature_score(self, estimator, X, y, current_mask): + # Return the best new feature and its score to add to the current_mask, + # i.e. return the best new feature and its score to add (resp. remove) + # when doing forward selection (resp. backward selection). + # Feature will be added if the current score and past score are greater + # than tol when n_feature is auto, + candidate_feature_indices = np.flatnonzero(~current_mask) + scores = {} + for feature_idx in candidate_feature_indices: + candidate_mask = current_mask.copy() + candidate_mask[feature_idx] = True + if self.direction == "backward": + candidate_mask = ~candidate_mask + X_new = X[:, candidate_mask] + scores[feature_idx] = cross_val_score( + estimator, + X_new, + y, + cv=self.cv, + scoring=self.scoring, + n_jobs=self.n_jobs, + ).mean() + new_feature_idx = max(scores, key=lambda feature_idx: scores[feature_idx]) + return new_feature_idx, scores[new_feature_idx] + + def _get_support_mask(self): + check_is_fitted(self) + return self.support_ + + def _more_tags(self): + return { + "allow_nan": _safe_tags(self.estimator, key="allow_nan"), + } diff --git a/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_univariate_selection.py b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_univariate_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a53b6c116ddc049a78fc2972447b33cfc630cd --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_univariate_selection.py @@ -0,0 +1,1052 @@ +"""Univariate features selection.""" + +# Authors: V. Michel, B. Thirion, G. Varoquaux, A. Gramfort, E. Duchesnay. +# L. Buitinck, A. Joly +# License: BSD 3 clause + + +import numpy as np +import warnings + +from numbers import Integral, Real +from scipy import special, stats +from scipy.sparse import issparse + +from ..base import BaseEstimator +from ..preprocessing import LabelBinarizer +from ..utils import as_float_array, check_array, check_X_y, safe_sqr, safe_mask +from ..utils.extmath import safe_sparse_dot, row_norms +from ..utils.validation import check_is_fitted +from ..utils._param_validation import Interval, StrOptions +from ._base import SelectorMixin + + +def _clean_nans(scores): + """ + Fixes Issue #1240: NaNs can't be properly compared, so change them to the + smallest value of scores's dtype. -inf seems to be unreliable. + """ + # XXX where should this function be called? fit? scoring functions + # themselves? + scores = as_float_array(scores, copy=True) + scores[np.isnan(scores)] = np.finfo(scores.dtype).min + return scores + + +###################################################################### +# Scoring functions + + +# The following function is a rewriting of scipy.stats.f_oneway +# Contrary to the scipy.stats.f_oneway implementation it does not +# copy the data while keeping the inputs unchanged. +def f_oneway(*args): + """Perform a 1-way ANOVA. + + The one-way ANOVA tests the null hypothesis that 2 or more groups have + the same population mean. The test is applied to samples from two or + more groups, possibly with differing sizes. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + *args : {array-like, sparse matrix} + Sample1, sample2... The sample measurements should be given as + arguments. + + Returns + ------- + f_statistic : float + The computed F-value of the test. + p_value : float + The associated p-value from the F-distribution. + + Notes + ----- + The ANOVA test has important assumptions that must be satisfied in order + for the associated p-value to be valid. + + 1. The samples are independent + 2. Each sample is from a normally distributed population + 3. The population standard deviations of the groups are all equal. This + property is known as homoscedasticity. + + If these assumptions are not true for a given set of data, it may still be + possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`_) although + with some loss of power. + + The algorithm is from Heiman[2], pp.394-7. + + See ``scipy.stats.f_oneway`` that should give the same results while + being less efficient. + + References + ---------- + .. [1] Lowry, Richard. "Concepts and Applications of Inferential + Statistics". Chapter 14. + http://faculty.vassar.edu/lowry/ch14pt1.html + + .. [2] Heiman, G.W. Research Methods in Statistics. 2002. + """ + n_classes = len(args) + args = [as_float_array(a) for a in args] + n_samples_per_class = np.array([a.shape[0] for a in args]) + n_samples = np.sum(n_samples_per_class) + ss_alldata = sum(safe_sqr(a).sum(axis=0) for a in args) + sums_args = [np.asarray(a.sum(axis=0)) for a in args] + square_of_sums_alldata = sum(sums_args) ** 2 + square_of_sums_args = [s**2 for s in sums_args] + sstot = ss_alldata - square_of_sums_alldata / float(n_samples) + ssbn = 0.0 + for k, _ in enumerate(args): + ssbn += square_of_sums_args[k] / n_samples_per_class[k] + ssbn -= square_of_sums_alldata / float(n_samples) + sswn = sstot - ssbn + dfbn = n_classes - 1 + dfwn = n_samples - n_classes + msb = ssbn / float(dfbn) + msw = sswn / float(dfwn) + constant_features_idx = np.where(msw == 0.0)[0] + if np.nonzero(msb)[0].size != msb.size and constant_features_idx.size: + warnings.warn("Features %s are constant." % constant_features_idx, UserWarning) + f = msb / msw + # flatten matrix to vector in sparse case + f = np.asarray(f).ravel() + prob = special.fdtrc(dfbn, dfwn, f) + return f, prob + + +def f_classif(X, y): + """Compute the ANOVA F-value for the provided sample. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The set of regressors that will be tested sequentially. + + y : ndarray of shape (n_samples,) + The target vector. + + Returns + ------- + f_statistic : ndarray of shape (n_features,) + F-statistic for each feature. + + p_values : ndarray of shape (n_features,) + P-values associated with the F-statistic. + + See Also + -------- + chi2 : Chi-squared stats of non-negative features for classification tasks. + f_regression : F-value between label/feature for regression tasks. + """ + X, y = check_X_y(X, y, accept_sparse=["csr", "csc", "coo"]) + args = [X[safe_mask(X, y == k)] for k in np.unique(y)] + return f_oneway(*args) + + +def _chisquare(f_obs, f_exp): + """Fast replacement for scipy.stats.chisquare. + + Version from https://github.com/scipy/scipy/pull/2525 with additional + optimizations. + """ + f_obs = np.asarray(f_obs, dtype=np.float64) + + k = len(f_obs) + # Reuse f_obs for chi-squared statistics + chisq = f_obs + chisq -= f_exp + chisq **= 2 + with np.errstate(invalid="ignore"): + chisq /= f_exp + chisq = chisq.sum(axis=0) + return chisq, special.chdtrc(k - 1, chisq) + + +def chi2(X, y): + """Compute chi-squared stats between each non-negative feature and class. + + This score can be used to select the `n_features` features with the + highest values for the test chi-squared statistic from X, which must + contain only **non-negative features** such as booleans or frequencies + (e.g., term counts in document classification), relative to the classes. + + Recall that the chi-square test measures dependence between stochastic + variables, so using this function "weeds out" the features that are the + most likely to be independent of class and therefore irrelevant for + classification. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Sample vectors. + + y : array-like of shape (n_samples,) + Target vector (class labels). + + Returns + ------- + chi2 : ndarray of shape (n_features,) + Chi2 statistics for each feature. + + p_values : ndarray of shape (n_features,) + P-values for each feature. + + See Also + -------- + f_classif : ANOVA F-value between label/feature for classification tasks. + f_regression : F-value between label/feature for regression tasks. + + Notes + ----- + Complexity of this algorithm is O(n_classes * n_features). + """ + + # XXX: we might want to do some of the following in logspace instead for + # numerical stability. + # Converting X to float allows getting better performance for the + # safe_sparse_dot call made below. + X = check_array(X, accept_sparse="csr", dtype=(np.float64, np.float32)) + if np.any((X.data if issparse(X) else X) < 0): + raise ValueError("Input X must be non-negative.") + + # Use a sparse representation for Y by default to reduce memory usage when + # y has many unique classes. + Y = LabelBinarizer(sparse_output=True).fit_transform(y) + if Y.shape[1] == 1: + Y = Y.toarray() + Y = np.append(1 - Y, Y, axis=1) + + observed = safe_sparse_dot(Y.T, X) # n_classes * n_features + + if issparse(observed): + # convert back to a dense array before calling _chisquare + # XXX: could _chisquare be reimplement to accept sparse matrices for + # cases where both n_classes and n_features are large (and X is + # sparse)? + observed = observed.toarray() + + feature_count = X.sum(axis=0).reshape(1, -1) + class_prob = Y.mean(axis=0).reshape(1, -1) + expected = np.dot(class_prob.T, feature_count) + + return _chisquare(observed, expected) + + +def r_regression(X, y, *, center=True, force_finite=True): + """Compute Pearson's r for each features and the target. + + Pearson's r is also known as the Pearson correlation coefficient. + + Linear model for testing the individual effect of each of many regressors. + This is a scoring function to be used in a feature selection procedure, not + a free standing feature selection procedure. + + The cross correlation between each regressor and the target is computed + as:: + + E[(X[:, i] - mean(X[:, i])) * (y - mean(y))] / (std(X[:, i]) * std(y)) + + For more on usage see the :ref:`User Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data matrix. + + y : array-like of shape (n_samples,) + The target vector. + + center : bool, default=True + Whether or not to center the data matrix `X` and the target vector `y`. + By default, `X` and `y` will be centered. + + force_finite : bool, default=True + Whether or not to force the Pearson's R correlation to be finite. + In the particular case where some features in `X` or the target `y` + are constant, the Pearson's R correlation is not defined. When + `force_finite=False`, a correlation of `np.nan` is returned to + acknowledge this case. When `force_finite=True`, this value will be + forced to a minimal correlation of `0.0`. + + .. versionadded:: 1.1 + + Returns + ------- + correlation_coefficient : ndarray of shape (n_features,) + Pearson's R correlation coefficients of features. + + See Also + -------- + f_regression: Univariate linear regression tests returning f-statistic + and p-values. + mutual_info_regression: Mutual information for a continuous target. + f_classif: ANOVA F-value between label/feature for classification tasks. + chi2: Chi-squared stats of non-negative features for classification tasks. + """ + X, y = check_X_y(X, y, accept_sparse=["csr", "csc", "coo"], dtype=np.float64) + n_samples = X.shape[0] + + # Compute centered values + # Note that E[(x - mean(x))*(y - mean(y))] = E[x*(y - mean(y))], so we + # need not center X + if center: + y = y - np.mean(y) + if issparse(X): + X_means = X.mean(axis=0).getA1() + else: + X_means = X.mean(axis=0) + # Compute the scaled standard deviations via moments + X_norms = np.sqrt(row_norms(X.T, squared=True) - n_samples * X_means**2) + else: + X_norms = row_norms(X.T) + + correlation_coefficient = safe_sparse_dot(y, X) + with np.errstate(divide="ignore", invalid="ignore"): + correlation_coefficient /= X_norms + correlation_coefficient /= np.linalg.norm(y) + + if force_finite and not np.isfinite(correlation_coefficient).all(): + # case where the target or some features are constant + # the correlation coefficient(s) is/are set to the minimum (i.e. 0.0) + nan_mask = np.isnan(correlation_coefficient) + correlation_coefficient[nan_mask] = 0.0 + return correlation_coefficient + + +def f_regression(X, y, *, center=True, force_finite=True): + """Univariate linear regression tests returning F-statistic and p-values. + + Quick linear model for testing the effect of a single regressor, + sequentially for many regressors. + + This is done in 2 steps: + + 1. The cross correlation between each regressor and the target is computed + using :func:`r_regression` as:: + + E[(X[:, i] - mean(X[:, i])) * (y - mean(y))] / (std(X[:, i]) * std(y)) + + 2. It is converted to an F score and then to a p-value. + + :func:`f_regression` is derived from :func:`r_regression` and will rank + features in the same order if all the features are positively correlated + with the target. + + Note however that contrary to :func:`f_regression`, :func:`r_regression` + values lie in [-1, 1] and can thus be negative. :func:`f_regression` is + therefore recommended as a feature selection criterion to identify + potentially predictive feature for a downstream classifier, irrespective of + the sign of the association with the target variable. + + Furthermore :func:`f_regression` returns p-values while + :func:`r_regression` does not. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data matrix. + + y : array-like of shape (n_samples,) + The target vector. + + center : bool, default=True + Whether or not to center the data matrix `X` and the target vector `y`. + By default, `X` and `y` will be centered. + + force_finite : bool, default=True + Whether or not to force the F-statistics and associated p-values to + be finite. There are two cases where the F-statistic is expected to not + be finite: + + - when the target `y` or some features in `X` are constant. In this + case, the Pearson's R correlation is not defined leading to obtain + `np.nan` values in the F-statistic and p-value. When + `force_finite=True`, the F-statistic is set to `0.0` and the + associated p-value is set to `1.0`. + - when a feature in `X` is perfectly correlated (or + anti-correlated) with the target `y`. In this case, the F-statistic + is expected to be `np.inf`. When `force_finite=True`, the F-statistic + is set to `np.finfo(dtype).max` and the associated p-value is set to + `0.0`. + + .. versionadded:: 1.1 + + Returns + ------- + f_statistic : ndarray of shape (n_features,) + F-statistic for each feature. + + p_values : ndarray of shape (n_features,) + P-values associated with the F-statistic. + + See Also + -------- + r_regression: Pearson's R between label/feature for regression tasks. + f_classif: ANOVA F-value between label/feature for classification tasks. + chi2: Chi-squared stats of non-negative features for classification tasks. + SelectKBest: Select features based on the k highest scores. + SelectFpr: Select features based on a false positive rate test. + SelectFdr: Select features based on an estimated false discovery rate. + SelectFwe: Select features based on family-wise error rate. + SelectPercentile: Select features based on percentile of the highest + scores. + """ + correlation_coefficient = r_regression( + X, y, center=center, force_finite=force_finite + ) + deg_of_freedom = y.size - (2 if center else 1) + + corr_coef_squared = correlation_coefficient**2 + + with np.errstate(divide="ignore", invalid="ignore"): + f_statistic = corr_coef_squared / (1 - corr_coef_squared) * deg_of_freedom + p_values = stats.f.sf(f_statistic, 1, deg_of_freedom) + + if force_finite and not np.isfinite(f_statistic).all(): + # case where there is a perfect (anti-)correlation + # f-statistics can be set to the maximum and p-values to zero + mask_inf = np.isinf(f_statistic) + f_statistic[mask_inf] = np.finfo(f_statistic.dtype).max + # case where the target or some features are constant + # f-statistics would be minimum and thus p-values large + mask_nan = np.isnan(f_statistic) + f_statistic[mask_nan] = 0.0 + p_values[mask_nan] = 1.0 + return f_statistic, p_values + + +###################################################################### +# Base classes + + +class _BaseFilter(SelectorMixin, BaseEstimator): + """Initialize the univariate feature selection. + + Parameters + ---------- + score_func : callable + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues) or a single array with scores. + """ + + _parameter_constraints: dict = {"score_func": [callable]} + + def __init__(self, score_func): + self.score_func = score_func + + def fit(self, X, y): + """Run score function on (X, y) and get the appropriate features. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The training input samples. + + y : array-like of shape (n_samples,) + The target values (class labels in classification, real numbers in + regression). + + Returns + ------- + self : object + Returns the instance itself. + """ + self._validate_params() + + X, y = self._validate_data( + X, y, accept_sparse=["csr", "csc"], multi_output=True + ) + + self._check_params(X, y) + score_func_ret = self.score_func(X, y) + if isinstance(score_func_ret, (list, tuple)): + self.scores_, self.pvalues_ = score_func_ret + self.pvalues_ = np.asarray(self.pvalues_) + else: + self.scores_ = score_func_ret + self.pvalues_ = None + + self.scores_ = np.asarray(self.scores_) + + return self + + def _check_params(self, X, y): + pass + + def _more_tags(self): + return {"requires_y": True} + + +###################################################################### +# Specific filters +###################################################################### +class SelectPercentile(_BaseFilter): + """Select features according to a percentile of the highest scores. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable, default=f_classif + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues) or a single array with scores. + Default is f_classif (see below "See Also"). The default function only + works with classification tasks. + + .. versionadded:: 0.18 + + percentile : int, default=10 + Percent of features to keep. + + Attributes + ---------- + scores_ : array-like of shape (n_features,) + Scores of features. + + pvalues_ : array-like of shape (n_features,) + p-values of feature scores, None if `score_func` returned only scores. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + f_classif : ANOVA F-value between label/feature for classification tasks. + mutual_info_classif : Mutual information for a discrete target. + chi2 : Chi-squared stats of non-negative features for classification tasks. + f_regression : F-value between label/feature for regression tasks. + mutual_info_regression : Mutual information for a continuous target. + SelectKBest : Select features based on the k highest scores. + SelectFpr : Select features based on a false positive rate test. + SelectFdr : Select features based on an estimated false discovery rate. + SelectFwe : Select features based on family-wise error rate. + GenericUnivariateSelect : Univariate feature selector with configurable + mode. + + Notes + ----- + Ties between features with equal scores will be broken in an unspecified + way. + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.feature_selection import SelectPercentile, chi2 + >>> X, y = load_digits(return_X_y=True) + >>> X.shape + (1797, 64) + >>> X_new = SelectPercentile(chi2, percentile=10).fit_transform(X, y) + >>> X_new.shape + (1797, 7) + """ + + _parameter_constraints: dict = { + **_BaseFilter._parameter_constraints, + "percentile": [Interval(Real, 0, 100, closed="both")], + } + + def __init__(self, score_func=f_classif, *, percentile=10): + super().__init__(score_func=score_func) + self.percentile = percentile + + def _get_support_mask(self): + check_is_fitted(self) + + # Cater for NaNs + if self.percentile == 100: + return np.ones(len(self.scores_), dtype=bool) + elif self.percentile == 0: + return np.zeros(len(self.scores_), dtype=bool) + + scores = _clean_nans(self.scores_) + threshold = np.percentile(scores, 100 - self.percentile) + mask = scores > threshold + ties = np.where(scores == threshold)[0] + if len(ties): + max_feats = int(len(scores) * self.percentile / 100) + kept_ties = ties[: max_feats - mask.sum()] + mask[kept_ties] = True + return mask + + +class SelectKBest(_BaseFilter): + """Select features according to the k highest scores. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable, default=f_classif + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues) or a single array with scores. + Default is f_classif (see below "See Also"). The default function only + works with classification tasks. + + .. versionadded:: 0.18 + + k : int or "all", default=10 + Number of top features to select. + The "all" option bypasses selection, for use in a parameter search. + + Attributes + ---------- + scores_ : array-like of shape (n_features,) + Scores of features. + + pvalues_ : array-like of shape (n_features,) + p-values of feature scores, None if `score_func` returned only scores. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + f_classif: ANOVA F-value between label/feature for classification tasks. + mutual_info_classif: Mutual information for a discrete target. + chi2: Chi-squared stats of non-negative features for classification tasks. + f_regression: F-value between label/feature for regression tasks. + mutual_info_regression: Mutual information for a continuous target. + SelectPercentile: Select features based on percentile of the highest + scores. + SelectFpr : Select features based on a false positive rate test. + SelectFdr : Select features based on an estimated false discovery rate. + SelectFwe : Select features based on family-wise error rate. + GenericUnivariateSelect : Univariate feature selector with configurable + mode. + + Notes + ----- + Ties between features with equal scores will be broken in an unspecified + way. + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.feature_selection import SelectKBest, chi2 + >>> X, y = load_digits(return_X_y=True) + >>> X.shape + (1797, 64) + >>> X_new = SelectKBest(chi2, k=20).fit_transform(X, y) + >>> X_new.shape + (1797, 20) + """ + + _parameter_constraints: dict = { + **_BaseFilter._parameter_constraints, + "k": [StrOptions({"all"}), Interval(Integral, 0, None, closed="left")], + } + + def __init__(self, score_func=f_classif, *, k=10): + super().__init__(score_func=score_func) + self.k = k + + def _check_params(self, X, y): + if not isinstance(self.k, str) and self.k > X.shape[1]: + raise ValueError( + f"k should be <= n_features = {X.shape[1]}; " + f"got {self.k}. Use k='all' to return all features." + ) + + def _get_support_mask(self): + check_is_fitted(self) + + if self.k == "all": + return np.ones(self.scores_.shape, dtype=bool) + elif self.k == 0: + return np.zeros(self.scores_.shape, dtype=bool) + else: + scores = _clean_nans(self.scores_) + mask = np.zeros(scores.shape, dtype=bool) + + # Request a stable sort. Mergesort takes more memory (~40MB per + # megafeature on x86-64). + mask[np.argsort(scores, kind="mergesort")[-self.k :]] = 1 + return mask + + +class SelectFpr(_BaseFilter): + """Filter: Select the pvalues below alpha based on a FPR test. + + FPR test stands for False Positive Rate test. It controls the total + amount of false detections. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable, default=f_classif + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues). + Default is f_classif (see below "See Also"). The default function only + works with classification tasks. + + alpha : float, default=5e-2 + Features with p-values less than `alpha` are selected. + + Attributes + ---------- + scores_ : array-like of shape (n_features,) + Scores of features. + + pvalues_ : array-like of shape (n_features,) + p-values of feature scores. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + f_classif : ANOVA F-value between label/feature for classification tasks. + chi2 : Chi-squared stats of non-negative features for classification tasks. + mutual_info_classif: Mutual information for a discrete target. + f_regression : F-value between label/feature for regression tasks. + mutual_info_regression : Mutual information for a continuous target. + SelectPercentile : Select features based on percentile of the highest + scores. + SelectKBest : Select features based on the k highest scores. + SelectFdr : Select features based on an estimated false discovery rate. + SelectFwe : Select features based on family-wise error rate. + GenericUnivariateSelect : Univariate feature selector with configurable + mode. + + Examples + -------- + >>> from sklearn.datasets import load_breast_cancer + >>> from sklearn.feature_selection import SelectFpr, chi2 + >>> X, y = load_breast_cancer(return_X_y=True) + >>> X.shape + (569, 30) + >>> X_new = SelectFpr(chi2, alpha=0.01).fit_transform(X, y) + >>> X_new.shape + (569, 16) + """ + + _parameter_constraints: dict = { + **_BaseFilter._parameter_constraints, + "alpha": [Interval(Real, 0, 1, closed="both")], + } + + def __init__(self, score_func=f_classif, *, alpha=5e-2): + super().__init__(score_func=score_func) + self.alpha = alpha + + def _get_support_mask(self): + check_is_fitted(self) + + return self.pvalues_ < self.alpha + + +class SelectFdr(_BaseFilter): + """Filter: Select the p-values for an estimated false discovery rate. + + This uses the Benjamini-Hochberg procedure. ``alpha`` is an upper bound + on the expected false discovery rate. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable, default=f_classif + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues). + Default is f_classif (see below "See Also"). The default function only + works with classification tasks. + + alpha : float, default=5e-2 + The highest uncorrected p-value for features to keep. + + Attributes + ---------- + scores_ : array-like of shape (n_features,) + Scores of features. + + pvalues_ : array-like of shape (n_features,) + p-values of feature scores. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + f_classif : ANOVA F-value between label/feature for classification tasks. + mutual_info_classif : Mutual information for a discrete target. + chi2 : Chi-squared stats of non-negative features for classification tasks. + f_regression : F-value between label/feature for regression tasks. + mutual_info_regression : Mutual information for a continuous target. + SelectPercentile : Select features based on percentile of the highest + scores. + SelectKBest : Select features based on the k highest scores. + SelectFpr : Select features based on a false positive rate test. + SelectFwe : Select features based on family-wise error rate. + GenericUnivariateSelect : Univariate feature selector with configurable + mode. + + References + ---------- + https://en.wikipedia.org/wiki/False_discovery_rate + + Examples + -------- + >>> from sklearn.datasets import load_breast_cancer + >>> from sklearn.feature_selection import SelectFdr, chi2 + >>> X, y = load_breast_cancer(return_X_y=True) + >>> X.shape + (569, 30) + >>> X_new = SelectFdr(chi2, alpha=0.01).fit_transform(X, y) + >>> X_new.shape + (569, 16) + """ + + _parameter_constraints: dict = { + **_BaseFilter._parameter_constraints, + "alpha": [Interval(Real, 0, 1, closed="both")], + } + + def __init__(self, score_func=f_classif, *, alpha=5e-2): + super().__init__(score_func=score_func) + self.alpha = alpha + + def _get_support_mask(self): + check_is_fitted(self) + + n_features = len(self.pvalues_) + sv = np.sort(self.pvalues_) + selected = sv[ + sv <= float(self.alpha) / n_features * np.arange(1, n_features + 1) + ] + if selected.size == 0: + return np.zeros_like(self.pvalues_, dtype=bool) + return self.pvalues_ <= selected.max() + + +class SelectFwe(_BaseFilter): + """Filter: Select the p-values corresponding to Family-wise error rate. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable, default=f_classif + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues). + Default is f_classif (see below "See Also"). The default function only + works with classification tasks. + + alpha : float, default=5e-2 + The highest uncorrected p-value for features to keep. + + Attributes + ---------- + scores_ : array-like of shape (n_features,) + Scores of features. + + pvalues_ : array-like of shape (n_features,) + p-values of feature scores. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + f_classif : ANOVA F-value between label/feature for classification tasks. + chi2 : Chi-squared stats of non-negative features for classification tasks. + f_regression : F-value between label/feature for regression tasks. + SelectPercentile : Select features based on percentile of the highest + scores. + SelectKBest : Select features based on the k highest scores. + SelectFpr : Select features based on a false positive rate test. + SelectFdr : Select features based on an estimated false discovery rate. + GenericUnivariateSelect : Univariate feature selector with configurable + mode. + + Examples + -------- + >>> from sklearn.datasets import load_breast_cancer + >>> from sklearn.feature_selection import SelectFwe, chi2 + >>> X, y = load_breast_cancer(return_X_y=True) + >>> X.shape + (569, 30) + >>> X_new = SelectFwe(chi2, alpha=0.01).fit_transform(X, y) + >>> X_new.shape + (569, 15) + """ + + _parameter_constraints: dict = { + **_BaseFilter._parameter_constraints, + "alpha": [Interval(Real, 0, 1, closed="both")], + } + + def __init__(self, score_func=f_classif, *, alpha=5e-2): + super().__init__(score_func=score_func) + self.alpha = alpha + + def _get_support_mask(self): + check_is_fitted(self) + + return self.pvalues_ < self.alpha / len(self.pvalues_) + + +###################################################################### +# Generic filter +###################################################################### + +# TODO this class should fit on either p-values or scores, +# depending on the mode. +class GenericUnivariateSelect(_BaseFilter): + """Univariate feature selector with configurable strategy. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable, default=f_classif + Function taking two arrays X and y, and returning a pair of arrays + (scores, pvalues). For modes 'percentile' or 'kbest' it can return + a single array scores. + + mode : {'percentile', 'k_best', 'fpr', 'fdr', 'fwe'}, default='percentile' + Feature selection mode. + + param : "all", float or int, default=1e-5 + Parameter of the corresponding mode. + + Attributes + ---------- + scores_ : array-like of shape (n_features,) + Scores of features. + + pvalues_ : array-like of shape (n_features,) + p-values of feature scores, None if `score_func` returned scores only. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + f_classif : ANOVA F-value between label/feature for classification tasks. + mutual_info_classif : Mutual information for a discrete target. + chi2 : Chi-squared stats of non-negative features for classification tasks. + f_regression : F-value between label/feature for regression tasks. + mutual_info_regression : Mutual information for a continuous target. + SelectPercentile : Select features based on percentile of the highest + scores. + SelectKBest : Select features based on the k highest scores. + SelectFpr : Select features based on a false positive rate test. + SelectFdr : Select features based on an estimated false discovery rate. + SelectFwe : Select features based on family-wise error rate. + + Examples + -------- + >>> from sklearn.datasets import load_breast_cancer + >>> from sklearn.feature_selection import GenericUnivariateSelect, chi2 + >>> X, y = load_breast_cancer(return_X_y=True) + >>> X.shape + (569, 30) + >>> transformer = GenericUnivariateSelect(chi2, mode='k_best', param=20) + >>> X_new = transformer.fit_transform(X, y) + >>> X_new.shape + (569, 20) + """ + + _selection_modes: dict = { + "percentile": SelectPercentile, + "k_best": SelectKBest, + "fpr": SelectFpr, + "fdr": SelectFdr, + "fwe": SelectFwe, + } + + _parameter_constraints: dict = { + **_BaseFilter._parameter_constraints, + "mode": [StrOptions(set(_selection_modes.keys()))], + "param": [Interval(Real, 0, None, closed="left"), StrOptions({"all"})], + } + + def __init__(self, score_func=f_classif, *, mode="percentile", param=1e-5): + super().__init__(score_func=score_func) + self.mode = mode + self.param = param + + def _make_selector(self): + selector = self._selection_modes[self.mode](score_func=self.score_func) + + # Now perform some acrobatics to set the right named parameter in + # the selector + possible_params = selector._get_param_names() + possible_params.remove("score_func") + selector.set_params(**{possible_params[0]: self.param}) + + return selector + + def _more_tags(self): + return {"preserves_dtype": [np.float64, np.float32]} + + def _check_params(self, X, y): + self._make_selector()._check_params(X, y) + + def _get_support_mask(self): + check_is_fitted(self) + + selector = self._make_selector() + selector.pvalues_ = self.pvalues_ + selector.scores_ = self.scores_ + return selector._get_support_mask() diff --git a/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_variance_threshold.py b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_variance_threshold.py new file mode 100644 index 0000000000000000000000000000000000000000..7c8db9cc7fa55cf79a442a8964a263d799df8032 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_variance_threshold.py @@ -0,0 +1,135 @@ +# Author: Lars Buitinck +# License: 3-clause BSD +from numbers import Real + +import numpy as np +from ..base import BaseEstimator +from ._base import SelectorMixin +from ..utils.sparsefuncs import mean_variance_axis, min_max_axis +from ..utils.validation import check_is_fitted +from ..utils._param_validation import Interval + + +class VarianceThreshold(SelectorMixin, BaseEstimator): + """Feature selector that removes all low-variance features. + + This feature selection algorithm looks only at the features (X), not the + desired outputs (y), and can thus be used for unsupervised learning. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + threshold : float, default=0 + Features with a training-set variance lower than this threshold will + be removed. The default is to keep all features with non-zero variance, + i.e. remove the features that have the same value in all samples. + + Attributes + ---------- + variances_ : array, shape (n_features,) + Variances of individual features. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + SelectFromModel: Meta-transformer for selecting features based on + importance weights. + SelectPercentile : Select features according to a percentile of the highest + scores. + SequentialFeatureSelector : Transformer that performs Sequential Feature + Selection. + + Notes + ----- + Allows NaN in the input. + Raises ValueError if no feature in X meets the variance threshold. + + Examples + -------- + The following dataset has integer features, two of which are the same + in every sample. These are removed with the default setting for threshold:: + + >>> from sklearn.feature_selection import VarianceThreshold + >>> X = [[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]] + >>> selector = VarianceThreshold() + >>> selector.fit_transform(X) + array([[2, 0], + [1, 4], + [1, 1]]) + """ + + _parameter_constraints: dict = { + "threshold": [Interval(Real, 0, None, closed="left")] + } + + def __init__(self, threshold=0.0): + self.threshold = threshold + + def fit(self, X, y=None): + """Learn empirical variances from X. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Data from which to compute variances, where `n_samples` is + the number of samples and `n_features` is the number of features. + + y : any, default=None + Ignored. This parameter exists only for compatibility with + sklearn.pipeline.Pipeline. + + Returns + ------- + self : object + Returns the instance itself. + """ + self._validate_params() + X = self._validate_data( + X, + accept_sparse=("csr", "csc"), + dtype=np.float64, + force_all_finite="allow-nan", + ) + + if hasattr(X, "toarray"): # sparse matrix + _, self.variances_ = mean_variance_axis(X, axis=0) + if self.threshold == 0: + mins, maxes = min_max_axis(X, axis=0) + peak_to_peaks = maxes - mins + else: + self.variances_ = np.nanvar(X, axis=0) + if self.threshold == 0: + peak_to_peaks = np.ptp(X, axis=0) + + if self.threshold == 0: + # Use peak-to-peak to avoid numeric precision issues + # for constant features + compare_arr = np.array([self.variances_, peak_to_peaks]) + self.variances_ = np.nanmin(compare_arr, axis=0) + + if np.all(~np.isfinite(self.variances_) | (self.variances_ <= self.threshold)): + msg = "No feature in X meets the variance threshold {0:.5f}" + if X.shape[0] == 1: + msg += " (X contains only one sample)" + raise ValueError(msg.format(self.threshold)) + + return self + + def _get_support_mask(self): + check_is_fitted(self) + + return self.variances_ > self.threshold + + def _more_tags(self): + return {"allow_nan": True} diff --git a/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_feature_select.py b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_feature_select.py new file mode 100644 index 0000000000000000000000000000000000000000..df8d2134ecf0e94991d9246a07825a18332c7dc7 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_feature_select.py @@ -0,0 +1,946 @@ +""" +Todo: cross-check the F-value with stats model +""" +import itertools +import warnings +import numpy as np +from numpy.testing import assert_allclose +from scipy import stats, sparse + +import pytest + +from sklearn.utils._testing import assert_almost_equal, _convert_container +from sklearn.utils._testing import assert_array_equal +from sklearn.utils._testing import assert_array_almost_equal +from sklearn.utils._testing import ignore_warnings +from sklearn.utils import safe_mask + +from sklearn.datasets import make_classification, make_regression +from sklearn.feature_selection import ( + chi2, + f_classif, + f_oneway, + f_regression, + GenericUnivariateSelect, + mutual_info_classif, + mutual_info_regression, + r_regression, + SelectPercentile, + SelectKBest, + SelectFpr, + SelectFdr, + SelectFwe, +) + + +############################################################################## +# Test the score functions + + +def test_f_oneway_vs_scipy_stats(): + # Test that our f_oneway gives the same result as scipy.stats + rng = np.random.RandomState(0) + X1 = rng.randn(10, 3) + X2 = 1 + rng.randn(10, 3) + f, pv = stats.f_oneway(X1, X2) + f2, pv2 = f_oneway(X1, X2) + assert np.allclose(f, f2) + assert np.allclose(pv, pv2) + + +def test_f_oneway_ints(): + # Smoke test f_oneway on integers: that it does raise casting errors + # with recent numpys + rng = np.random.RandomState(0) + X = rng.randint(10, size=(10, 10)) + y = np.arange(10) + fint, pint = f_oneway(X, y) + + # test that is gives the same result as with float + f, p = f_oneway(X.astype(float), y) + assert_array_almost_equal(f, fint, decimal=4) + assert_array_almost_equal(p, pint, decimal=4) + + +def test_f_classif(): + # Test whether the F test yields meaningful results + # on a simple simulated classification problem + X, y = make_classification( + n_samples=200, + n_features=20, + n_informative=3, + n_redundant=2, + n_repeated=0, + n_classes=8, + n_clusters_per_class=1, + flip_y=0.0, + class_sep=10, + shuffle=False, + random_state=0, + ) + + F, pv = f_classif(X, y) + F_sparse, pv_sparse = f_classif(sparse.csr_matrix(X), y) + assert (F > 0).all() + assert (pv > 0).all() + assert (pv < 1).all() + assert (pv[:5] < 0.05).all() + assert (pv[5:] > 1.0e-4).all() + assert_array_almost_equal(F_sparse, F) + assert_array_almost_equal(pv_sparse, pv) + + +@pytest.mark.parametrize("center", [True, False]) +def test_r_regression(center): + X, y = make_regression( + n_samples=2000, n_features=20, n_informative=5, shuffle=False, random_state=0 + ) + + corr_coeffs = r_regression(X, y, center=center) + assert (-1 < corr_coeffs).all() + assert (corr_coeffs < 1).all() + + sparse_X = _convert_container(X, "sparse") + + sparse_corr_coeffs = r_regression(sparse_X, y, center=center) + assert_allclose(sparse_corr_coeffs, corr_coeffs) + + # Testing against numpy for reference + Z = np.hstack((X, y[:, np.newaxis])) + correlation_matrix = np.corrcoef(Z, rowvar=False) + np_corr_coeffs = correlation_matrix[:-1, -1] + assert_array_almost_equal(np_corr_coeffs, corr_coeffs, decimal=3) + + +def test_f_regression(): + # Test whether the F test yields meaningful results + # on a simple simulated regression problem + X, y = make_regression( + n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0 + ) + + F, pv = f_regression(X, y) + assert (F > 0).all() + assert (pv > 0).all() + assert (pv < 1).all() + assert (pv[:5] < 0.05).all() + assert (pv[5:] > 1.0e-4).all() + + # with centering, compare with sparse + F, pv = f_regression(X, y, center=True) + F_sparse, pv_sparse = f_regression(sparse.csr_matrix(X), y, center=True) + assert_allclose(F_sparse, F) + assert_allclose(pv_sparse, pv) + + # again without centering, compare with sparse + F, pv = f_regression(X, y, center=False) + F_sparse, pv_sparse = f_regression(sparse.csr_matrix(X), y, center=False) + assert_allclose(F_sparse, F) + assert_allclose(pv_sparse, pv) + + +def test_f_regression_input_dtype(): + # Test whether f_regression returns the same value + # for any numeric data_type + rng = np.random.RandomState(0) + X = rng.rand(10, 20) + y = np.arange(10).astype(int) + + F1, pv1 = f_regression(X, y) + F2, pv2 = f_regression(X, y.astype(float)) + assert_allclose(F1, F2, 5) + assert_allclose(pv1, pv2, 5) + + +def test_f_regression_center(): + # Test whether f_regression preserves dof according to 'center' argument + # We use two centered variates so we have a simple relationship between + # F-score with variates centering and F-score without variates centering. + # Create toy example + X = np.arange(-5, 6).reshape(-1, 1) # X has zero mean + n_samples = X.size + Y = np.ones(n_samples) + Y[::2] *= -1.0 + Y[0] = 0.0 # have Y mean being null + + F1, _ = f_regression(X, Y, center=True) + F2, _ = f_regression(X, Y, center=False) + assert_allclose(F1 * (n_samples - 1.0) / (n_samples - 2.0), F2) + assert_almost_equal(F2[0], 0.232558139) # value from statsmodels OLS + + +@pytest.mark.parametrize( + "X, y, expected_corr_coef, force_finite", + [ + ( + # A feature in X is constant - forcing finite + np.array([[2, 1], [2, 0], [2, 10], [2, 4]]), + np.array([0, 1, 1, 0]), + np.array([0.0, 0.32075]), + True, + ), + ( + # The target y is constant - forcing finite + np.array([[5, 1], [3, 0], [2, 10], [8, 4]]), + np.array([0, 0, 0, 0]), + np.array([0.0, 0.0]), + True, + ), + ( + # A feature in X is constant - not forcing finite + np.array([[2, 1], [2, 0], [2, 10], [2, 4]]), + np.array([0, 1, 1, 0]), + np.array([np.nan, 0.32075]), + False, + ), + ( + # The target y is constant - not forcing finite + np.array([[5, 1], [3, 0], [2, 10], [8, 4]]), + np.array([0, 0, 0, 0]), + np.array([np.nan, np.nan]), + False, + ), + ], +) +def test_r_regression_force_finite(X, y, expected_corr_coef, force_finite): + """Check the behaviour of `force_finite` for some corner cases with `r_regression`. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/15672 + """ + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + corr_coef = r_regression(X, y, force_finite=force_finite) + np.testing.assert_array_almost_equal(corr_coef, expected_corr_coef) + + +@pytest.mark.parametrize( + "X, y, expected_f_statistic, expected_p_values, force_finite", + [ + ( + # A feature in X is constant - forcing finite + np.array([[2, 1], [2, 0], [2, 10], [2, 4]]), + np.array([0, 1, 1, 0]), + np.array([0.0, 0.2293578]), + np.array([1.0, 0.67924985]), + True, + ), + ( + # The target y is constant - forcing finite + np.array([[5, 1], [3, 0], [2, 10], [8, 4]]), + np.array([0, 0, 0, 0]), + np.array([0.0, 0.0]), + np.array([1.0, 1.0]), + True, + ), + ( + # Feature in X correlated with y - forcing finite + np.array([[0, 1], [1, 0], [2, 10], [3, 4]]), + np.array([0, 1, 2, 3]), + np.array([np.finfo(np.float64).max, 0.845433]), + np.array([0.0, 0.454913]), + True, + ), + ( + # Feature in X anti-correlated with y - forcing finite + np.array([[3, 1], [2, 0], [1, 10], [0, 4]]), + np.array([0, 1, 2, 3]), + np.array([np.finfo(np.float64).max, 0.845433]), + np.array([0.0, 0.454913]), + True, + ), + ( + # A feature in X is constant - not forcing finite + np.array([[2, 1], [2, 0], [2, 10], [2, 4]]), + np.array([0, 1, 1, 0]), + np.array([np.nan, 0.2293578]), + np.array([np.nan, 0.67924985]), + False, + ), + ( + # The target y is constant - not forcing finite + np.array([[5, 1], [3, 0], [2, 10], [8, 4]]), + np.array([0, 0, 0, 0]), + np.array([np.nan, np.nan]), + np.array([np.nan, np.nan]), + False, + ), + ( + # Feature in X correlated with y - not forcing finite + np.array([[0, 1], [1, 0], [2, 10], [3, 4]]), + np.array([0, 1, 2, 3]), + np.array([np.inf, 0.845433]), + np.array([0.0, 0.454913]), + False, + ), + ( + # Feature in X anti-correlated with y - not forcing finite + np.array([[3, 1], [2, 0], [1, 10], [0, 4]]), + np.array([0, 1, 2, 3]), + np.array([np.inf, 0.845433]), + np.array([0.0, 0.454913]), + False, + ), + ], +) +def test_f_regression_corner_case( + X, y, expected_f_statistic, expected_p_values, force_finite +): + """Check the behaviour of `force_finite` for some corner cases with `f_regression`. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/15672 + """ + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + f_statistic, p_values = f_regression(X, y, force_finite=force_finite) + np.testing.assert_array_almost_equal(f_statistic, expected_f_statistic) + np.testing.assert_array_almost_equal(p_values, expected_p_values) + + +def test_f_classif_multi_class(): + # Test whether the F test yields meaningful results + # on a simple simulated classification problem + X, y = make_classification( + n_samples=200, + n_features=20, + n_informative=3, + n_redundant=2, + n_repeated=0, + n_classes=8, + n_clusters_per_class=1, + flip_y=0.0, + class_sep=10, + shuffle=False, + random_state=0, + ) + + F, pv = f_classif(X, y) + assert (F > 0).all() + assert (pv > 0).all() + assert (pv < 1).all() + assert (pv[:5] < 0.05).all() + assert (pv[5:] > 1.0e-4).all() + + +def test_select_percentile_classif(): + # Test whether the relative univariate feature selection + # gets the correct items in a simple classification problem + # with the percentile heuristic + X, y = make_classification( + n_samples=200, + n_features=20, + n_informative=3, + n_redundant=2, + n_repeated=0, + n_classes=8, + n_clusters_per_class=1, + flip_y=0.0, + class_sep=10, + shuffle=False, + random_state=0, + ) + + univariate_filter = SelectPercentile(f_classif, percentile=25) + X_r = univariate_filter.fit(X, y).transform(X) + X_r2 = ( + GenericUnivariateSelect(f_classif, mode="percentile", param=25) + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + gtruth = np.zeros(20) + gtruth[:5] = 1 + assert_array_equal(support, gtruth) + + +def test_select_percentile_classif_sparse(): + # Test whether the relative univariate feature selection + # gets the correct items in a simple classification problem + # with the percentile heuristic + X, y = make_classification( + n_samples=200, + n_features=20, + n_informative=3, + n_redundant=2, + n_repeated=0, + n_classes=8, + n_clusters_per_class=1, + flip_y=0.0, + class_sep=10, + shuffle=False, + random_state=0, + ) + X = sparse.csr_matrix(X) + univariate_filter = SelectPercentile(f_classif, percentile=25) + X_r = univariate_filter.fit(X, y).transform(X) + X_r2 = ( + GenericUnivariateSelect(f_classif, mode="percentile", param=25) + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r.toarray(), X_r2.toarray()) + support = univariate_filter.get_support() + gtruth = np.zeros(20) + gtruth[:5] = 1 + assert_array_equal(support, gtruth) + + X_r2inv = univariate_filter.inverse_transform(X_r2) + assert sparse.issparse(X_r2inv) + support_mask = safe_mask(X_r2inv, support) + assert X_r2inv.shape == X.shape + assert_array_equal(X_r2inv[:, support_mask].toarray(), X_r.toarray()) + # Check other columns are empty + assert X_r2inv.getnnz() == X_r.getnnz() + + +############################################################################## +# Test univariate selection in classification settings + + +def test_select_kbest_classif(): + # Test whether the relative univariate feature selection + # gets the correct items in a simple classification problem + # with the k best heuristic + X, y = make_classification( + n_samples=200, + n_features=20, + n_informative=3, + n_redundant=2, + n_repeated=0, + n_classes=8, + n_clusters_per_class=1, + flip_y=0.0, + class_sep=10, + shuffle=False, + random_state=0, + ) + + univariate_filter = SelectKBest(f_classif, k=5) + X_r = univariate_filter.fit(X, y).transform(X) + X_r2 = ( + GenericUnivariateSelect(f_classif, mode="k_best", param=5) + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + gtruth = np.zeros(20) + gtruth[:5] = 1 + assert_array_equal(support, gtruth) + + +def test_select_kbest_all(): + # Test whether k="all" correctly returns all features. + X, y = make_classification( + n_samples=20, n_features=10, shuffle=False, random_state=0 + ) + + univariate_filter = SelectKBest(f_classif, k="all") + X_r = univariate_filter.fit(X, y).transform(X) + assert_array_equal(X, X_r) + # Non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/24949 + X_r2 = ( + GenericUnivariateSelect(f_classif, mode="k_best", param="all") + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r, X_r2) + + +@pytest.mark.parametrize("dtype_in", [np.float32, np.float64]) +def test_select_kbest_zero(dtype_in): + # Test whether k=0 correctly returns no features. + X, y = make_classification( + n_samples=20, n_features=10, shuffle=False, random_state=0 + ) + X = X.astype(dtype_in) + + univariate_filter = SelectKBest(f_classif, k=0) + univariate_filter.fit(X, y) + support = univariate_filter.get_support() + gtruth = np.zeros(10, dtype=bool) + assert_array_equal(support, gtruth) + with pytest.warns(UserWarning, match="No features were selected"): + X_selected = univariate_filter.transform(X) + assert X_selected.shape == (20, 0) + assert X_selected.dtype == dtype_in + + +def test_select_heuristics_classif(): + # Test whether the relative univariate feature selection + # gets the correct items in a simple classification problem + # with the fdr, fwe and fpr heuristics + X, y = make_classification( + n_samples=200, + n_features=20, + n_informative=3, + n_redundant=2, + n_repeated=0, + n_classes=8, + n_clusters_per_class=1, + flip_y=0.0, + class_sep=10, + shuffle=False, + random_state=0, + ) + + univariate_filter = SelectFwe(f_classif, alpha=0.01) + X_r = univariate_filter.fit(X, y).transform(X) + gtruth = np.zeros(20) + gtruth[:5] = 1 + for mode in ["fdr", "fpr", "fwe"]: + X_r2 = ( + GenericUnivariateSelect(f_classif, mode=mode, param=0.01) + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + assert_allclose(support, gtruth) + + +############################################################################## +# Test univariate selection in regression settings + + +def assert_best_scores_kept(score_filter): + scores = score_filter.scores_ + support = score_filter.get_support() + assert_allclose(np.sort(scores[support]), np.sort(scores)[-support.sum() :]) + + +def test_select_percentile_regression(): + # Test whether the relative univariate feature selection + # gets the correct items in a simple regression problem + # with the percentile heuristic + X, y = make_regression( + n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0 + ) + + univariate_filter = SelectPercentile(f_regression, percentile=25) + X_r = univariate_filter.fit(X, y).transform(X) + assert_best_scores_kept(univariate_filter) + X_r2 = ( + GenericUnivariateSelect(f_regression, mode="percentile", param=25) + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + gtruth = np.zeros(20) + gtruth[:5] = 1 + assert_array_equal(support, gtruth) + X_2 = X.copy() + X_2[:, np.logical_not(support)] = 0 + assert_array_equal(X_2, univariate_filter.inverse_transform(X_r)) + # Check inverse_transform respects dtype + assert_array_equal( + X_2.astype(bool), univariate_filter.inverse_transform(X_r.astype(bool)) + ) + + +def test_select_percentile_regression_full(): + # Test whether the relative univariate feature selection + # selects all features when '100%' is asked. + X, y = make_regression( + n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0 + ) + + univariate_filter = SelectPercentile(f_regression, percentile=100) + X_r = univariate_filter.fit(X, y).transform(X) + assert_best_scores_kept(univariate_filter) + X_r2 = ( + GenericUnivariateSelect(f_regression, mode="percentile", param=100) + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + gtruth = np.ones(20) + assert_array_equal(support, gtruth) + + +def test_select_kbest_regression(): + # Test whether the relative univariate feature selection + # gets the correct items in a simple regression problem + # with the k best heuristic + X, y = make_regression( + n_samples=200, + n_features=20, + n_informative=5, + shuffle=False, + random_state=0, + noise=10, + ) + + univariate_filter = SelectKBest(f_regression, k=5) + X_r = univariate_filter.fit(X, y).transform(X) + assert_best_scores_kept(univariate_filter) + X_r2 = ( + GenericUnivariateSelect(f_regression, mode="k_best", param=5) + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + gtruth = np.zeros(20) + gtruth[:5] = 1 + assert_array_equal(support, gtruth) + + +def test_select_heuristics_regression(): + # Test whether the relative univariate feature selection + # gets the correct items in a simple regression problem + # with the fpr, fdr or fwe heuristics + X, y = make_regression( + n_samples=200, + n_features=20, + n_informative=5, + shuffle=False, + random_state=0, + noise=10, + ) + + univariate_filter = SelectFpr(f_regression, alpha=0.01) + X_r = univariate_filter.fit(X, y).transform(X) + gtruth = np.zeros(20) + gtruth[:5] = 1 + for mode in ["fdr", "fpr", "fwe"]: + X_r2 = ( + GenericUnivariateSelect(f_regression, mode=mode, param=0.01) + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + assert_array_equal(support[:5], np.ones((5,), dtype=bool)) + assert np.sum(support[5:] == 1) < 3 + + +def test_boundary_case_ch2(): + # Test boundary case, and always aim to select 1 feature. + X = np.array([[10, 20], [20, 20], [20, 30]]) + y = np.array([[1], [0], [0]]) + scores, pvalues = chi2(X, y) + assert_array_almost_equal(scores, np.array([4.0, 0.71428571])) + assert_array_almost_equal(pvalues, np.array([0.04550026, 0.39802472])) + + filter_fdr = SelectFdr(chi2, alpha=0.1) + filter_fdr.fit(X, y) + support_fdr = filter_fdr.get_support() + assert_array_equal(support_fdr, np.array([True, False])) + + filter_kbest = SelectKBest(chi2, k=1) + filter_kbest.fit(X, y) + support_kbest = filter_kbest.get_support() + assert_array_equal(support_kbest, np.array([True, False])) + + filter_percentile = SelectPercentile(chi2, percentile=50) + filter_percentile.fit(X, y) + support_percentile = filter_percentile.get_support() + assert_array_equal(support_percentile, np.array([True, False])) + + filter_fpr = SelectFpr(chi2, alpha=0.1) + filter_fpr.fit(X, y) + support_fpr = filter_fpr.get_support() + assert_array_equal(support_fpr, np.array([True, False])) + + filter_fwe = SelectFwe(chi2, alpha=0.1) + filter_fwe.fit(X, y) + support_fwe = filter_fwe.get_support() + assert_array_equal(support_fwe, np.array([True, False])) + + +@pytest.mark.parametrize("alpha", [0.001, 0.01, 0.1]) +@pytest.mark.parametrize("n_informative", [1, 5, 10]) +def test_select_fdr_regression(alpha, n_informative): + # Test that fdr heuristic actually has low FDR. + def single_fdr(alpha, n_informative, random_state): + X, y = make_regression( + n_samples=150, + n_features=20, + n_informative=n_informative, + shuffle=False, + random_state=random_state, + noise=10, + ) + + with warnings.catch_warnings(record=True): + # Warnings can be raised when no features are selected + # (low alpha or very noisy data) + univariate_filter = SelectFdr(f_regression, alpha=alpha) + X_r = univariate_filter.fit(X, y).transform(X) + X_r2 = ( + GenericUnivariateSelect(f_regression, mode="fdr", param=alpha) + .fit(X, y) + .transform(X) + ) + + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + num_false_positives = np.sum(support[n_informative:] == 1) + num_true_positives = np.sum(support[:n_informative] == 1) + + if num_false_positives == 0: + return 0.0 + false_discovery_rate = num_false_positives / ( + num_true_positives + num_false_positives + ) + return false_discovery_rate + + # As per Benjamini-Hochberg, the expected false discovery rate + # should be lower than alpha: + # FDR = E(FP / (TP + FP)) <= alpha + false_discovery_rate = np.mean( + [single_fdr(alpha, n_informative, random_state) for random_state in range(100)] + ) + assert alpha >= false_discovery_rate + + # Make sure that the empirical false discovery rate increases + # with alpha: + if false_discovery_rate != 0: + assert false_discovery_rate > alpha / 10 + + +def test_select_fwe_regression(): + # Test whether the relative univariate feature selection + # gets the correct items in a simple regression problem + # with the fwe heuristic + X, y = make_regression( + n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0 + ) + + univariate_filter = SelectFwe(f_regression, alpha=0.01) + X_r = univariate_filter.fit(X, y).transform(X) + X_r2 = ( + GenericUnivariateSelect(f_regression, mode="fwe", param=0.01) + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + gtruth = np.zeros(20) + gtruth[:5] = 1 + assert_array_equal(support[:5], np.ones((5,), dtype=bool)) + assert np.sum(support[5:] == 1) < 2 + + +def test_selectkbest_tiebreaking(): + # Test whether SelectKBest actually selects k features in case of ties. + # Prior to 0.11, SelectKBest would return more features than requested. + Xs = [[0, 1, 1], [0, 0, 1], [1, 0, 0], [1, 1, 0]] + y = [1] + dummy_score = lambda X, y: (X[0], X[0]) + for X in Xs: + sel = SelectKBest(dummy_score, k=1) + X1 = ignore_warnings(sel.fit_transform)([X], y) + assert X1.shape[1] == 1 + assert_best_scores_kept(sel) + + sel = SelectKBest(dummy_score, k=2) + X2 = ignore_warnings(sel.fit_transform)([X], y) + assert X2.shape[1] == 2 + assert_best_scores_kept(sel) + + +def test_selectpercentile_tiebreaking(): + # Test if SelectPercentile selects the right n_features in case of ties. + Xs = [[0, 1, 1], [0, 0, 1], [1, 0, 0], [1, 1, 0]] + y = [1] + dummy_score = lambda X, y: (X[0], X[0]) + for X in Xs: + sel = SelectPercentile(dummy_score, percentile=34) + X1 = ignore_warnings(sel.fit_transform)([X], y) + assert X1.shape[1] == 1 + assert_best_scores_kept(sel) + + sel = SelectPercentile(dummy_score, percentile=67) + X2 = ignore_warnings(sel.fit_transform)([X], y) + assert X2.shape[1] == 2 + assert_best_scores_kept(sel) + + +def test_tied_pvalues(): + # Test whether k-best and percentiles work with tied pvalues from chi2. + # chi2 will return the same p-values for the following features, but it + # will return different scores. + X0 = np.array([[10000, 9999, 9998], [1, 1, 1]]) + y = [0, 1] + + for perm in itertools.permutations((0, 1, 2)): + X = X0[:, perm] + Xt = SelectKBest(chi2, k=2).fit_transform(X, y) + assert Xt.shape == (2, 2) + assert 9998 not in Xt + + Xt = SelectPercentile(chi2, percentile=67).fit_transform(X, y) + assert Xt.shape == (2, 2) + assert 9998 not in Xt + + +def test_scorefunc_multilabel(): + # Test whether k-best and percentiles works with multilabels with chi2. + + X = np.array([[10000, 9999, 0], [100, 9999, 0], [1000, 99, 0]]) + y = [[1, 1], [0, 1], [1, 0]] + + Xt = SelectKBest(chi2, k=2).fit_transform(X, y) + assert Xt.shape == (3, 2) + assert 0 not in Xt + + Xt = SelectPercentile(chi2, percentile=67).fit_transform(X, y) + assert Xt.shape == (3, 2) + assert 0 not in Xt + + +def test_tied_scores(): + # Test for stable sorting in k-best with tied scores. + X_train = np.array([[0, 0, 0], [1, 1, 1]]) + y_train = [0, 1] + + for n_features in [1, 2, 3]: + sel = SelectKBest(chi2, k=n_features).fit(X_train, y_train) + X_test = sel.transform([[0, 1, 2]]) + assert_array_equal(X_test[0], np.arange(3)[-n_features:]) + + +def test_nans(): + # Assert that SelectKBest and SelectPercentile can handle NaNs. + # First feature has zero variance to confuse f_classif (ANOVA) and + # make it return a NaN. + X = [[0, 1, 0], [0, -1, -1], [0, 0.5, 0.5]] + y = [1, 0, 1] + + for select in ( + SelectKBest(f_classif, k=2), + SelectPercentile(f_classif, percentile=67), + ): + ignore_warnings(select.fit)(X, y) + assert_array_equal(select.get_support(indices=True), np.array([1, 2])) + + +def test_invalid_k(): + X = [[0, 1, 0], [0, -1, -1], [0, 0.5, 0.5]] + y = [1, 0, 1] + + with pytest.raises(ValueError): + SelectKBest(k=4).fit(X, y) + with pytest.raises(ValueError): + GenericUnivariateSelect(mode="k_best", param=4).fit(X, y) + + +def test_f_classif_constant_feature(): + # Test that f_classif warns if a feature is constant throughout. + + X, y = make_classification(n_samples=10, n_features=5) + X[:, 0] = 2.0 + with pytest.warns(UserWarning): + f_classif(X, y) + + +def test_no_feature_selected(): + rng = np.random.RandomState(0) + + # Generate random uncorrelated data: a strict univariate test should + # rejects all the features + X = rng.rand(40, 10) + y = rng.randint(0, 4, size=40) + strict_selectors = [ + SelectFwe(alpha=0.01).fit(X, y), + SelectFdr(alpha=0.01).fit(X, y), + SelectFpr(alpha=0.01).fit(X, y), + SelectPercentile(percentile=0).fit(X, y), + SelectKBest(k=0).fit(X, y), + ] + for selector in strict_selectors: + assert_array_equal(selector.get_support(), np.zeros(10)) + with pytest.warns(UserWarning, match="No features were selected"): + X_selected = selector.transform(X) + assert X_selected.shape == (40, 0) + + +def test_mutual_info_classif(): + X, y = make_classification( + n_samples=100, + n_features=5, + n_informative=1, + n_redundant=1, + n_repeated=0, + n_classes=2, + n_clusters_per_class=1, + flip_y=0.0, + class_sep=10, + shuffle=False, + random_state=0, + ) + + # Test in KBest mode. + univariate_filter = SelectKBest(mutual_info_classif, k=2) + X_r = univariate_filter.fit(X, y).transform(X) + X_r2 = ( + GenericUnivariateSelect(mutual_info_classif, mode="k_best", param=2) + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + gtruth = np.zeros(5) + gtruth[:2] = 1 + assert_array_equal(support, gtruth) + + # Test in Percentile mode. + univariate_filter = SelectPercentile(mutual_info_classif, percentile=40) + X_r = univariate_filter.fit(X, y).transform(X) + X_r2 = ( + GenericUnivariateSelect(mutual_info_classif, mode="percentile", param=40) + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + gtruth = np.zeros(5) + gtruth[:2] = 1 + assert_array_equal(support, gtruth) + + +def test_mutual_info_regression(): + X, y = make_regression( + n_samples=100, + n_features=10, + n_informative=2, + shuffle=False, + random_state=0, + noise=10, + ) + + # Test in KBest mode. + univariate_filter = SelectKBest(mutual_info_regression, k=2) + X_r = univariate_filter.fit(X, y).transform(X) + assert_best_scores_kept(univariate_filter) + X_r2 = ( + GenericUnivariateSelect(mutual_info_regression, mode="k_best", param=2) + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + gtruth = np.zeros(10) + gtruth[:2] = 1 + assert_array_equal(support, gtruth) + + # Test in Percentile mode. + univariate_filter = SelectPercentile(mutual_info_regression, percentile=20) + X_r = univariate_filter.fit(X, y).transform(X) + X_r2 = ( + GenericUnivariateSelect(mutual_info_regression, mode="percentile", param=20) + .fit(X, y) + .transform(X) + ) + assert_array_equal(X_r, X_r2) + support = univariate_filter.get_support() + gtruth = np.zeros(10) + gtruth[:2] = 1 + assert_array_equal(support, gtruth) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/tree/_classes.py b/videollama2/lib/python3.10/site-packages/sklearn/tree/_classes.py new file mode 100644 index 0000000000000000000000000000000000000000..6e01b8b49e5948291b5a297e82b5a01f3dab1245 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/tree/_classes.py @@ -0,0 +1,1769 @@ +""" +This module gathers tree-based methods, including decision, regression and +randomized trees. Single and multi-output problems are both handled. +""" + +# Authors: Gilles Louppe +# Peter Prettenhofer +# Brian Holt +# Noel Dawe +# Satrajit Gosh +# Joly Arnaud +# Fares Hedayati +# Nelson Liu +# +# License: BSD 3 clause + +import numbers +import warnings +import copy +from abc import ABCMeta +from abc import abstractmethod +from math import ceil +from numbers import Integral, Real + +import numpy as np +from scipy.sparse import issparse + +from ..base import BaseEstimator +from ..base import ClassifierMixin +from ..base import clone +from ..base import RegressorMixin +from ..base import is_classifier +from ..base import MultiOutputMixin +from ..utils import Bunch +from ..utils import check_random_state +from ..utils.validation import _check_sample_weight +from ..utils import compute_sample_weight +from ..utils.multiclass import check_classification_targets +from ..utils.validation import check_is_fitted +from ..utils._param_validation import Hidden, Interval, StrOptions + +from ._criterion import Criterion +from ._splitter import Splitter +from ._tree import DepthFirstTreeBuilder +from ._tree import BestFirstTreeBuilder +from ._tree import Tree +from ._tree import _build_pruned_tree_ccp +from ._tree import ccp_pruning_path +from . import _tree, _splitter, _criterion + +__all__ = [ + "DecisionTreeClassifier", + "DecisionTreeRegressor", + "ExtraTreeClassifier", + "ExtraTreeRegressor", +] + + +# ============================================================================= +# Types and constants +# ============================================================================= + +DTYPE = _tree.DTYPE +DOUBLE = _tree.DOUBLE + +CRITERIA_CLF = { + "gini": _criterion.Gini, + "log_loss": _criterion.Entropy, + "entropy": _criterion.Entropy, +} +CRITERIA_REG = { + "squared_error": _criterion.MSE, + "friedman_mse": _criterion.FriedmanMSE, + "absolute_error": _criterion.MAE, + "poisson": _criterion.Poisson, +} + +DENSE_SPLITTERS = {"best": _splitter.BestSplitter, "random": _splitter.RandomSplitter} + +SPARSE_SPLITTERS = { + "best": _splitter.BestSparseSplitter, + "random": _splitter.RandomSparseSplitter, +} + +# ============================================================================= +# Base decision tree +# ============================================================================= + + +class BaseDecisionTree(MultiOutputMixin, BaseEstimator, metaclass=ABCMeta): + """Base class for decision trees. + + Warning: This class should not be used directly. + Use derived classes instead. + """ + + _parameter_constraints: dict = { + "splitter": [StrOptions({"best", "random"})], + "max_depth": [Interval(Integral, 1, None, closed="left"), None], + "min_samples_split": [ + Interval(Integral, 2, None, closed="left"), + Interval("real_not_int", 0.0, 1.0, closed="right"), + ], + "min_samples_leaf": [ + Interval(Integral, 1, None, closed="left"), + Interval("real_not_int", 0.0, 1.0, closed="neither"), + ], + "min_weight_fraction_leaf": [Interval(Real, 0.0, 0.5, closed="both")], + "max_features": [ + Interval(Integral, 1, None, closed="left"), + Interval("real_not_int", 0.0, 1.0, closed="right"), + StrOptions({"auto", "sqrt", "log2"}, deprecated={"auto"}), + None, + ], + "random_state": ["random_state"], + "max_leaf_nodes": [Interval(Integral, 2, None, closed="left"), None], + "min_impurity_decrease": [Interval(Real, 0.0, None, closed="left")], + "ccp_alpha": [Interval(Real, 0.0, None, closed="left")], + } + + @abstractmethod + def __init__( + self, + *, + criterion, + splitter, + max_depth, + min_samples_split, + min_samples_leaf, + min_weight_fraction_leaf, + max_features, + max_leaf_nodes, + random_state, + min_impurity_decrease, + class_weight=None, + ccp_alpha=0.0, + ): + self.criterion = criterion + self.splitter = splitter + self.max_depth = max_depth + self.min_samples_split = min_samples_split + self.min_samples_leaf = min_samples_leaf + self.min_weight_fraction_leaf = min_weight_fraction_leaf + self.max_features = max_features + self.max_leaf_nodes = max_leaf_nodes + self.random_state = random_state + self.min_impurity_decrease = min_impurity_decrease + self.class_weight = class_weight + self.ccp_alpha = ccp_alpha + + def get_depth(self): + """Return the depth of the decision tree. + + The depth of a tree is the maximum distance between the root + and any leaf. + + Returns + ------- + self.tree_.max_depth : int + The maximum depth of the tree. + """ + check_is_fitted(self) + return self.tree_.max_depth + + def get_n_leaves(self): + """Return the number of leaves of the decision tree. + + Returns + ------- + self.tree_.n_leaves : int + Number of leaves. + """ + check_is_fitted(self) + return self.tree_.n_leaves + + def fit(self, X, y, sample_weight=None, check_input=True): + self._validate_params() + random_state = check_random_state(self.random_state) + + if check_input: + # Need to validate separately here. + # We can't pass multi_output=True because that would allow y to be + # csr. + check_X_params = dict(dtype=DTYPE, accept_sparse="csc") + check_y_params = dict(ensure_2d=False, dtype=None) + X, y = self._validate_data( + X, y, validate_separately=(check_X_params, check_y_params) + ) + if issparse(X): + X.sort_indices() + + if X.indices.dtype != np.intc or X.indptr.dtype != np.intc: + raise ValueError( + "No support for np.int64 index based sparse matrices" + ) + + if self.criterion == "poisson": + if np.any(y < 0): + raise ValueError( + "Some value(s) of y are negative which is" + " not allowed for Poisson regression." + ) + if np.sum(y) <= 0: + raise ValueError( + "Sum of y is not positive which is " + "necessary for Poisson regression." + ) + + # Determine output settings + n_samples, self.n_features_in_ = X.shape + is_classification = is_classifier(self) + + y = np.atleast_1d(y) + expanded_class_weight = None + + if y.ndim == 1: + # reshape is necessary to preserve the data contiguity against vs + # [:, np.newaxis] that does not. + y = np.reshape(y, (-1, 1)) + + self.n_outputs_ = y.shape[1] + + if is_classification: + check_classification_targets(y) + y = np.copy(y) + + self.classes_ = [] + self.n_classes_ = [] + + if self.class_weight is not None: + y_original = np.copy(y) + + y_encoded = np.zeros(y.shape, dtype=int) + for k in range(self.n_outputs_): + classes_k, y_encoded[:, k] = np.unique(y[:, k], return_inverse=True) + self.classes_.append(classes_k) + self.n_classes_.append(classes_k.shape[0]) + y = y_encoded + + if self.class_weight is not None: + expanded_class_weight = compute_sample_weight( + self.class_weight, y_original + ) + + self.n_classes_ = np.array(self.n_classes_, dtype=np.intp) + + if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous: + y = np.ascontiguousarray(y, dtype=DOUBLE) + + max_depth = np.iinfo(np.int32).max if self.max_depth is None else self.max_depth + + if isinstance(self.min_samples_leaf, numbers.Integral): + min_samples_leaf = self.min_samples_leaf + else: # float + min_samples_leaf = int(ceil(self.min_samples_leaf * n_samples)) + + if isinstance(self.min_samples_split, numbers.Integral): + min_samples_split = self.min_samples_split + else: # float + min_samples_split = int(ceil(self.min_samples_split * n_samples)) + min_samples_split = max(2, min_samples_split) + + min_samples_split = max(min_samples_split, 2 * min_samples_leaf) + + if isinstance(self.max_features, str): + if self.max_features == "auto": + if is_classification: + max_features = max(1, int(np.sqrt(self.n_features_in_))) + warnings.warn( + "`max_features='auto'` has been deprecated in 1.1 " + "and will be removed in 1.3. To keep the past behaviour, " + "explicitly set `max_features='sqrt'`.", + FutureWarning, + ) + else: + max_features = self.n_features_in_ + warnings.warn( + "`max_features='auto'` has been deprecated in 1.1 " + "and will be removed in 1.3. To keep the past behaviour, " + "explicitly set `max_features=1.0'`.", + FutureWarning, + ) + elif self.max_features == "sqrt": + max_features = max(1, int(np.sqrt(self.n_features_in_))) + elif self.max_features == "log2": + max_features = max(1, int(np.log2(self.n_features_in_))) + elif self.max_features is None: + max_features = self.n_features_in_ + elif isinstance(self.max_features, numbers.Integral): + max_features = self.max_features + else: # float + if self.max_features > 0.0: + max_features = max(1, int(self.max_features * self.n_features_in_)) + else: + max_features = 0 + + self.max_features_ = max_features + + max_leaf_nodes = -1 if self.max_leaf_nodes is None else self.max_leaf_nodes + + if len(y) != n_samples: + raise ValueError( + "Number of labels=%d does not match number of samples=%d" + % (len(y), n_samples) + ) + + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X, DOUBLE) + + if expanded_class_weight is not None: + if sample_weight is not None: + sample_weight = sample_weight * expanded_class_weight + else: + sample_weight = expanded_class_weight + + # Set min_weight_leaf from min_weight_fraction_leaf + if sample_weight is None: + min_weight_leaf = self.min_weight_fraction_leaf * n_samples + else: + min_weight_leaf = self.min_weight_fraction_leaf * np.sum(sample_weight) + + # Build tree + criterion = self.criterion + if not isinstance(criterion, Criterion): + if is_classification: + criterion = CRITERIA_CLF[self.criterion]( + self.n_outputs_, self.n_classes_ + ) + else: + criterion = CRITERIA_REG[self.criterion](self.n_outputs_, n_samples) + else: + # Make a deepcopy in case the criterion has mutable attributes that + # might be shared and modified concurrently during parallel fitting + criterion = copy.deepcopy(criterion) + + SPLITTERS = SPARSE_SPLITTERS if issparse(X) else DENSE_SPLITTERS + + splitter = self.splitter + if not isinstance(self.splitter, Splitter): + splitter = SPLITTERS[self.splitter]( + criterion, + self.max_features_, + min_samples_leaf, + min_weight_leaf, + random_state, + ) + + if is_classifier(self): + self.tree_ = Tree(self.n_features_in_, self.n_classes_, self.n_outputs_) + else: + self.tree_ = Tree( + self.n_features_in_, + # TODO: tree shouldn't need this in this case + np.array([1] * self.n_outputs_, dtype=np.intp), + self.n_outputs_, + ) + + # Use BestFirst if max_leaf_nodes given; use DepthFirst otherwise + if max_leaf_nodes < 0: + builder = DepthFirstTreeBuilder( + splitter, + min_samples_split, + min_samples_leaf, + min_weight_leaf, + max_depth, + self.min_impurity_decrease, + ) + else: + builder = BestFirstTreeBuilder( + splitter, + min_samples_split, + min_samples_leaf, + min_weight_leaf, + max_depth, + max_leaf_nodes, + self.min_impurity_decrease, + ) + + builder.build(self.tree_, X, y, sample_weight) + + if self.n_outputs_ == 1 and is_classifier(self): + self.n_classes_ = self.n_classes_[0] + self.classes_ = self.classes_[0] + + self._prune_tree() + + return self + + def _validate_X_predict(self, X, check_input): + """Validate the training data on predict (probabilities).""" + if check_input: + X = self._validate_data(X, dtype=DTYPE, accept_sparse="csr", reset=False) + if issparse(X) and ( + X.indices.dtype != np.intc or X.indptr.dtype != np.intc + ): + raise ValueError("No support for np.int64 index based sparse matrices") + else: + # The number of features is checked regardless of `check_input` + self._check_n_features(X, reset=False) + return X + + def predict(self, X, check_input=True): + """Predict class or regression value for X. + + For a classification model, the predicted class for each sample in X is + returned. For a regression model, the predicted value based on X is + returned. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + check_input : bool, default=True + Allow to bypass several input checking. + Don't use this parameter unless you know what you're doing. + + Returns + ------- + y : array-like of shape (n_samples,) or (n_samples, n_outputs) + The predicted classes, or the predict values. + """ + check_is_fitted(self) + X = self._validate_X_predict(X, check_input) + proba = self.tree_.predict(X) + n_samples = X.shape[0] + + # Classification + if is_classifier(self): + if self.n_outputs_ == 1: + return self.classes_.take(np.argmax(proba, axis=1), axis=0) + + else: + class_type = self.classes_[0].dtype + predictions = np.zeros((n_samples, self.n_outputs_), dtype=class_type) + for k in range(self.n_outputs_): + predictions[:, k] = self.classes_[k].take( + np.argmax(proba[:, k], axis=1), axis=0 + ) + + return predictions + + # Regression + else: + if self.n_outputs_ == 1: + return proba[:, 0] + + else: + return proba[:, :, 0] + + def apply(self, X, check_input=True): + """Return the index of the leaf that each sample is predicted as. + + .. versionadded:: 0.17 + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + check_input : bool, default=True + Allow to bypass several input checking. + Don't use this parameter unless you know what you're doing. + + Returns + ------- + X_leaves : array-like of shape (n_samples,) + For each datapoint x in X, return the index of the leaf x + ends up in. Leaves are numbered within + ``[0; self.tree_.node_count)``, possibly with gaps in the + numbering. + """ + check_is_fitted(self) + X = self._validate_X_predict(X, check_input) + return self.tree_.apply(X) + + def decision_path(self, X, check_input=True): + """Return the decision path in the tree. + + .. versionadded:: 0.18 + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + check_input : bool, default=True + Allow to bypass several input checking. + Don't use this parameter unless you know what you're doing. + + Returns + ------- + indicator : sparse matrix of shape (n_samples, n_nodes) + Return a node indicator CSR matrix where non zero elements + indicates that the samples goes through the nodes. + """ + X = self._validate_X_predict(X, check_input) + return self.tree_.decision_path(X) + + def _prune_tree(self): + """Prune tree using Minimal Cost-Complexity Pruning.""" + check_is_fitted(self) + + if self.ccp_alpha == 0.0: + return + + # build pruned tree + if is_classifier(self): + n_classes = np.atleast_1d(self.n_classes_) + pruned_tree = Tree(self.n_features_in_, n_classes, self.n_outputs_) + else: + pruned_tree = Tree( + self.n_features_in_, + # TODO: the tree shouldn't need this param + np.array([1] * self.n_outputs_, dtype=np.intp), + self.n_outputs_, + ) + _build_pruned_tree_ccp(pruned_tree, self.tree_, self.ccp_alpha) + + self.tree_ = pruned_tree + + def cost_complexity_pruning_path(self, X, y, sample_weight=None): + """Compute the pruning path during Minimal Cost-Complexity Pruning. + + See :ref:`minimal_cost_complexity_pruning` for details on the pruning + process. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The training input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csc_matrix``. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs) + The target values (class labels) as integers or strings. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. If None, then samples are equally weighted. Splits + that would create child nodes with net zero or negative weight are + ignored while searching for a split in each node. Splits are also + ignored if they would result in any single class carrying a + negative weight in either child node. + + Returns + ------- + ccp_path : :class:`~sklearn.utils.Bunch` + Dictionary-like object, with the following attributes. + + ccp_alphas : ndarray + Effective alphas of subtree during pruning. + + impurities : ndarray + Sum of the impurities of the subtree leaves for the + corresponding alpha value in ``ccp_alphas``. + """ + est = clone(self).set_params(ccp_alpha=0.0) + est.fit(X, y, sample_weight=sample_weight) + return Bunch(**ccp_pruning_path(est.tree_)) + + @property + def feature_importances_(self): + """Return the feature importances. + + The importance of a feature is computed as the (normalized) total + reduction of the criterion brought by that feature. + It is also known as the Gini importance. + + Warning: impurity-based feature importances can be misleading for + high cardinality features (many unique values). See + :func:`sklearn.inspection.permutation_importance` as an alternative. + + Returns + ------- + feature_importances_ : ndarray of shape (n_features,) + Normalized total reduction of criteria by feature + (Gini importance). + """ + check_is_fitted(self) + + return self.tree_.compute_feature_importances() + + +# ============================================================================= +# Public estimators +# ============================================================================= + + +class DecisionTreeClassifier(ClassifierMixin, BaseDecisionTree): + """A decision tree classifier. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + criterion : {"gini", "entropy", "log_loss"}, default="gini" + The function to measure the quality of a split. Supported criteria are + "gini" for the Gini impurity and "log_loss" and "entropy" both for the + Shannon information gain, see :ref:`tree_mathematical_formulation`. + + splitter : {"best", "random"}, default="best" + The strategy used to choose the split at each node. Supported + strategies are "best" to choose the best split and "random" to choose + the best random split. + + max_depth : int, default=None + The maximum depth of the tree. If None, then nodes are expanded until + all leaves are pure or until all leaves contain less than + min_samples_split samples. + + min_samples_split : int or float, default=2 + The minimum number of samples required to split an internal node: + + - If int, then consider `min_samples_split` as the minimum number. + - If float, then `min_samples_split` is a fraction and + `ceil(min_samples_split * n_samples)` are the minimum + number of samples for each split. + + .. versionchanged:: 0.18 + Added float values for fractions. + + min_samples_leaf : int or float, default=1 + The minimum number of samples required to be at a leaf node. + A split point at any depth will only be considered if it leaves at + least ``min_samples_leaf`` training samples in each of the left and + right branches. This may have the effect of smoothing the model, + especially in regression. + + - If int, then consider `min_samples_leaf` as the minimum number. + - If float, then `min_samples_leaf` is a fraction and + `ceil(min_samples_leaf * n_samples)` are the minimum + number of samples for each node. + + .. versionchanged:: 0.18 + Added float values for fractions. + + min_weight_fraction_leaf : float, default=0.0 + The minimum weighted fraction of the sum total of weights (of all + the input samples) required to be at a leaf node. Samples have + equal weight when sample_weight is not provided. + + max_features : int, float or {"auto", "sqrt", "log2"}, default=None + The number of features to consider when looking for the best split: + + - If int, then consider `max_features` features at each split. + - If float, then `max_features` is a fraction and + `max(1, int(max_features * n_features_in_))` features are considered at + each split. + - If "auto", then `max_features=sqrt(n_features)`. + - If "sqrt", then `max_features=sqrt(n_features)`. + - If "log2", then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + .. deprecated:: 1.1 + The `"auto"` option was deprecated in 1.1 and will be removed + in 1.3. + + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + + random_state : int, RandomState instance or None, default=None + Controls the randomness of the estimator. The features are always + randomly permuted at each split, even if ``splitter`` is set to + ``"best"``. When ``max_features < n_features``, the algorithm will + select ``max_features`` at random at each split before finding the best + split among them. But the best found split may vary across different + runs, even if ``max_features=n_features``. That is the case, if the + improvement of the criterion is identical for several splits and one + split has to be selected at random. To obtain a deterministic behaviour + during fitting, ``random_state`` has to be fixed to an integer. + See :term:`Glossary ` for details. + + max_leaf_nodes : int, default=None + Grow a tree with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + If None then unlimited number of leaf nodes. + + min_impurity_decrease : float, default=0.0 + A node will be split if this split induces a decrease of the impurity + greater than or equal to this value. + + The weighted impurity decrease equation is the following:: + + N_t / N * (impurity - N_t_R / N_t * right_impurity + - N_t_L / N_t * left_impurity) + + where ``N`` is the total number of samples, ``N_t`` is the number of + samples at the current node, ``N_t_L`` is the number of samples in the + left child, and ``N_t_R`` is the number of samples in the right child. + + ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, + if ``sample_weight`` is passed. + + .. versionadded:: 0.19 + + class_weight : dict, list of dict or "balanced", default=None + Weights associated with classes in the form ``{class_label: weight}``. + If None, all classes are supposed to have weight one. For + multi-output problems, a list of dicts can be provided in the same + order as the columns of y. + + Note that for multioutput (including multilabel) weights should be + defined for each class of every column in its own dict. For example, + for four-class multilabel classification weights should be + [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of + [{1:1}, {2:5}, {3:1}, {4:1}]. + + The "balanced" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data + as ``n_samples / (n_classes * np.bincount(y))`` + + For multi-output, the weights of each column of y will be multiplied. + + Note that these weights will be multiplied with sample_weight (passed + through the fit method) if sample_weight is specified. + + ccp_alpha : non-negative float, default=0.0 + Complexity parameter used for Minimal Cost-Complexity Pruning. The + subtree with the largest cost complexity that is smaller than + ``ccp_alpha`` will be chosen. By default, no pruning is performed. See + :ref:`minimal_cost_complexity_pruning` for details. + + .. versionadded:: 0.22 + + Attributes + ---------- + classes_ : ndarray of shape (n_classes,) or list of ndarray + The classes labels (single output problem), + or a list of arrays of class labels (multi-output problem). + + feature_importances_ : ndarray of shape (n_features,) + The impurity-based feature importances. + The higher, the more important the feature. + The importance of a feature is computed as the (normalized) + total reduction of the criterion brought by that feature. It is also + known as the Gini importance [4]_. + + Warning: impurity-based feature importances can be misleading for + high cardinality features (many unique values). See + :func:`sklearn.inspection.permutation_importance` as an alternative. + + max_features_ : int + The inferred value of max_features. + + n_classes_ : int or list of int + The number of classes (for single output problems), + or a list containing the number of classes for each + output (for multi-output problems). + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_outputs_ : int + The number of outputs when ``fit`` is performed. + + tree_ : Tree instance + The underlying Tree object. Please refer to + ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and + :ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py` + for basic usage of these attributes. + + See Also + -------- + DecisionTreeRegressor : A decision tree regressor. + + Notes + ----- + The default values for the parameters controlling the size of the trees + (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and + unpruned trees which can potentially be very large on some data sets. To + reduce memory consumption, the complexity and size of the trees should be + controlled by setting those parameter values. + + The :meth:`predict` method operates using the :func:`numpy.argmax` + function on the outputs of :meth:`predict_proba`. This means that in + case the highest predicted probabilities are tied, the classifier will + predict the tied class with the lowest index in :term:`classes_`. + + References + ---------- + + .. [1] https://en.wikipedia.org/wiki/Decision_tree_learning + + .. [2] L. Breiman, J. Friedman, R. Olshen, and C. Stone, "Classification + and Regression Trees", Wadsworth, Belmont, CA, 1984. + + .. [3] T. Hastie, R. Tibshirani and J. Friedman. "Elements of Statistical + Learning", Springer, 2009. + + .. [4] L. Breiman, and A. Cutler, "Random Forests", + https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn.model_selection import cross_val_score + >>> from sklearn.tree import DecisionTreeClassifier + >>> clf = DecisionTreeClassifier(random_state=0) + >>> iris = load_iris() + >>> cross_val_score(clf, iris.data, iris.target, cv=10) + ... # doctest: +SKIP + ... + array([ 1. , 0.93..., 0.86..., 0.93..., 0.93..., + 0.93..., 0.93..., 1. , 0.93..., 1. ]) + """ + + _parameter_constraints: dict = { + **BaseDecisionTree._parameter_constraints, + "criterion": [StrOptions({"gini", "entropy", "log_loss"}), Hidden(Criterion)], + "class_weight": [dict, list, StrOptions({"balanced"}), None], + } + + def __init__( + self, + *, + criterion="gini", + splitter="best", + max_depth=None, + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0.0, + max_features=None, + random_state=None, + max_leaf_nodes=None, + min_impurity_decrease=0.0, + class_weight=None, + ccp_alpha=0.0, + ): + super().__init__( + criterion=criterion, + splitter=splitter, + max_depth=max_depth, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + min_weight_fraction_leaf=min_weight_fraction_leaf, + max_features=max_features, + max_leaf_nodes=max_leaf_nodes, + class_weight=class_weight, + random_state=random_state, + min_impurity_decrease=min_impurity_decrease, + ccp_alpha=ccp_alpha, + ) + + def fit(self, X, y, sample_weight=None, check_input=True): + """Build a decision tree classifier from the training set (X, y). + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The training input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csc_matrix``. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs) + The target values (class labels) as integers or strings. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. If None, then samples are equally weighted. Splits + that would create child nodes with net zero or negative weight are + ignored while searching for a split in each node. Splits are also + ignored if they would result in any single class carrying a + negative weight in either child node. + + check_input : bool, default=True + Allow to bypass several input checking. + Don't use this parameter unless you know what you're doing. + + Returns + ------- + self : DecisionTreeClassifier + Fitted estimator. + """ + + super().fit( + X, + y, + sample_weight=sample_weight, + check_input=check_input, + ) + return self + + def predict_proba(self, X, check_input=True): + """Predict class probabilities of the input samples X. + + The predicted class probability is the fraction of samples of the same + class in a leaf. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + check_input : bool, default=True + Allow to bypass several input checking. + Don't use this parameter unless you know what you're doing. + + Returns + ------- + proba : ndarray of shape (n_samples, n_classes) or list of n_outputs \ + such arrays if n_outputs > 1 + The class probabilities of the input samples. The order of the + classes corresponds to that in the attribute :term:`classes_`. + """ + check_is_fitted(self) + X = self._validate_X_predict(X, check_input) + proba = self.tree_.predict(X) + + if self.n_outputs_ == 1: + proba = proba[:, : self.n_classes_] + normalizer = proba.sum(axis=1)[:, np.newaxis] + normalizer[normalizer == 0.0] = 1.0 + proba /= normalizer + + return proba + + else: + all_proba = [] + + for k in range(self.n_outputs_): + proba_k = proba[:, k, : self.n_classes_[k]] + normalizer = proba_k.sum(axis=1)[:, np.newaxis] + normalizer[normalizer == 0.0] = 1.0 + proba_k /= normalizer + all_proba.append(proba_k) + + return all_proba + + def predict_log_proba(self, X): + """Predict class log-probabilities of the input samples X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csr_matrix``. + + Returns + ------- + proba : ndarray of shape (n_samples, n_classes) or list of n_outputs \ + such arrays if n_outputs > 1 + The class log-probabilities of the input samples. The order of the + classes corresponds to that in the attribute :term:`classes_`. + """ + proba = self.predict_proba(X) + + if self.n_outputs_ == 1: + return np.log(proba) + + else: + for k in range(self.n_outputs_): + proba[k] = np.log(proba[k]) + + return proba + + def _more_tags(self): + return {"multilabel": True} + + +class DecisionTreeRegressor(RegressorMixin, BaseDecisionTree): + """A decision tree regressor. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + criterion : {"squared_error", "friedman_mse", "absolute_error", \ + "poisson"}, default="squared_error" + The function to measure the quality of a split. Supported criteria + are "squared_error" for the mean squared error, which is equal to + variance reduction as feature selection criterion and minimizes the L2 + loss using the mean of each terminal node, "friedman_mse", which uses + mean squared error with Friedman's improvement score for potential + splits, "absolute_error" for the mean absolute error, which minimizes + the L1 loss using the median of each terminal node, and "poisson" which + uses reduction in Poisson deviance to find splits. + + .. versionadded:: 0.18 + Mean Absolute Error (MAE) criterion. + + .. versionadded:: 0.24 + Poisson deviance criterion. + + splitter : {"best", "random"}, default="best" + The strategy used to choose the split at each node. Supported + strategies are "best" to choose the best split and "random" to choose + the best random split. + + max_depth : int, default=None + The maximum depth of the tree. If None, then nodes are expanded until + all leaves are pure or until all leaves contain less than + min_samples_split samples. + + min_samples_split : int or float, default=2 + The minimum number of samples required to split an internal node: + + - If int, then consider `min_samples_split` as the minimum number. + - If float, then `min_samples_split` is a fraction and + `ceil(min_samples_split * n_samples)` are the minimum + number of samples for each split. + + .. versionchanged:: 0.18 + Added float values for fractions. + + min_samples_leaf : int or float, default=1 + The minimum number of samples required to be at a leaf node. + A split point at any depth will only be considered if it leaves at + least ``min_samples_leaf`` training samples in each of the left and + right branches. This may have the effect of smoothing the model, + especially in regression. + + - If int, then consider `min_samples_leaf` as the minimum number. + - If float, then `min_samples_leaf` is a fraction and + `ceil(min_samples_leaf * n_samples)` are the minimum + number of samples for each node. + + .. versionchanged:: 0.18 + Added float values for fractions. + + min_weight_fraction_leaf : float, default=0.0 + The minimum weighted fraction of the sum total of weights (of all + the input samples) required to be at a leaf node. Samples have + equal weight when sample_weight is not provided. + + max_features : int, float or {"auto", "sqrt", "log2"}, default=None + The number of features to consider when looking for the best split: + + - If int, then consider `max_features` features at each split. + - If float, then `max_features` is a fraction and + `max(1, int(max_features * n_features_in_))` features are considered at each + split. + - If "auto", then `max_features=n_features`. + - If "sqrt", then `max_features=sqrt(n_features)`. + - If "log2", then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + .. deprecated:: 1.1 + The `"auto"` option was deprecated in 1.1 and will be removed + in 1.3. + + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + + random_state : int, RandomState instance or None, default=None + Controls the randomness of the estimator. The features are always + randomly permuted at each split, even if ``splitter`` is set to + ``"best"``. When ``max_features < n_features``, the algorithm will + select ``max_features`` at random at each split before finding the best + split among them. But the best found split may vary across different + runs, even if ``max_features=n_features``. That is the case, if the + improvement of the criterion is identical for several splits and one + split has to be selected at random. To obtain a deterministic behaviour + during fitting, ``random_state`` has to be fixed to an integer. + See :term:`Glossary ` for details. + + max_leaf_nodes : int, default=None + Grow a tree with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + If None then unlimited number of leaf nodes. + + min_impurity_decrease : float, default=0.0 + A node will be split if this split induces a decrease of the impurity + greater than or equal to this value. + + The weighted impurity decrease equation is the following:: + + N_t / N * (impurity - N_t_R / N_t * right_impurity + - N_t_L / N_t * left_impurity) + + where ``N`` is the total number of samples, ``N_t`` is the number of + samples at the current node, ``N_t_L`` is the number of samples in the + left child, and ``N_t_R`` is the number of samples in the right child. + + ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, + if ``sample_weight`` is passed. + + .. versionadded:: 0.19 + + ccp_alpha : non-negative float, default=0.0 + Complexity parameter used for Minimal Cost-Complexity Pruning. The + subtree with the largest cost complexity that is smaller than + ``ccp_alpha`` will be chosen. By default, no pruning is performed. See + :ref:`minimal_cost_complexity_pruning` for details. + + .. versionadded:: 0.22 + + Attributes + ---------- + feature_importances_ : ndarray of shape (n_features,) + The feature importances. + The higher, the more important the feature. + The importance of a feature is computed as the + (normalized) total reduction of the criterion brought + by that feature. It is also known as the Gini importance [4]_. + + Warning: impurity-based feature importances can be misleading for + high cardinality features (many unique values). See + :func:`sklearn.inspection.permutation_importance` as an alternative. + + max_features_ : int + The inferred value of max_features. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_outputs_ : int + The number of outputs when ``fit`` is performed. + + tree_ : Tree instance + The underlying Tree object. Please refer to + ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and + :ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py` + for basic usage of these attributes. + + See Also + -------- + DecisionTreeClassifier : A decision tree classifier. + + Notes + ----- + The default values for the parameters controlling the size of the trees + (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and + unpruned trees which can potentially be very large on some data sets. To + reduce memory consumption, the complexity and size of the trees should be + controlled by setting those parameter values. + + References + ---------- + + .. [1] https://en.wikipedia.org/wiki/Decision_tree_learning + + .. [2] L. Breiman, J. Friedman, R. Olshen, and C. Stone, "Classification + and Regression Trees", Wadsworth, Belmont, CA, 1984. + + .. [3] T. Hastie, R. Tibshirani and J. Friedman. "Elements of Statistical + Learning", Springer, 2009. + + .. [4] L. Breiman, and A. Cutler, "Random Forests", + https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm + + Examples + -------- + >>> from sklearn.datasets import load_diabetes + >>> from sklearn.model_selection import cross_val_score + >>> from sklearn.tree import DecisionTreeRegressor + >>> X, y = load_diabetes(return_X_y=True) + >>> regressor = DecisionTreeRegressor(random_state=0) + >>> cross_val_score(regressor, X, y, cv=10) + ... # doctest: +SKIP + ... + array([-0.39..., -0.46..., 0.02..., 0.06..., -0.50..., + 0.16..., 0.11..., -0.73..., -0.30..., -0.00...]) + """ + + _parameter_constraints: dict = { + **BaseDecisionTree._parameter_constraints, + "criterion": [ + StrOptions({"squared_error", "friedman_mse", "absolute_error", "poisson"}), + Hidden(Criterion), + ], + } + + def __init__( + self, + *, + criterion="squared_error", + splitter="best", + max_depth=None, + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0.0, + max_features=None, + random_state=None, + max_leaf_nodes=None, + min_impurity_decrease=0.0, + ccp_alpha=0.0, + ): + super().__init__( + criterion=criterion, + splitter=splitter, + max_depth=max_depth, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + min_weight_fraction_leaf=min_weight_fraction_leaf, + max_features=max_features, + max_leaf_nodes=max_leaf_nodes, + random_state=random_state, + min_impurity_decrease=min_impurity_decrease, + ccp_alpha=ccp_alpha, + ) + + def fit(self, X, y, sample_weight=None, check_input=True): + """Build a decision tree regressor from the training set (X, y). + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The training input samples. Internally, it will be converted to + ``dtype=np.float32`` and if a sparse matrix is provided + to a sparse ``csc_matrix``. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs) + The target values (real numbers). Use ``dtype=np.float64`` and + ``order='C'`` for maximum efficiency. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. If None, then samples are equally weighted. Splits + that would create child nodes with net zero or negative weight are + ignored while searching for a split in each node. + + check_input : bool, default=True + Allow to bypass several input checking. + Don't use this parameter unless you know what you're doing. + + Returns + ------- + self : DecisionTreeRegressor + Fitted estimator. + """ + + super().fit( + X, + y, + sample_weight=sample_weight, + check_input=check_input, + ) + return self + + def _compute_partial_dependence_recursion(self, grid, target_features): + """Fast partial dependence computation. + + Parameters + ---------- + grid : ndarray of shape (n_samples, n_target_features) + The grid points on which the partial dependence should be + evaluated. + target_features : ndarray of shape (n_target_features) + The set of target features for which the partial dependence + should be evaluated. + + Returns + ------- + averaged_predictions : ndarray of shape (n_samples,) + The value of the partial dependence function on each grid point. + """ + grid = np.asarray(grid, dtype=DTYPE, order="C") + averaged_predictions = np.zeros( + shape=grid.shape[0], dtype=np.float64, order="C" + ) + + self.tree_.compute_partial_dependence( + grid, target_features, averaged_predictions + ) + return averaged_predictions + + +class ExtraTreeClassifier(DecisionTreeClassifier): + """An extremely randomized tree classifier. + + Extra-trees differ from classic decision trees in the way they are built. + When looking for the best split to separate the samples of a node into two + groups, random splits are drawn for each of the `max_features` randomly + selected features and the best split among those is chosen. When + `max_features` is set 1, this amounts to building a totally random + decision tree. + + Warning: Extra-trees should only be used within ensemble methods. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + criterion : {"gini", "entropy", "log_loss"}, default="gini" + The function to measure the quality of a split. Supported criteria are + "gini" for the Gini impurity and "log_loss" and "entropy" both for the + Shannon information gain, see :ref:`tree_mathematical_formulation`. + + splitter : {"random", "best"}, default="random" + The strategy used to choose the split at each node. Supported + strategies are "best" to choose the best split and "random" to choose + the best random split. + + max_depth : int, default=None + The maximum depth of the tree. If None, then nodes are expanded until + all leaves are pure or until all leaves contain less than + min_samples_split samples. + + min_samples_split : int or float, default=2 + The minimum number of samples required to split an internal node: + + - If int, then consider `min_samples_split` as the minimum number. + - If float, then `min_samples_split` is a fraction and + `ceil(min_samples_split * n_samples)` are the minimum + number of samples for each split. + + .. versionchanged:: 0.18 + Added float values for fractions. + + min_samples_leaf : int or float, default=1 + The minimum number of samples required to be at a leaf node. + A split point at any depth will only be considered if it leaves at + least ``min_samples_leaf`` training samples in each of the left and + right branches. This may have the effect of smoothing the model, + especially in regression. + + - If int, then consider `min_samples_leaf` as the minimum number. + - If float, then `min_samples_leaf` is a fraction and + `ceil(min_samples_leaf * n_samples)` are the minimum + number of samples for each node. + + .. versionchanged:: 0.18 + Added float values for fractions. + + min_weight_fraction_leaf : float, default=0.0 + The minimum weighted fraction of the sum total of weights (of all + the input samples) required to be at a leaf node. Samples have + equal weight when sample_weight is not provided. + + max_features : int, float, {"auto", "sqrt", "log2"} or None, default="sqrt" + The number of features to consider when looking for the best split: + + - If int, then consider `max_features` features at each split. + - If float, then `max_features` is a fraction and + `max(1, int(max_features * n_features_in_))` features are considered at + each split. + - If "auto", then `max_features=sqrt(n_features)`. + - If "sqrt", then `max_features=sqrt(n_features)`. + - If "log2", then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + .. versionchanged:: 1.1 + The default of `max_features` changed from `"auto"` to `"sqrt"`. + + .. deprecated:: 1.1 + The `"auto"` option was deprecated in 1.1 and will be removed + in 1.3. + + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + + random_state : int, RandomState instance or None, default=None + Used to pick randomly the `max_features` used at each split. + See :term:`Glossary ` for details. + + max_leaf_nodes : int, default=None + Grow a tree with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + If None then unlimited number of leaf nodes. + + min_impurity_decrease : float, default=0.0 + A node will be split if this split induces a decrease of the impurity + greater than or equal to this value. + + The weighted impurity decrease equation is the following:: + + N_t / N * (impurity - N_t_R / N_t * right_impurity + - N_t_L / N_t * left_impurity) + + where ``N`` is the total number of samples, ``N_t`` is the number of + samples at the current node, ``N_t_L`` is the number of samples in the + left child, and ``N_t_R`` is the number of samples in the right child. + + ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, + if ``sample_weight`` is passed. + + .. versionadded:: 0.19 + + class_weight : dict, list of dict or "balanced", default=None + Weights associated with classes in the form ``{class_label: weight}``. + If None, all classes are supposed to have weight one. For + multi-output problems, a list of dicts can be provided in the same + order as the columns of y. + + Note that for multioutput (including multilabel) weights should be + defined for each class of every column in its own dict. For example, + for four-class multilabel classification weights should be + [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of + [{1:1}, {2:5}, {3:1}, {4:1}]. + + The "balanced" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data + as ``n_samples / (n_classes * np.bincount(y))`` + + For multi-output, the weights of each column of y will be multiplied. + + Note that these weights will be multiplied with sample_weight (passed + through the fit method) if sample_weight is specified. + + ccp_alpha : non-negative float, default=0.0 + Complexity parameter used for Minimal Cost-Complexity Pruning. The + subtree with the largest cost complexity that is smaller than + ``ccp_alpha`` will be chosen. By default, no pruning is performed. See + :ref:`minimal_cost_complexity_pruning` for details. + + .. versionadded:: 0.22 + + Attributes + ---------- + classes_ : ndarray of shape (n_classes,) or list of ndarray + The classes labels (single output problem), + or a list of arrays of class labels (multi-output problem). + + max_features_ : int + The inferred value of max_features. + + n_classes_ : int or list of int + The number of classes (for single output problems), + or a list containing the number of classes for each + output (for multi-output problems). + + feature_importances_ : ndarray of shape (n_features,) + The impurity-based feature importances. + The higher, the more important the feature. + The importance of a feature is computed as the (normalized) + total reduction of the criterion brought by that feature. It is also + known as the Gini importance. + + Warning: impurity-based feature importances can be misleading for + high cardinality features (many unique values). See + :func:`sklearn.inspection.permutation_importance` as an alternative. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_outputs_ : int + The number of outputs when ``fit`` is performed. + + tree_ : Tree instance + The underlying Tree object. Please refer to + ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and + :ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py` + for basic usage of these attributes. + + See Also + -------- + ExtraTreeRegressor : An extremely randomized tree regressor. + sklearn.ensemble.ExtraTreesClassifier : An extra-trees classifier. + sklearn.ensemble.ExtraTreesRegressor : An extra-trees regressor. + sklearn.ensemble.RandomForestClassifier : A random forest classifier. + sklearn.ensemble.RandomForestRegressor : A random forest regressor. + sklearn.ensemble.RandomTreesEmbedding : An ensemble of + totally random trees. + + Notes + ----- + The default values for the parameters controlling the size of the trees + (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and + unpruned trees which can potentially be very large on some data sets. To + reduce memory consumption, the complexity and size of the trees should be + controlled by setting those parameter values. + + References + ---------- + + .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", + Machine Learning, 63(1), 3-42, 2006. + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.ensemble import BaggingClassifier + >>> from sklearn.tree import ExtraTreeClassifier + >>> X, y = load_iris(return_X_y=True) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> extra_tree = ExtraTreeClassifier(random_state=0) + >>> cls = BaggingClassifier(extra_tree, random_state=0).fit( + ... X_train, y_train) + >>> cls.score(X_test, y_test) + 0.8947... + """ + + def __init__( + self, + *, + criterion="gini", + splitter="random", + max_depth=None, + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0.0, + max_features="sqrt", + random_state=None, + max_leaf_nodes=None, + min_impurity_decrease=0.0, + class_weight=None, + ccp_alpha=0.0, + ): + super().__init__( + criterion=criterion, + splitter=splitter, + max_depth=max_depth, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + min_weight_fraction_leaf=min_weight_fraction_leaf, + max_features=max_features, + max_leaf_nodes=max_leaf_nodes, + class_weight=class_weight, + min_impurity_decrease=min_impurity_decrease, + random_state=random_state, + ccp_alpha=ccp_alpha, + ) + + +class ExtraTreeRegressor(DecisionTreeRegressor): + """An extremely randomized tree regressor. + + Extra-trees differ from classic decision trees in the way they are built. + When looking for the best split to separate the samples of a node into two + groups, random splits are drawn for each of the `max_features` randomly + selected features and the best split among those is chosen. When + `max_features` is set 1, this amounts to building a totally random + decision tree. + + Warning: Extra-trees should only be used within ensemble methods. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + criterion : {"squared_error", "friedman_mse", "absolute_error", "poisson"}, \ + default="squared_error" + The function to measure the quality of a split. Supported criteria + are "squared_error" for the mean squared error, which is equal to + variance reduction as feature selection criterion and minimizes the L2 + loss using the mean of each terminal node, "friedman_mse", which uses + mean squared error with Friedman's improvement score for potential + splits, "absolute_error" for the mean absolute error, which minimizes + the L1 loss using the median of each terminal node, and "poisson" which + uses reduction in Poisson deviance to find splits. + + .. versionadded:: 0.18 + Mean Absolute Error (MAE) criterion. + + .. versionadded:: 0.24 + Poisson deviance criterion. + + splitter : {"random", "best"}, default="random" + The strategy used to choose the split at each node. Supported + strategies are "best" to choose the best split and "random" to choose + the best random split. + + max_depth : int, default=None + The maximum depth of the tree. If None, then nodes are expanded until + all leaves are pure or until all leaves contain less than + min_samples_split samples. + + min_samples_split : int or float, default=2 + The minimum number of samples required to split an internal node: + + - If int, then consider `min_samples_split` as the minimum number. + - If float, then `min_samples_split` is a fraction and + `ceil(min_samples_split * n_samples)` are the minimum + number of samples for each split. + + .. versionchanged:: 0.18 + Added float values for fractions. + + min_samples_leaf : int or float, default=1 + The minimum number of samples required to be at a leaf node. + A split point at any depth will only be considered if it leaves at + least ``min_samples_leaf`` training samples in each of the left and + right branches. This may have the effect of smoothing the model, + especially in regression. + + - If int, then consider `min_samples_leaf` as the minimum number. + - If float, then `min_samples_leaf` is a fraction and + `ceil(min_samples_leaf * n_samples)` are the minimum + number of samples for each node. + + .. versionchanged:: 0.18 + Added float values for fractions. + + min_weight_fraction_leaf : float, default=0.0 + The minimum weighted fraction of the sum total of weights (of all + the input samples) required to be at a leaf node. Samples have + equal weight when sample_weight is not provided. + + max_features : int, float, {"auto", "sqrt", "log2"} or None, default=1.0 + The number of features to consider when looking for the best split: + + - If int, then consider `max_features` features at each split. + - If float, then `max_features` is a fraction and + `max(1, int(max_features * n_features_in_))` features are considered at each + split. + - If "auto", then `max_features=n_features`. + - If "sqrt", then `max_features=sqrt(n_features)`. + - If "log2", then `max_features=log2(n_features)`. + - If None, then `max_features=n_features`. + + .. versionchanged:: 1.1 + The default of `max_features` changed from `"auto"` to `1.0`. + + .. deprecated:: 1.1 + The `"auto"` option was deprecated in 1.1 and will be removed + in 1.3. + + Note: the search for a split does not stop until at least one + valid partition of the node samples is found, even if it requires to + effectively inspect more than ``max_features`` features. + + random_state : int, RandomState instance or None, default=None + Used to pick randomly the `max_features` used at each split. + See :term:`Glossary ` for details. + + min_impurity_decrease : float, default=0.0 + A node will be split if this split induces a decrease of the impurity + greater than or equal to this value. + + The weighted impurity decrease equation is the following:: + + N_t / N * (impurity - N_t_R / N_t * right_impurity + - N_t_L / N_t * left_impurity) + + where ``N`` is the total number of samples, ``N_t`` is the number of + samples at the current node, ``N_t_L`` is the number of samples in the + left child, and ``N_t_R`` is the number of samples in the right child. + + ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, + if ``sample_weight`` is passed. + + .. versionadded:: 0.19 + + max_leaf_nodes : int, default=None + Grow a tree with ``max_leaf_nodes`` in best-first fashion. + Best nodes are defined as relative reduction in impurity. + If None then unlimited number of leaf nodes. + + ccp_alpha : non-negative float, default=0.0 + Complexity parameter used for Minimal Cost-Complexity Pruning. The + subtree with the largest cost complexity that is smaller than + ``ccp_alpha`` will be chosen. By default, no pruning is performed. See + :ref:`minimal_cost_complexity_pruning` for details. + + .. versionadded:: 0.22 + + Attributes + ---------- + max_features_ : int + The inferred value of max_features. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + feature_importances_ : ndarray of shape (n_features,) + Return impurity-based feature importances (the higher, the more + important the feature). + + Warning: impurity-based feature importances can be misleading for + high cardinality features (many unique values). See + :func:`sklearn.inspection.permutation_importance` as an alternative. + + n_outputs_ : int + The number of outputs when ``fit`` is performed. + + tree_ : Tree instance + The underlying Tree object. Please refer to + ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and + :ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py` + for basic usage of these attributes. + + See Also + -------- + ExtraTreeClassifier : An extremely randomized tree classifier. + sklearn.ensemble.ExtraTreesClassifier : An extra-trees classifier. + sklearn.ensemble.ExtraTreesRegressor : An extra-trees regressor. + + Notes + ----- + The default values for the parameters controlling the size of the trees + (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and + unpruned trees which can potentially be very large on some data sets. To + reduce memory consumption, the complexity and size of the trees should be + controlled by setting those parameter values. + + References + ---------- + + .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", + Machine Learning, 63(1), 3-42, 2006. + + Examples + -------- + >>> from sklearn.datasets import load_diabetes + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.ensemble import BaggingRegressor + >>> from sklearn.tree import ExtraTreeRegressor + >>> X, y = load_diabetes(return_X_y=True) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> extra_tree = ExtraTreeRegressor(random_state=0) + >>> reg = BaggingRegressor(extra_tree, random_state=0).fit( + ... X_train, y_train) + >>> reg.score(X_test, y_test) + 0.33... + """ + + def __init__( + self, + *, + criterion="squared_error", + splitter="random", + max_depth=None, + min_samples_split=2, + min_samples_leaf=1, + min_weight_fraction_leaf=0.0, + max_features=1.0, + random_state=None, + min_impurity_decrease=0.0, + max_leaf_nodes=None, + ccp_alpha=0.0, + ): + super().__init__( + criterion=criterion, + splitter=splitter, + max_depth=max_depth, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + min_weight_fraction_leaf=min_weight_fraction_leaf, + max_features=max_features, + max_leaf_nodes=max_leaf_nodes, + min_impurity_decrease=min_impurity_decrease, + random_state=random_state, + ccp_alpha=ccp_alpha, + ) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/tree/_splitter.pxd b/videollama2/lib/python3.10/site-packages/sklearn/tree/_splitter.pxd new file mode 100644 index 0000000000000000000000000000000000000000..f97761879922ad7450b0a80aeb91e3d8068ce750 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/tree/_splitter.pxd @@ -0,0 +1,100 @@ +# Authors: Gilles Louppe +# Peter Prettenhofer +# Brian Holt +# Joel Nothman +# Arnaud Joly +# Jacob Schreiber +# +# License: BSD 3 clause + +# See _splitter.pyx for details. + +from ._criterion cimport Criterion + +from ._tree cimport DTYPE_t # Type of X +from ._tree cimport DOUBLE_t # Type of y, sample_weight +from ._tree cimport SIZE_t # Type for indices and counters +from ._tree cimport INT32_t # Signed 32 bit integer +from ._tree cimport UINT32_t # Unsigned 32 bit integer + +cdef struct SplitRecord: + # Data to track sample split + SIZE_t feature # Which feature to split on. + SIZE_t pos # Split samples array at the given position, + # i.e. count of samples below threshold for feature. + # pos is >= end if the node is a leaf. + double threshold # Threshold to split at. + double improvement # Impurity improvement given parent node. + double impurity_left # Impurity of the left split. + double impurity_right # Impurity of the right split. + +cdef class Splitter: + # The splitter searches in the input space for a feature and a threshold + # to split the samples samples[start:end]. + # + # The impurity computations are delegated to a criterion object. + + # Internal structures + cdef public Criterion criterion # Impurity criterion + cdef public SIZE_t max_features # Number of features to test + cdef public SIZE_t min_samples_leaf # Min samples in a leaf + cdef public double min_weight_leaf # Minimum weight in a leaf + + cdef object random_state # Random state + cdef UINT32_t rand_r_state # sklearn_rand_r random number state + + cdef SIZE_t[::1] samples # Sample indices in X, y + cdef SIZE_t n_samples # X.shape[0] + cdef double weighted_n_samples # Weighted number of samples + cdef SIZE_t[::1] features # Feature indices in X + cdef SIZE_t[::1] constant_features # Constant features indices + cdef SIZE_t n_features # X.shape[1] + cdef DTYPE_t[::1] feature_values # temp. array holding feature values + + cdef SIZE_t start # Start position for the current node + cdef SIZE_t end # End position for the current node + + cdef const DOUBLE_t[:, ::1] y + cdef const DOUBLE_t[:] sample_weight + + # The samples vector `samples` is maintained by the Splitter object such + # that the samples contained in a node are contiguous. With this setting, + # `node_split` reorganizes the node samples `samples[start:end]` in two + # subsets `samples[start:pos]` and `samples[pos:end]`. + + # The 1-d `features` array of size n_features contains the features + # indices and allows fast sampling without replacement of features. + + # The 1-d `constant_features` array of size n_features holds in + # `constant_features[:n_constant_features]` the feature ids with + # constant values for all the samples that reached a specific node. + # The value `n_constant_features` is given by the parent node to its + # child nodes. The content of the range `[n_constant_features:]` is left + # undefined, but preallocated for performance reasons + # This allows optimization with depth-based tree building. + + # Methods + cdef int init( + self, + object X, + const DOUBLE_t[:, ::1] y, + const DOUBLE_t[:] sample_weight + ) except -1 + + cdef int node_reset( + self, + SIZE_t start, + SIZE_t end, + double* weighted_n_node_samples + ) nogil except -1 + + cdef int node_split( + self, + double impurity, # Impurity of the node + SplitRecord* split, + SIZE_t* n_constant_features + ) nogil except -1 + + cdef void node_value(self, double* dest) nogil + + cdef double node_impurity(self) nogil diff --git a/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__init__.py b/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f3b6b854e10b4661bc8c2ac74afa7bc6f54cc5a Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_export.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_export.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03a4ee5714bd94f38ee1f99e518712c81e546c2a Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_export.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_reingold_tilford.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_reingold_tilford.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1013c59c2df4007f5f4d769021c1c8a0dfb680c5 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_reingold_tilford.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_tree.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_tree.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db37136aa1f90b90d3a3578ad0704ffb9820964d Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_tree.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/test_export.py b/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/test_export.py new file mode 100644 index 0000000000000000000000000000000000000000..657860a435c05f225b47c0ef36dc0c48f21ac00a --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/test_export.py @@ -0,0 +1,512 @@ +""" +Testing for export functions of decision trees (sklearn.tree.export). +""" +from re import finditer, search +from textwrap import dedent + +from numpy.random import RandomState +import pytest + +from sklearn.base import is_classifier +from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor +from sklearn.ensemble import GradientBoostingClassifier +from sklearn.tree import export_graphviz, plot_tree, export_text +from io import StringIO +from sklearn.exceptions import NotFittedError + +# toy sample +X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] +y = [-1, -1, -1, 1, 1, 1] +y2 = [[-1, 1], [-1, 1], [-1, 1], [1, 2], [1, 2], [1, 3]] +w = [1, 1, 1, 0.5, 0.5, 0.5] +y_degraded = [1, 1, 1, 1, 1, 1] + + +def test_graphviz_toy(): + # Check correctness of export_graphviz + clf = DecisionTreeClassifier( + max_depth=3, min_samples_split=2, criterion="gini", random_state=2 + ) + clf.fit(X, y) + + # Test export code + contents1 = export_graphviz(clf, out_file=None) + contents2 = ( + "digraph Tree {\n" + 'node [shape=box, fontname="helvetica"] ;\n' + 'edge [fontname="helvetica"] ;\n' + '0 [label="x[0] <= 0.0\\ngini = 0.5\\nsamples = 6\\n' + 'value = [3, 3]"] ;\n' + '1 [label="gini = 0.0\\nsamples = 3\\nvalue = [3, 0]"] ;\n' + "0 -> 1 [labeldistance=2.5, labelangle=45, " + 'headlabel="True"] ;\n' + '2 [label="gini = 0.0\\nsamples = 3\\nvalue = [0, 3]"] ;\n' + "0 -> 2 [labeldistance=2.5, labelangle=-45, " + 'headlabel="False"] ;\n' + "}" + ) + + assert contents1 == contents2 + + # Test with feature_names + contents1 = export_graphviz( + clf, feature_names=["feature0", "feature1"], out_file=None + ) + contents2 = ( + "digraph Tree {\n" + 'node [shape=box, fontname="helvetica"] ;\n' + 'edge [fontname="helvetica"] ;\n' + '0 [label="feature0 <= 0.0\\ngini = 0.5\\nsamples = 6\\n' + 'value = [3, 3]"] ;\n' + '1 [label="gini = 0.0\\nsamples = 3\\nvalue = [3, 0]"] ;\n' + "0 -> 1 [labeldistance=2.5, labelangle=45, " + 'headlabel="True"] ;\n' + '2 [label="gini = 0.0\\nsamples = 3\\nvalue = [0, 3]"] ;\n' + "0 -> 2 [labeldistance=2.5, labelangle=-45, " + 'headlabel="False"] ;\n' + "}" + ) + + assert contents1 == contents2 + + # Test with class_names + contents1 = export_graphviz(clf, class_names=["yes", "no"], out_file=None) + contents2 = ( + "digraph Tree {\n" + 'node [shape=box, fontname="helvetica"] ;\n' + 'edge [fontname="helvetica"] ;\n' + '0 [label="x[0] <= 0.0\\ngini = 0.5\\nsamples = 6\\n' + 'value = [3, 3]\\nclass = yes"] ;\n' + '1 [label="gini = 0.0\\nsamples = 3\\nvalue = [3, 0]\\n' + 'class = yes"] ;\n' + "0 -> 1 [labeldistance=2.5, labelangle=45, " + 'headlabel="True"] ;\n' + '2 [label="gini = 0.0\\nsamples = 3\\nvalue = [0, 3]\\n' + 'class = no"] ;\n' + "0 -> 2 [labeldistance=2.5, labelangle=-45, " + 'headlabel="False"] ;\n' + "}" + ) + + assert contents1 == contents2 + + # Test plot_options + contents1 = export_graphviz( + clf, + filled=True, + impurity=False, + proportion=True, + special_characters=True, + rounded=True, + out_file=None, + fontname="sans", + ) + contents2 = ( + "digraph Tree {\n" + 'node [shape=box, style="filled, rounded", color="black", ' + 'fontname="sans"] ;\n' + 'edge [fontname="sans"] ;\n' + "0 [label=0 ≤ 0.0
samples = 100.0%
" + 'value = [0.5, 0.5]>, fillcolor="#ffffff"] ;\n' + "1 [label=value = [1.0, 0.0]>, " + 'fillcolor="#e58139"] ;\n' + "0 -> 1 [labeldistance=2.5, labelangle=45, " + 'headlabel="True"] ;\n' + "2 [label=value = [0.0, 1.0]>, " + 'fillcolor="#399de5"] ;\n' + "0 -> 2 [labeldistance=2.5, labelangle=-45, " + 'headlabel="False"] ;\n' + "}" + ) + + assert contents1 == contents2 + + # Test max_depth + contents1 = export_graphviz(clf, max_depth=0, class_names=True, out_file=None) + contents2 = ( + "digraph Tree {\n" + 'node [shape=box, fontname="helvetica"] ;\n' + 'edge [fontname="helvetica"] ;\n' + '0 [label="x[0] <= 0.0\\ngini = 0.5\\nsamples = 6\\n' + 'value = [3, 3]\\nclass = y[0]"] ;\n' + '1 [label="(...)"] ;\n' + "0 -> 1 ;\n" + '2 [label="(...)"] ;\n' + "0 -> 2 ;\n" + "}" + ) + + assert contents1 == contents2 + + # Test max_depth with plot_options + contents1 = export_graphviz( + clf, max_depth=0, filled=True, out_file=None, node_ids=True + ) + contents2 = ( + "digraph Tree {\n" + 'node [shape=box, style="filled", color="black", ' + 'fontname="helvetica"] ;\n' + 'edge [fontname="helvetica"] ;\n' + '0 [label="node #0\\nx[0] <= 0.0\\ngini = 0.5\\n' + 'samples = 6\\nvalue = [3, 3]", fillcolor="#ffffff"] ;\n' + '1 [label="(...)", fillcolor="#C0C0C0"] ;\n' + "0 -> 1 ;\n" + '2 [label="(...)", fillcolor="#C0C0C0"] ;\n' + "0 -> 2 ;\n" + "}" + ) + + assert contents1 == contents2 + + # Test multi-output with weighted samples + clf = DecisionTreeClassifier( + max_depth=2, min_samples_split=2, criterion="gini", random_state=2 + ) + clf = clf.fit(X, y2, sample_weight=w) + + contents1 = export_graphviz(clf, filled=True, impurity=False, out_file=None) + contents2 = ( + "digraph Tree {\n" + 'node [shape=box, style="filled", color="black", ' + 'fontname="helvetica"] ;\n' + 'edge [fontname="helvetica"] ;\n' + '0 [label="x[0] <= 0.0\\nsamples = 6\\n' + "value = [[3.0, 1.5, 0.0]\\n" + '[3.0, 1.0, 0.5]]", fillcolor="#ffffff"] ;\n' + '1 [label="samples = 3\\nvalue = [[3, 0, 0]\\n' + '[3, 0, 0]]", fillcolor="#e58139"] ;\n' + "0 -> 1 [labeldistance=2.5, labelangle=45, " + 'headlabel="True"] ;\n' + '2 [label="x[0] <= 1.5\\nsamples = 3\\n' + "value = [[0.0, 1.5, 0.0]\\n" + '[0.0, 1.0, 0.5]]", fillcolor="#f1bd97"] ;\n' + "0 -> 2 [labeldistance=2.5, labelangle=-45, " + 'headlabel="False"] ;\n' + '3 [label="samples = 2\\nvalue = [[0, 1, 0]\\n' + '[0, 1, 0]]", fillcolor="#e58139"] ;\n' + "2 -> 3 ;\n" + '4 [label="samples = 1\\nvalue = [[0.0, 0.5, 0.0]\\n' + '[0.0, 0.0, 0.5]]", fillcolor="#e58139"] ;\n' + "2 -> 4 ;\n" + "}" + ) + + assert contents1 == contents2 + + # Test regression output with plot_options + clf = DecisionTreeRegressor( + max_depth=3, min_samples_split=2, criterion="squared_error", random_state=2 + ) + clf.fit(X, y) + + contents1 = export_graphviz( + clf, + filled=True, + leaves_parallel=True, + out_file=None, + rotate=True, + rounded=True, + fontname="sans", + ) + contents2 = ( + "digraph Tree {\n" + 'node [shape=box, style="filled, rounded", color="black", ' + 'fontname="sans"] ;\n' + "graph [ranksep=equally, splines=polyline] ;\n" + 'edge [fontname="sans"] ;\n' + "rankdir=LR ;\n" + '0 [label="x[0] <= 0.0\\nsquared_error = 1.0\\nsamples = 6\\n' + 'value = 0.0", fillcolor="#f2c09c"] ;\n' + '1 [label="squared_error = 0.0\\nsamples = 3\\' + 'nvalue = -1.0", ' + 'fillcolor="#ffffff"] ;\n' + "0 -> 1 [labeldistance=2.5, labelangle=-45, " + 'headlabel="True"] ;\n' + '2 [label="squared_error = 0.0\\nsamples = 3\\nvalue = 1.0", ' + 'fillcolor="#e58139"] ;\n' + "0 -> 2 [labeldistance=2.5, labelangle=45, " + 'headlabel="False"] ;\n' + "{rank=same ; 0} ;\n" + "{rank=same ; 1; 2} ;\n" + "}" + ) + + assert contents1 == contents2 + + # Test classifier with degraded learning set + clf = DecisionTreeClassifier(max_depth=3) + clf.fit(X, y_degraded) + + contents1 = export_graphviz(clf, filled=True, out_file=None) + contents2 = ( + "digraph Tree {\n" + 'node [shape=box, style="filled", color="black", ' + 'fontname="helvetica"] ;\n' + 'edge [fontname="helvetica"] ;\n' + '0 [label="gini = 0.0\\nsamples = 6\\nvalue = 6.0", ' + 'fillcolor="#ffffff"] ;\n' + "}" + ) + + +def test_graphviz_errors(): + # Check for errors of export_graphviz + clf = DecisionTreeClassifier(max_depth=3, min_samples_split=2) + + # Check not-fitted decision tree error + out = StringIO() + with pytest.raises(NotFittedError): + export_graphviz(clf, out) + + clf.fit(X, y) + + # Check if it errors when length of feature_names + # mismatches with number of features + message = "Length of feature_names, 1 does not match number of features, 2" + with pytest.raises(ValueError, match=message): + export_graphviz(clf, None, feature_names=["a"]) + + message = "Length of feature_names, 3 does not match number of features, 2" + with pytest.raises(ValueError, match=message): + export_graphviz(clf, None, feature_names=["a", "b", "c"]) + + # Check error when argument is not an estimator + message = "is not an estimator instance" + with pytest.raises(TypeError, match=message): + export_graphviz(clf.fit(X, y).tree_) + + # Check class_names error + out = StringIO() + with pytest.raises(IndexError): + export_graphviz(clf, out, class_names=[]) + + # Check precision error + out = StringIO() + with pytest.raises(ValueError, match="should be greater or equal"): + export_graphviz(clf, out, precision=-1) + with pytest.raises(ValueError, match="should be an integer"): + export_graphviz(clf, out, precision="1") + + +def test_friedman_mse_in_graphviz(): + clf = DecisionTreeRegressor(criterion="friedman_mse", random_state=0) + clf.fit(X, y) + dot_data = StringIO() + export_graphviz(clf, out_file=dot_data) + + clf = GradientBoostingClassifier(n_estimators=2, random_state=0) + clf.fit(X, y) + for estimator in clf.estimators_: + export_graphviz(estimator[0], out_file=dot_data) + + for finding in finditer(r"\[.*?samples.*?\]", dot_data.getvalue()): + assert "friedman_mse" in finding.group() + + +def test_precision(): + + rng_reg = RandomState(2) + rng_clf = RandomState(8) + for X, y, clf in zip( + (rng_reg.random_sample((5, 2)), rng_clf.random_sample((1000, 4))), + (rng_reg.random_sample((5,)), rng_clf.randint(2, size=(1000,))), + ( + DecisionTreeRegressor( + criterion="friedman_mse", random_state=0, max_depth=1 + ), + DecisionTreeClassifier(max_depth=1, random_state=0), + ), + ): + + clf.fit(X, y) + for precision in (4, 3): + dot_data = export_graphviz( + clf, out_file=None, precision=precision, proportion=True + ) + + # With the current random state, the impurity and the threshold + # will have the number of precision set in the export_graphviz + # function. We will check the number of precision with a strict + # equality. The value reported will have only 2 precision and + # therefore, only a less equal comparison will be done. + + # check value + for finding in finditer(r"value = \d+\.\d+", dot_data): + assert len(search(r"\.\d+", finding.group()).group()) <= precision + 1 + # check impurity + if is_classifier(clf): + pattern = r"gini = \d+\.\d+" + else: + pattern = r"friedman_mse = \d+\.\d+" + + # check impurity + for finding in finditer(pattern, dot_data): + assert len(search(r"\.\d+", finding.group()).group()) == precision + 1 + # check threshold + for finding in finditer(r"<= \d+\.\d+", dot_data): + assert len(search(r"\.\d+", finding.group()).group()) == precision + 1 + + +def test_export_text_errors(): + clf = DecisionTreeClassifier(max_depth=2, random_state=0) + clf.fit(X, y) + + err_msg = "max_depth bust be >= 0, given -1" + with pytest.raises(ValueError, match=err_msg): + export_text(clf, max_depth=-1) + err_msg = "feature_names must contain 2 elements, got 1" + with pytest.raises(ValueError, match=err_msg): + export_text(clf, feature_names=["a"]) + err_msg = "decimals must be >= 0, given -1" + with pytest.raises(ValueError, match=err_msg): + export_text(clf, decimals=-1) + err_msg = "spacing must be > 0, given 0" + with pytest.raises(ValueError, match=err_msg): + export_text(clf, spacing=0) + + +def test_export_text(): + clf = DecisionTreeClassifier(max_depth=2, random_state=0) + clf.fit(X, y) + + expected_report = dedent( + """ + |--- feature_1 <= 0.00 + | |--- class: -1 + |--- feature_1 > 0.00 + | |--- class: 1 + """ + ).lstrip() + + assert export_text(clf) == expected_report + # testing that leaves at level 1 are not truncated + assert export_text(clf, max_depth=0) == expected_report + # testing that the rest of the tree is truncated + assert export_text(clf, max_depth=10) == expected_report + + expected_report = dedent( + """ + |--- b <= 0.00 + | |--- class: -1 + |--- b > 0.00 + | |--- class: 1 + """ + ).lstrip() + assert export_text(clf, feature_names=["a", "b"]) == expected_report + + expected_report = dedent( + """ + |--- feature_1 <= 0.00 + | |--- weights: [3.00, 0.00] class: -1 + |--- feature_1 > 0.00 + | |--- weights: [0.00, 3.00] class: 1 + """ + ).lstrip() + assert export_text(clf, show_weights=True) == expected_report + + expected_report = dedent( + """ + |- feature_1 <= 0.00 + | |- class: -1 + |- feature_1 > 0.00 + | |- class: 1 + """ + ).lstrip() + assert export_text(clf, spacing=1) == expected_report + + X_l = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1], [-1, 1]] + y_l = [-1, -1, -1, 1, 1, 1, 2] + clf = DecisionTreeClassifier(max_depth=4, random_state=0) + clf.fit(X_l, y_l) + expected_report = dedent( + """ + |--- feature_1 <= 0.00 + | |--- class: -1 + |--- feature_1 > 0.00 + | |--- truncated branch of depth 2 + """ + ).lstrip() + assert export_text(clf, max_depth=0) == expected_report + + X_mo = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] + y_mo = [[-1, -1], [-1, -1], [-1, -1], [1, 1], [1, 1], [1, 1]] + + reg = DecisionTreeRegressor(max_depth=2, random_state=0) + reg.fit(X_mo, y_mo) + + expected_report = dedent( + """ + |--- feature_1 <= 0.0 + | |--- value: [-1.0, -1.0] + |--- feature_1 > 0.0 + | |--- value: [1.0, 1.0] + """ + ).lstrip() + assert export_text(reg, decimals=1) == expected_report + assert export_text(reg, decimals=1, show_weights=True) == expected_report + + X_single = [[-2], [-1], [-1], [1], [1], [2]] + reg = DecisionTreeRegressor(max_depth=2, random_state=0) + reg.fit(X_single, y_mo) + + expected_report = dedent( + """ + |--- first <= 0.0 + | |--- value: [-1.0, -1.0] + |--- first > 0.0 + | |--- value: [1.0, 1.0] + """ + ).lstrip() + assert export_text(reg, decimals=1, feature_names=["first"]) == expected_report + assert ( + export_text(reg, decimals=1, show_weights=True, feature_names=["first"]) + == expected_report + ) + + +def test_plot_tree_entropy(pyplot): + # mostly smoke tests + # Check correctness of export_graphviz for criterion = entropy + clf = DecisionTreeClassifier( + max_depth=3, min_samples_split=2, criterion="entropy", random_state=2 + ) + clf.fit(X, y) + + # Test export code + feature_names = ["first feat", "sepal_width"] + nodes = plot_tree(clf, feature_names=feature_names) + assert len(nodes) == 3 + assert ( + nodes[0].get_text() + == "first feat <= 0.0\nentropy = 1.0\nsamples = 6\nvalue = [3, 3]" + ) + assert nodes[1].get_text() == "entropy = 0.0\nsamples = 3\nvalue = [3, 0]" + assert nodes[2].get_text() == "entropy = 0.0\nsamples = 3\nvalue = [0, 3]" + + +def test_plot_tree_gini(pyplot): + # mostly smoke tests + # Check correctness of export_graphviz for criterion = gini + clf = DecisionTreeClassifier( + max_depth=3, min_samples_split=2, criterion="gini", random_state=2 + ) + clf.fit(X, y) + + # Test export code + feature_names = ["first feat", "sepal_width"] + nodes = plot_tree(clf, feature_names=feature_names) + assert len(nodes) == 3 + assert ( + nodes[0].get_text() + == "first feat <= 0.0\ngini = 0.5\nsamples = 6\nvalue = [3, 3]" + ) + assert nodes[1].get_text() == "gini = 0.0\nsamples = 3\nvalue = [3, 0]" + assert nodes[2].get_text() == "gini = 0.0\nsamples = 3\nvalue = [0, 3]" + + +def test_not_fitted_tree(pyplot): + + # Testing if not fitted tree throws the correct error + clf = DecisionTreeRegressor() + with pytest.raises(NotFittedError): + plot_tree(clf) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/test_tree.py b/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/test_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..94f08307b741553cf282de11fc9a672865c1bd28 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/tree/tests/test_tree.py @@ -0,0 +1,2430 @@ +""" +Testing for the tree module (sklearn.tree). +""" +import copy +import pickle +from itertools import product +import struct +import io +import copyreg + +import pytest +import numpy as np +from numpy.testing import assert_allclose +from scipy.sparse import csc_matrix +from scipy.sparse import csr_matrix +from scipy.sparse import coo_matrix + +import joblib +from joblib.numpy_pickle import NumpyPickler + +from sklearn.random_projection import _sparse_random_matrix + +from sklearn.dummy import DummyRegressor + +from sklearn.metrics import accuracy_score +from sklearn.metrics import mean_squared_error +from sklearn.metrics import mean_poisson_deviance + +from sklearn.model_selection import train_test_split + +from sklearn.utils._testing import assert_array_equal +from sklearn.utils._testing import assert_array_almost_equal +from sklearn.utils._testing import assert_almost_equal +from sklearn.utils._testing import create_memmap_backed_data +from sklearn.utils._testing import ignore_warnings +from sklearn.utils._testing import skip_if_32bit + +from sklearn.utils.estimator_checks import check_sample_weights_invariance +from sklearn.utils.validation import check_random_state +from sklearn.utils import _IS_32BIT + +from sklearn.exceptions import NotFittedError + +from sklearn.tree import DecisionTreeClassifier +from sklearn.tree import DecisionTreeRegressor +from sklearn.tree import ExtraTreeClassifier +from sklearn.tree import ExtraTreeRegressor + +from sklearn import tree +from sklearn.tree._tree import TREE_LEAF, TREE_UNDEFINED +from sklearn.tree._tree import Tree as CythonTree +from sklearn.tree._tree import _check_n_classes +from sklearn.tree._tree import _check_value_ndarray +from sklearn.tree._tree import _check_node_ndarray +from sklearn.tree._tree import NODE_DTYPE + +from sklearn.tree._classes import CRITERIA_CLF +from sklearn.tree._classes import CRITERIA_REG +from sklearn import datasets + +from sklearn.utils import compute_sample_weight + + +CLF_CRITERIONS = ("gini", "log_loss") +REG_CRITERIONS = ("squared_error", "absolute_error", "friedman_mse", "poisson") + +CLF_TREES = { + "DecisionTreeClassifier": DecisionTreeClassifier, + "ExtraTreeClassifier": ExtraTreeClassifier, +} + +REG_TREES = { + "DecisionTreeRegressor": DecisionTreeRegressor, + "ExtraTreeRegressor": ExtraTreeRegressor, +} + +ALL_TREES: dict = dict() +ALL_TREES.update(CLF_TREES) +ALL_TREES.update(REG_TREES) + +SPARSE_TREES = [ + "DecisionTreeClassifier", + "DecisionTreeRegressor", + "ExtraTreeClassifier", + "ExtraTreeRegressor", +] + + +X_small = np.array( + [ + [0, 0, 4, 0, 0, 0, 1, -14, 0, -4, 0, 0, 0, 0], + [0, 0, 5, 3, 0, -4, 0, 0, 1, -5, 0.2, 0, 4, 1], + [-1, -1, 0, 0, -4.5, 0, 0, 2.1, 1, 0, 0, -4.5, 0, 1], + [-1, -1, 0, -1.2, 0, 0, 0, 0, 0, 0, 0.2, 0, 0, 1], + [-1, -1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1], + [-1, -2, 0, 4, -3, 10, 4, 0, -3.2, 0, 4, 3, -4, 1], + [2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -3, 1], + [2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1], + [2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1], + [2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -1, 0], + [2, 8, 5, 1, 0.5, -4, 10, 0, 1, -5, 3, 0, 2, 0], + [2, 0, 1, 1, 1, -1, 1, 0, 0, -2, 3, 0, 1, 0], + [2, 0, 1, 2, 3, -1, 10, 2, 0, -1, 1, 2, 2, 0], + [1, 1, 0, 2, 2, -1, 1, 2, 0, -5, 1, 2, 3, 0], + [3, 1, 0, 3, 0, -4, 10, 0, 1, -5, 3, 0, 3, 1], + [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 0.5, 0, -3, 1], + [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 1.5, 1, -1, -1], + [2.11, 8, -6, -0.5, 0, 10, 0, 0, -3.2, 6, 0.5, 0, -1, -1], + [2, 0, 5, 1, 0.5, -2, 10, 0, 1, -5, 3, 1, 0, -1], + [2, 0, 1, 1, 1, -2, 1, 0, 0, -2, 0, 0, 0, 1], + [2, 1, 1, 1, 2, -1, 10, 2, 0, -1, 0, 2, 1, 1], + [1, 1, 0, 0, 1, -3, 1, 2, 0, -5, 1, 2, 1, 1], + [3, 1, 0, 1, 0, -4, 1, 0, 1, -2, 0, 0, 1, 0], + ] +) + +y_small = [1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0] +y_small_reg = [ + 1.0, + 2.1, + 1.2, + 0.05, + 10, + 2.4, + 3.1, + 1.01, + 0.01, + 2.98, + 3.1, + 1.1, + 0.0, + 1.2, + 2, + 11, + 0, + 0, + 4.5, + 0.201, + 1.06, + 0.9, + 0, +] + +# toy sample +X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] +y = [-1, -1, -1, 1, 1, 1] +T = [[-1, -1], [2, 2], [3, 2]] +true_result = [-1, 1, 1] + +# also load the iris dataset +# and randomly permute it +iris = datasets.load_iris() +rng = np.random.RandomState(1) +perm = rng.permutation(iris.target.size) +iris.data = iris.data[perm] +iris.target = iris.target[perm] + +# also load the diabetes dataset +# and randomly permute it +diabetes = datasets.load_diabetes() +perm = rng.permutation(diabetes.target.size) +diabetes.data = diabetes.data[perm] +diabetes.target = diabetes.target[perm] + +digits = datasets.load_digits() +perm = rng.permutation(digits.target.size) +digits.data = digits.data[perm] +digits.target = digits.target[perm] + +random_state = check_random_state(0) +X_multilabel, y_multilabel = datasets.make_multilabel_classification( + random_state=0, n_samples=30, n_features=10 +) + +# NB: despite their names X_sparse_* are numpy arrays (and not sparse matrices) +X_sparse_pos = random_state.uniform(size=(20, 5)) +X_sparse_pos[X_sparse_pos <= 0.8] = 0.0 +y_random = random_state.randint(0, 4, size=(20,)) +X_sparse_mix = _sparse_random_matrix(20, 10, density=0.25, random_state=0).toarray() + + +DATASETS = { + "iris": {"X": iris.data, "y": iris.target}, + "diabetes": {"X": diabetes.data, "y": diabetes.target}, + "digits": {"X": digits.data, "y": digits.target}, + "toy": {"X": X, "y": y}, + "clf_small": {"X": X_small, "y": y_small}, + "reg_small": {"X": X_small, "y": y_small_reg}, + "multilabel": {"X": X_multilabel, "y": y_multilabel}, + "sparse-pos": {"X": X_sparse_pos, "y": y_random}, + "sparse-neg": {"X": -X_sparse_pos, "y": y_random}, + "sparse-mix": {"X": X_sparse_mix, "y": y_random}, + "zeros": {"X": np.zeros((20, 3)), "y": y_random}, +} + +for name in DATASETS: + DATASETS[name]["X_sparse"] = csc_matrix(DATASETS[name]["X"]) + + +def assert_tree_equal(d, s, message): + assert ( + s.node_count == d.node_count + ), "{0}: inequal number of node ({1} != {2})".format( + message, s.node_count, d.node_count + ) + + assert_array_equal( + d.children_right, s.children_right, message + ": inequal children_right" + ) + assert_array_equal( + d.children_left, s.children_left, message + ": inequal children_left" + ) + + external = d.children_right == TREE_LEAF + internal = np.logical_not(external) + + assert_array_equal( + d.feature[internal], s.feature[internal], message + ": inequal features" + ) + assert_array_equal( + d.threshold[internal], s.threshold[internal], message + ": inequal threshold" + ) + assert_array_equal( + d.n_node_samples.sum(), + s.n_node_samples.sum(), + message + ": inequal sum(n_node_samples)", + ) + assert_array_equal( + d.n_node_samples, s.n_node_samples, message + ": inequal n_node_samples" + ) + + assert_almost_equal(d.impurity, s.impurity, err_msg=message + ": inequal impurity") + + assert_array_almost_equal( + d.value[external], s.value[external], err_msg=message + ": inequal value" + ) + + +def test_classification_toy(): + # Check classification on a toy dataset. + for name, Tree in CLF_TREES.items(): + clf = Tree(random_state=0) + clf.fit(X, y) + assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) + + clf = Tree(max_features=1, random_state=1) + clf.fit(X, y) + assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) + + +def test_weighted_classification_toy(): + # Check classification on a weighted toy dataset. + for name, Tree in CLF_TREES.items(): + clf = Tree(random_state=0) + + clf.fit(X, y, sample_weight=np.ones(len(X))) + assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) + + clf.fit(X, y, sample_weight=np.full(len(X), 0.5)) + assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name)) + + +@pytest.mark.parametrize("Tree", REG_TREES.values()) +@pytest.mark.parametrize("criterion", REG_CRITERIONS) +def test_regression_toy(Tree, criterion): + # Check regression on a toy dataset. + if criterion == "poisson": + # make target positive while not touching the original y and + # true_result + a = np.abs(np.min(y)) + 1 + y_train = np.array(y) + a + y_test = np.array(true_result) + a + else: + y_train = y + y_test = true_result + + reg = Tree(criterion=criterion, random_state=1) + reg.fit(X, y_train) + assert_allclose(reg.predict(T), y_test) + + clf = Tree(criterion=criterion, max_features=1, random_state=1) + clf.fit(X, y_train) + assert_allclose(reg.predict(T), y_test) + + +def test_xor(): + # Check on a XOR problem + y = np.zeros((10, 10)) + y[:5, :5] = 1 + y[5:, 5:] = 1 + + gridx, gridy = np.indices(y.shape) + + X = np.vstack([gridx.ravel(), gridy.ravel()]).T + y = y.ravel() + + for name, Tree in CLF_TREES.items(): + clf = Tree(random_state=0) + clf.fit(X, y) + assert clf.score(X, y) == 1.0, "Failed with {0}".format(name) + + clf = Tree(random_state=0, max_features=1) + clf.fit(X, y) + assert clf.score(X, y) == 1.0, "Failed with {0}".format(name) + + +def test_iris(): + # Check consistency on dataset iris. + for (name, Tree), criterion in product(CLF_TREES.items(), CLF_CRITERIONS): + clf = Tree(criterion=criterion, random_state=0) + clf.fit(iris.data, iris.target) + score = accuracy_score(clf.predict(iris.data), iris.target) + assert score > 0.9, "Failed with {0}, criterion = {1} and score = {2}".format( + name, criterion, score + ) + + clf = Tree(criterion=criterion, max_features=2, random_state=0) + clf.fit(iris.data, iris.target) + score = accuracy_score(clf.predict(iris.data), iris.target) + assert score > 0.5, "Failed with {0}, criterion = {1} and score = {2}".format( + name, criterion, score + ) + + +@pytest.mark.parametrize("name, Tree", REG_TREES.items()) +@pytest.mark.parametrize("criterion", REG_CRITERIONS) +def test_diabetes_overfit(name, Tree, criterion): + # check consistency of overfitted trees on the diabetes dataset + # since the trees will overfit, we expect an MSE of 0 + reg = Tree(criterion=criterion, random_state=0) + reg.fit(diabetes.data, diabetes.target) + score = mean_squared_error(diabetes.target, reg.predict(diabetes.data)) + assert score == pytest.approx( + 0 + ), f"Failed with {name}, criterion = {criterion} and score = {score}" + + +@skip_if_32bit +@pytest.mark.parametrize("name, Tree", REG_TREES.items()) +@pytest.mark.parametrize( + "criterion, max_depth, metric, max_loss", + [ + ("squared_error", 15, mean_squared_error, 60), + ("absolute_error", 20, mean_squared_error, 60), + ("friedman_mse", 15, mean_squared_error, 60), + ("poisson", 15, mean_poisson_deviance, 30), + ], +) +def test_diabetes_underfit(name, Tree, criterion, max_depth, metric, max_loss): + # check consistency of trees when the depth and the number of features are + # limited + + reg = Tree(criterion=criterion, max_depth=max_depth, max_features=6, random_state=0) + reg.fit(diabetes.data, diabetes.target) + loss = metric(diabetes.target, reg.predict(diabetes.data)) + assert 0 < loss < max_loss + + +def test_probability(): + # Predict probabilities using DecisionTreeClassifier. + + for name, Tree in CLF_TREES.items(): + clf = Tree(max_depth=1, max_features=1, random_state=42) + clf.fit(iris.data, iris.target) + + prob_predict = clf.predict_proba(iris.data) + assert_array_almost_equal( + np.sum(prob_predict, 1), + np.ones(iris.data.shape[0]), + err_msg="Failed with {0}".format(name), + ) + assert_array_equal( + np.argmax(prob_predict, 1), + clf.predict(iris.data), + err_msg="Failed with {0}".format(name), + ) + assert_almost_equal( + clf.predict_proba(iris.data), + np.exp(clf.predict_log_proba(iris.data)), + 8, + err_msg="Failed with {0}".format(name), + ) + + +def test_arrayrepr(): + # Check the array representation. + # Check resize + X = np.arange(10000)[:, np.newaxis] + y = np.arange(10000) + + for name, Tree in REG_TREES.items(): + reg = Tree(max_depth=None, random_state=0) + reg.fit(X, y) + + +def test_pure_set(): + # Check when y is pure. + X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] + y = [1, 1, 1, 1, 1, 1] + + for name, TreeClassifier in CLF_TREES.items(): + clf = TreeClassifier(random_state=0) + clf.fit(X, y) + assert_array_equal(clf.predict(X), y, err_msg="Failed with {0}".format(name)) + + for name, TreeRegressor in REG_TREES.items(): + reg = TreeRegressor(random_state=0) + reg.fit(X, y) + assert_almost_equal(reg.predict(X), y, err_msg="Failed with {0}".format(name)) + + +def test_numerical_stability(): + # Check numerical stability. + X = np.array( + [ + [152.08097839, 140.40744019, 129.75102234, 159.90493774], + [142.50700378, 135.81935120, 117.82884979, 162.75781250], + [127.28772736, 140.40744019, 129.75102234, 159.90493774], + [132.37025452, 143.71923828, 138.35694885, 157.84558105], + [103.10237122, 143.71928406, 138.35696411, 157.84559631], + [127.71276855, 143.71923828, 138.35694885, 157.84558105], + [120.91514587, 140.40744019, 129.75102234, 159.90493774], + ] + ) + + y = np.array([1.0, 0.70209277, 0.53896582, 0.0, 0.90914464, 0.48026916, 0.49622521]) + + with np.errstate(all="raise"): + for name, Tree in REG_TREES.items(): + reg = Tree(random_state=0) + reg.fit(X, y) + reg.fit(X, -y) + reg.fit(-X, y) + reg.fit(-X, -y) + + +def test_importances(): + # Check variable importances. + X, y = datasets.make_classification( + n_samples=5000, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=0, + ) + + for name, Tree in CLF_TREES.items(): + clf = Tree(random_state=0) + + clf.fit(X, y) + importances = clf.feature_importances_ + n_important = np.sum(importances > 0.1) + + assert importances.shape[0] == 10, "Failed with {0}".format(name) + assert n_important == 3, "Failed with {0}".format(name) + + # Check on iris that importances are the same for all builders + clf = DecisionTreeClassifier(random_state=0) + clf.fit(iris.data, iris.target) + clf2 = DecisionTreeClassifier(random_state=0, max_leaf_nodes=len(iris.data)) + clf2.fit(iris.data, iris.target) + + assert_array_equal(clf.feature_importances_, clf2.feature_importances_) + + +def test_importances_raises(): + # Check if variable importance before fit raises ValueError. + clf = DecisionTreeClassifier() + with pytest.raises(ValueError): + getattr(clf, "feature_importances_") + + +def test_importances_gini_equal_squared_error(): + # Check that gini is equivalent to squared_error for binary output variable + + X, y = datasets.make_classification( + n_samples=2000, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=0, + ) + + # The gini index and the mean square error (variance) might differ due + # to numerical instability. Since those instabilities mainly occurs at + # high tree depth, we restrict this maximal depth. + clf = DecisionTreeClassifier(criterion="gini", max_depth=5, random_state=0).fit( + X, y + ) + reg = DecisionTreeRegressor( + criterion="squared_error", max_depth=5, random_state=0 + ).fit(X, y) + + assert_almost_equal(clf.feature_importances_, reg.feature_importances_) + assert_array_equal(clf.tree_.feature, reg.tree_.feature) + assert_array_equal(clf.tree_.children_left, reg.tree_.children_left) + assert_array_equal(clf.tree_.children_right, reg.tree_.children_right) + assert_array_equal(clf.tree_.n_node_samples, reg.tree_.n_node_samples) + + +# TODO(1.3): Remove warning filter +@pytest.mark.filterwarnings("ignore:`max_features='auto'` has been deprecated in 1.1") +def test_max_features(): + # Check max_features. + for name, TreeRegressor in REG_TREES.items(): + reg = TreeRegressor(max_features="auto") + reg.fit(diabetes.data, diabetes.target) + assert reg.max_features_ == diabetes.data.shape[1] + + for name, TreeClassifier in CLF_TREES.items(): + clf = TreeClassifier(max_features="auto") + clf.fit(iris.data, iris.target) + assert clf.max_features_ == 2 + + for name, TreeEstimator in ALL_TREES.items(): + est = TreeEstimator(max_features="sqrt") + est.fit(iris.data, iris.target) + assert est.max_features_ == int(np.sqrt(iris.data.shape[1])) + + est = TreeEstimator(max_features="log2") + est.fit(iris.data, iris.target) + assert est.max_features_ == int(np.log2(iris.data.shape[1])) + + est = TreeEstimator(max_features=1) + est.fit(iris.data, iris.target) + assert est.max_features_ == 1 + + est = TreeEstimator(max_features=3) + est.fit(iris.data, iris.target) + assert est.max_features_ == 3 + + est = TreeEstimator(max_features=0.01) + est.fit(iris.data, iris.target) + assert est.max_features_ == 1 + + est = TreeEstimator(max_features=0.5) + est.fit(iris.data, iris.target) + assert est.max_features_ == int(0.5 * iris.data.shape[1]) + + est = TreeEstimator(max_features=1.0) + est.fit(iris.data, iris.target) + assert est.max_features_ == iris.data.shape[1] + + est = TreeEstimator(max_features=None) + est.fit(iris.data, iris.target) + assert est.max_features_ == iris.data.shape[1] + + +def test_error(): + # Test that it gives proper exception on deficient input. + for name, TreeEstimator in CLF_TREES.items(): + # predict before fit + est = TreeEstimator() + with pytest.raises(NotFittedError): + est.predict_proba(X) + + est.fit(X, y) + X2 = [[-2, -1, 1]] # wrong feature shape for sample + with pytest.raises(ValueError): + est.predict_proba(X2) + + # Wrong dimensions + est = TreeEstimator() + y2 = y[:-1] + with pytest.raises(ValueError): + est.fit(X, y2) + + # Test with arrays that are non-contiguous. + Xf = np.asfortranarray(X) + est = TreeEstimator() + est.fit(Xf, y) + assert_almost_equal(est.predict(T), true_result) + + # predict before fitting + est = TreeEstimator() + with pytest.raises(NotFittedError): + est.predict(T) + + # predict on vector with different dims + est.fit(X, y) + t = np.asarray(T) + with pytest.raises(ValueError): + est.predict(t[:, 1:]) + + # wrong sample shape + Xt = np.array(X).T + + est = TreeEstimator() + est.fit(np.dot(X, Xt), y) + with pytest.raises(ValueError): + est.predict(X) + with pytest.raises(ValueError): + est.apply(X) + + clf = TreeEstimator() + clf.fit(X, y) + with pytest.raises(ValueError): + clf.predict(Xt) + with pytest.raises(ValueError): + clf.apply(Xt) + + # apply before fitting + est = TreeEstimator() + with pytest.raises(NotFittedError): + est.apply(T) + + # non positive target for Poisson splitting Criterion + est = DecisionTreeRegressor(criterion="poisson") + with pytest.raises(ValueError, match="y is not positive.*Poisson"): + est.fit([[0, 1, 2]], [0, 0, 0]) + with pytest.raises(ValueError, match="Some.*y are negative.*Poisson"): + est.fit([[0, 1, 2]], [5, -0.1, 2]) + + +def test_min_samples_split(): + """Test min_samples_split parameter""" + X = np.asfortranarray(iris.data, dtype=tree._tree.DTYPE) + y = iris.target + + # test both DepthFirstTreeBuilder and BestFirstTreeBuilder + # by setting max_leaf_nodes + for max_leaf_nodes, name in product((None, 1000), ALL_TREES.keys()): + TreeEstimator = ALL_TREES[name] + + # test for integer parameter + est = TreeEstimator( + min_samples_split=10, max_leaf_nodes=max_leaf_nodes, random_state=0 + ) + est.fit(X, y) + # count samples on nodes, -1 means it is a leaf + node_samples = est.tree_.n_node_samples[est.tree_.children_left != -1] + + assert np.min(node_samples) > 9, "Failed with {0}".format(name) + + # test for float parameter + est = TreeEstimator( + min_samples_split=0.2, max_leaf_nodes=max_leaf_nodes, random_state=0 + ) + est.fit(X, y) + # count samples on nodes, -1 means it is a leaf + node_samples = est.tree_.n_node_samples[est.tree_.children_left != -1] + + assert np.min(node_samples) > 9, "Failed with {0}".format(name) + + +def test_min_samples_leaf(): + # Test if leaves contain more than leaf_count training examples + X = np.asfortranarray(iris.data, dtype=tree._tree.DTYPE) + y = iris.target + + # test both DepthFirstTreeBuilder and BestFirstTreeBuilder + # by setting max_leaf_nodes + for max_leaf_nodes, name in product((None, 1000), ALL_TREES.keys()): + TreeEstimator = ALL_TREES[name] + + # test integer parameter + est = TreeEstimator( + min_samples_leaf=5, max_leaf_nodes=max_leaf_nodes, random_state=0 + ) + est.fit(X, y) + out = est.tree_.apply(X) + node_counts = np.bincount(out) + # drop inner nodes + leaf_count = node_counts[node_counts != 0] + assert np.min(leaf_count) > 4, "Failed with {0}".format(name) + + # test float parameter + est = TreeEstimator( + min_samples_leaf=0.1, max_leaf_nodes=max_leaf_nodes, random_state=0 + ) + est.fit(X, y) + out = est.tree_.apply(X) + node_counts = np.bincount(out) + # drop inner nodes + leaf_count = node_counts[node_counts != 0] + assert np.min(leaf_count) > 4, "Failed with {0}".format(name) + + +def check_min_weight_fraction_leaf(name, datasets, sparse=False): + """Test if leaves contain at least min_weight_fraction_leaf of the + training set""" + if sparse: + X = DATASETS[datasets]["X_sparse"].astype(np.float32) + else: + X = DATASETS[datasets]["X"].astype(np.float32) + y = DATASETS[datasets]["y"] + + weights = rng.rand(X.shape[0]) + total_weight = np.sum(weights) + + TreeEstimator = ALL_TREES[name] + + # test both DepthFirstTreeBuilder and BestFirstTreeBuilder + # by setting max_leaf_nodes + for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 6)): + est = TreeEstimator( + min_weight_fraction_leaf=frac, max_leaf_nodes=max_leaf_nodes, random_state=0 + ) + est.fit(X, y, sample_weight=weights) + + if sparse: + out = est.tree_.apply(X.tocsr()) + + else: + out = est.tree_.apply(X) + + node_weights = np.bincount(out, weights=weights) + # drop inner nodes + leaf_weights = node_weights[node_weights != 0] + assert ( + np.min(leaf_weights) >= total_weight * est.min_weight_fraction_leaf + ), "Failed with {0} min_weight_fraction_leaf={1}".format( + name, est.min_weight_fraction_leaf + ) + + # test case with no weights passed in + total_weight = X.shape[0] + + for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 6)): + est = TreeEstimator( + min_weight_fraction_leaf=frac, max_leaf_nodes=max_leaf_nodes, random_state=0 + ) + est.fit(X, y) + + if sparse: + out = est.tree_.apply(X.tocsr()) + else: + out = est.tree_.apply(X) + + node_weights = np.bincount(out) + # drop inner nodes + leaf_weights = node_weights[node_weights != 0] + assert ( + np.min(leaf_weights) >= total_weight * est.min_weight_fraction_leaf + ), "Failed with {0} min_weight_fraction_leaf={1}".format( + name, est.min_weight_fraction_leaf + ) + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_min_weight_fraction_leaf_on_dense_input(name): + check_min_weight_fraction_leaf(name, "iris") + + +@pytest.mark.parametrize("name", SPARSE_TREES) +def test_min_weight_fraction_leaf_on_sparse_input(name): + check_min_weight_fraction_leaf(name, "multilabel", True) + + +def check_min_weight_fraction_leaf_with_min_samples_leaf(name, datasets, sparse=False): + """Test the interaction between min_weight_fraction_leaf and + min_samples_leaf when sample_weights is not provided in fit.""" + if sparse: + X = DATASETS[datasets]["X_sparse"].astype(np.float32) + else: + X = DATASETS[datasets]["X"].astype(np.float32) + y = DATASETS[datasets]["y"] + + total_weight = X.shape[0] + TreeEstimator = ALL_TREES[name] + for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 3)): + # test integer min_samples_leaf + est = TreeEstimator( + min_weight_fraction_leaf=frac, + max_leaf_nodes=max_leaf_nodes, + min_samples_leaf=5, + random_state=0, + ) + est.fit(X, y) + + if sparse: + out = est.tree_.apply(X.tocsr()) + else: + out = est.tree_.apply(X) + + node_weights = np.bincount(out) + # drop inner nodes + leaf_weights = node_weights[node_weights != 0] + assert np.min(leaf_weights) >= max( + (total_weight * est.min_weight_fraction_leaf), 5 + ), "Failed with {0} min_weight_fraction_leaf={1}, min_samples_leaf={2}".format( + name, est.min_weight_fraction_leaf, est.min_samples_leaf + ) + for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 3)): + # test float min_samples_leaf + est = TreeEstimator( + min_weight_fraction_leaf=frac, + max_leaf_nodes=max_leaf_nodes, + min_samples_leaf=0.1, + random_state=0, + ) + est.fit(X, y) + + if sparse: + out = est.tree_.apply(X.tocsr()) + else: + out = est.tree_.apply(X) + + node_weights = np.bincount(out) + # drop inner nodes + leaf_weights = node_weights[node_weights != 0] + assert np.min(leaf_weights) >= max( + (total_weight * est.min_weight_fraction_leaf), + (total_weight * est.min_samples_leaf), + ), "Failed with {0} min_weight_fraction_leaf={1}, min_samples_leaf={2}".format( + name, est.min_weight_fraction_leaf, est.min_samples_leaf + ) + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_min_weight_fraction_leaf_with_min_samples_leaf_on_dense_input(name): + check_min_weight_fraction_leaf_with_min_samples_leaf(name, "iris") + + +@pytest.mark.parametrize("name", SPARSE_TREES) +def test_min_weight_fraction_leaf_with_min_samples_leaf_on_sparse_input(name): + check_min_weight_fraction_leaf_with_min_samples_leaf(name, "multilabel", True) + + +def test_min_impurity_decrease(): + # test if min_impurity_decrease ensure that a split is made only if + # if the impurity decrease is at least that value + X, y = datasets.make_classification(n_samples=10000, random_state=42) + + # test both DepthFirstTreeBuilder and BestFirstTreeBuilder + # by setting max_leaf_nodes + for max_leaf_nodes, name in product((None, 1000), ALL_TREES.keys()): + TreeEstimator = ALL_TREES[name] + + # Check default value of min_impurity_decrease, 1e-7 + est1 = TreeEstimator(max_leaf_nodes=max_leaf_nodes, random_state=0) + # Check with explicit value of 0.05 + est2 = TreeEstimator( + max_leaf_nodes=max_leaf_nodes, min_impurity_decrease=0.05, random_state=0 + ) + # Check with a much lower value of 0.0001 + est3 = TreeEstimator( + max_leaf_nodes=max_leaf_nodes, min_impurity_decrease=0.0001, random_state=0 + ) + # Check with a much lower value of 0.1 + est4 = TreeEstimator( + max_leaf_nodes=max_leaf_nodes, min_impurity_decrease=0.1, random_state=0 + ) + + for est, expected_decrease in ( + (est1, 1e-7), + (est2, 0.05), + (est3, 0.0001), + (est4, 0.1), + ): + assert ( + est.min_impurity_decrease <= expected_decrease + ), "Failed, min_impurity_decrease = {0} > {1}".format( + est.min_impurity_decrease, expected_decrease + ) + est.fit(X, y) + for node in range(est.tree_.node_count): + # If current node is a not leaf node, check if the split was + # justified w.r.t the min_impurity_decrease + if est.tree_.children_left[node] != TREE_LEAF: + imp_parent = est.tree_.impurity[node] + wtd_n_node = est.tree_.weighted_n_node_samples[node] + + left = est.tree_.children_left[node] + wtd_n_left = est.tree_.weighted_n_node_samples[left] + imp_left = est.tree_.impurity[left] + wtd_imp_left = wtd_n_left * imp_left + + right = est.tree_.children_right[node] + wtd_n_right = est.tree_.weighted_n_node_samples[right] + imp_right = est.tree_.impurity[right] + wtd_imp_right = wtd_n_right * imp_right + + wtd_avg_left_right_imp = wtd_imp_right + wtd_imp_left + wtd_avg_left_right_imp /= wtd_n_node + + fractional_node_weight = ( + est.tree_.weighted_n_node_samples[node] / X.shape[0] + ) + + actual_decrease = fractional_node_weight * ( + imp_parent - wtd_avg_left_right_imp + ) + + assert ( + actual_decrease >= expected_decrease + ), "Failed with {0} expected min_impurity_decrease={1}".format( + actual_decrease, expected_decrease + ) + + +def test_pickle(): + """Test pickling preserves Tree properties and performance.""" + for name, TreeEstimator in ALL_TREES.items(): + if "Classifier" in name: + X, y = iris.data, iris.target + else: + X, y = diabetes.data, diabetes.target + + est = TreeEstimator(random_state=0) + est.fit(X, y) + score = est.score(X, y) + + # test that all class properties are maintained + attributes = [ + "max_depth", + "node_count", + "capacity", + "n_classes", + "children_left", + "children_right", + "n_leaves", + "feature", + "threshold", + "impurity", + "n_node_samples", + "weighted_n_node_samples", + "value", + ] + fitted_attribute = { + attribute: getattr(est.tree_, attribute) for attribute in attributes + } + + serialized_object = pickle.dumps(est) + est2 = pickle.loads(serialized_object) + assert type(est2) == est.__class__ + + score2 = est2.score(X, y) + assert ( + score == score2 + ), "Failed to generate same score after pickling with {0}".format(name) + for attribute in fitted_attribute: + assert_array_equal( + getattr(est2.tree_, attribute), + fitted_attribute[attribute], + err_msg=( + f"Failed to generate same attribute {attribute} after pickling with" + f" {name}" + ), + ) + + +def test_multioutput(): + # Check estimators on multi-output problems. + X = [ + [-2, -1], + [-1, -1], + [-1, -2], + [1, 1], + [1, 2], + [2, 1], + [-2, 1], + [-1, 1], + [-1, 2], + [2, -1], + [1, -1], + [1, -2], + ] + + y = [ + [-1, 0], + [-1, 0], + [-1, 0], + [1, 1], + [1, 1], + [1, 1], + [-1, 2], + [-1, 2], + [-1, 2], + [1, 3], + [1, 3], + [1, 3], + ] + + T = [[-1, -1], [1, 1], [-1, 1], [1, -1]] + y_true = [[-1, 0], [1, 1], [-1, 2], [1, 3]] + + # toy classification problem + for name, TreeClassifier in CLF_TREES.items(): + clf = TreeClassifier(random_state=0) + y_hat = clf.fit(X, y).predict(T) + assert_array_equal(y_hat, y_true) + assert y_hat.shape == (4, 2) + + proba = clf.predict_proba(T) + assert len(proba) == 2 + assert proba[0].shape == (4, 2) + assert proba[1].shape == (4, 4) + + log_proba = clf.predict_log_proba(T) + assert len(log_proba) == 2 + assert log_proba[0].shape == (4, 2) + assert log_proba[1].shape == (4, 4) + + # toy regression problem + for name, TreeRegressor in REG_TREES.items(): + reg = TreeRegressor(random_state=0) + y_hat = reg.fit(X, y).predict(T) + assert_almost_equal(y_hat, y_true) + assert y_hat.shape == (4, 2) + + +def test_classes_shape(): + # Test that n_classes_ and classes_ have proper shape. + for name, TreeClassifier in CLF_TREES.items(): + # Classification, single output + clf = TreeClassifier(random_state=0) + clf.fit(X, y) + + assert clf.n_classes_ == 2 + assert_array_equal(clf.classes_, [-1, 1]) + + # Classification, multi-output + _y = np.vstack((y, np.array(y) * 2)).T + clf = TreeClassifier(random_state=0) + clf.fit(X, _y) + assert len(clf.n_classes_) == 2 + assert len(clf.classes_) == 2 + assert_array_equal(clf.n_classes_, [2, 2]) + assert_array_equal(clf.classes_, [[-1, 1], [-2, 2]]) + + +def test_unbalanced_iris(): + # Check class rebalancing. + unbalanced_X = iris.data[:125] + unbalanced_y = iris.target[:125] + sample_weight = compute_sample_weight("balanced", unbalanced_y) + + for name, TreeClassifier in CLF_TREES.items(): + clf = TreeClassifier(random_state=0) + clf.fit(unbalanced_X, unbalanced_y, sample_weight=sample_weight) + assert_almost_equal(clf.predict(unbalanced_X), unbalanced_y) + + +def test_memory_layout(): + # Check that it works no matter the memory layout + for (name, TreeEstimator), dtype in product( + ALL_TREES.items(), [np.float64, np.float32] + ): + est = TreeEstimator(random_state=0) + + # Nothing + X = np.asarray(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # C-order + X = np.asarray(iris.data, order="C", dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # F-order + X = np.asarray(iris.data, order="F", dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # Contiguous + X = np.ascontiguousarray(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # csr matrix + X = csr_matrix(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # csc_matrix + X = csc_matrix(iris.data, dtype=dtype) + y = iris.target + assert_array_equal(est.fit(X, y).predict(X), y) + + # Strided + X = np.asarray(iris.data[::3], dtype=dtype) + y = iris.target[::3] + assert_array_equal(est.fit(X, y).predict(X), y) + + +def test_sample_weight(): + # Check sample weighting. + # Test that zero-weighted samples are not taken into account + X = np.arange(100)[:, np.newaxis] + y = np.ones(100) + y[:50] = 0.0 + + sample_weight = np.ones(100) + sample_weight[y == 0] = 0.0 + + clf = DecisionTreeClassifier(random_state=0) + clf.fit(X, y, sample_weight=sample_weight) + assert_array_equal(clf.predict(X), np.ones(100)) + + # Test that low weighted samples are not taken into account at low depth + X = np.arange(200)[:, np.newaxis] + y = np.zeros(200) + y[50:100] = 1 + y[100:200] = 2 + X[100:200, 0] = 200 + + sample_weight = np.ones(200) + + sample_weight[y == 2] = 0.51 # Samples of class '2' are still weightier + clf = DecisionTreeClassifier(max_depth=1, random_state=0) + clf.fit(X, y, sample_weight=sample_weight) + assert clf.tree_.threshold[0] == 149.5 + + sample_weight[y == 2] = 0.5 # Samples of class '2' are no longer weightier + clf = DecisionTreeClassifier(max_depth=1, random_state=0) + clf.fit(X, y, sample_weight=sample_weight) + assert clf.tree_.threshold[0] == 49.5 # Threshold should have moved + + # Test that sample weighting is the same as having duplicates + X = iris.data + y = iris.target + + duplicates = rng.randint(0, X.shape[0], 100) + + clf = DecisionTreeClassifier(random_state=1) + clf.fit(X[duplicates], y[duplicates]) + + sample_weight = np.bincount(duplicates, minlength=X.shape[0]) + clf2 = DecisionTreeClassifier(random_state=1) + clf2.fit(X, y, sample_weight=sample_weight) + + internal = clf.tree_.children_left != tree._tree.TREE_LEAF + assert_array_almost_equal( + clf.tree_.threshold[internal], clf2.tree_.threshold[internal] + ) + + +def test_sample_weight_invalid(): + # Check sample weighting raises errors. + X = np.arange(100)[:, np.newaxis] + y = np.ones(100) + y[:50] = 0.0 + + clf = DecisionTreeClassifier(random_state=0) + + sample_weight = np.random.rand(100, 1) + with pytest.raises(ValueError): + clf.fit(X, y, sample_weight=sample_weight) + + sample_weight = np.array(0) + expected_err = r"Singleton.* cannot be considered a valid collection" + with pytest.raises(TypeError, match=expected_err): + clf.fit(X, y, sample_weight=sample_weight) + + +def check_class_weights(name): + """Check class_weights resemble sample_weights behavior.""" + TreeClassifier = CLF_TREES[name] + + # Iris is balanced, so no effect expected for using 'balanced' weights + clf1 = TreeClassifier(random_state=0) + clf1.fit(iris.data, iris.target) + clf2 = TreeClassifier(class_weight="balanced", random_state=0) + clf2.fit(iris.data, iris.target) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + # Make a multi-output problem with three copies of Iris + iris_multi = np.vstack((iris.target, iris.target, iris.target)).T + # Create user-defined weights that should balance over the outputs + clf3 = TreeClassifier( + class_weight=[ + {0: 2.0, 1: 2.0, 2: 1.0}, + {0: 2.0, 1: 1.0, 2: 2.0}, + {0: 1.0, 1: 2.0, 2: 2.0}, + ], + random_state=0, + ) + clf3.fit(iris.data, iris_multi) + assert_almost_equal(clf2.feature_importances_, clf3.feature_importances_) + # Check against multi-output "auto" which should also have no effect + clf4 = TreeClassifier(class_weight="balanced", random_state=0) + clf4.fit(iris.data, iris_multi) + assert_almost_equal(clf3.feature_importances_, clf4.feature_importances_) + + # Inflate importance of class 1, check against user-defined weights + sample_weight = np.ones(iris.target.shape) + sample_weight[iris.target == 1] *= 100 + class_weight = {0: 1.0, 1: 100.0, 2: 1.0} + clf1 = TreeClassifier(random_state=0) + clf1.fit(iris.data, iris.target, sample_weight) + clf2 = TreeClassifier(class_weight=class_weight, random_state=0) + clf2.fit(iris.data, iris.target) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + # Check that sample_weight and class_weight are multiplicative + clf1 = TreeClassifier(random_state=0) + clf1.fit(iris.data, iris.target, sample_weight**2) + clf2 = TreeClassifier(class_weight=class_weight, random_state=0) + clf2.fit(iris.data, iris.target, sample_weight) + assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_) + + +@pytest.mark.parametrize("name", CLF_TREES) +def test_class_weights(name): + check_class_weights(name) + + +def check_class_weight_errors(name): + # Test if class_weight raises errors and warnings when expected. + TreeClassifier = CLF_TREES[name] + _y = np.vstack((y, np.array(y) * 2)).T + + # Incorrect length list for multi-output + clf = TreeClassifier(class_weight=[{-1: 0.5, 1: 1.0}], random_state=0) + err_msg = "number of elements in class_weight should match number of outputs." + with pytest.raises(ValueError, match=err_msg): + clf.fit(X, _y) + + +@pytest.mark.parametrize("name", CLF_TREES) +def test_class_weight_errors(name): + check_class_weight_errors(name) + + +def test_max_leaf_nodes(): + # Test greedy trees with max_depth + 1 leafs. + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + k = 4 + for name, TreeEstimator in ALL_TREES.items(): + est = TreeEstimator(max_depth=None, max_leaf_nodes=k + 1).fit(X, y) + assert est.get_n_leaves() == k + 1 + + +def test_max_leaf_nodes_max_depth(): + # Test precedence of max_leaf_nodes over max_depth. + X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1) + k = 4 + for name, TreeEstimator in ALL_TREES.items(): + est = TreeEstimator(max_depth=1, max_leaf_nodes=k).fit(X, y) + assert est.get_depth() == 1 + + +def test_arrays_persist(): + # Ensure property arrays' memory stays alive when tree disappears + # non-regression for #2726 + for attr in [ + "n_classes", + "value", + "children_left", + "children_right", + "threshold", + "impurity", + "feature", + "n_node_samples", + ]: + value = getattr(DecisionTreeClassifier().fit([[0], [1]], [0, 1]).tree_, attr) + # if pointing to freed memory, contents may be arbitrary + assert -3 <= value.flat[0] < 3, "Array points to arbitrary memory" + + +def test_only_constant_features(): + random_state = check_random_state(0) + X = np.zeros((10, 20)) + y = random_state.randint(0, 2, (10,)) + for name, TreeEstimator in ALL_TREES.items(): + est = TreeEstimator(random_state=0) + est.fit(X, y) + assert est.tree_.max_depth == 0 + + +def test_behaviour_constant_feature_after_splits(): + X = np.transpose( + np.vstack(([[0, 0, 0, 0, 0, 1, 2, 4, 5, 6, 7]], np.zeros((4, 11)))) + ) + y = [0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 3] + for name, TreeEstimator in ALL_TREES.items(): + # do not check extra random trees + if "ExtraTree" not in name: + est = TreeEstimator(random_state=0, max_features=1) + est.fit(X, y) + assert est.tree_.max_depth == 2 + assert est.tree_.node_count == 5 + + +def test_with_only_one_non_constant_features(): + X = np.hstack([np.array([[1.0], [1.0], [0.0], [0.0]]), np.zeros((4, 1000))]) + + y = np.array([0.0, 1.0, 0.0, 1.0]) + for name, TreeEstimator in CLF_TREES.items(): + est = TreeEstimator(random_state=0, max_features=1) + est.fit(X, y) + assert est.tree_.max_depth == 1 + assert_array_equal(est.predict_proba(X), np.full((4, 2), 0.5)) + + for name, TreeEstimator in REG_TREES.items(): + est = TreeEstimator(random_state=0, max_features=1) + est.fit(X, y) + assert est.tree_.max_depth == 1 + assert_array_equal(est.predict(X), np.full((4,), 0.5)) + + +def test_big_input(): + # Test if the warning for too large inputs is appropriate. + X = np.repeat(10**40.0, 4).astype(np.float64).reshape(-1, 1) + clf = DecisionTreeClassifier() + with pytest.raises(ValueError, match="float32"): + clf.fit(X, [0, 1, 0, 1]) + + +def test_realloc(): + from sklearn.tree._utils import _realloc_test + + with pytest.raises(MemoryError): + _realloc_test() + + +def test_huge_allocations(): + n_bits = 8 * struct.calcsize("P") + + X = np.random.randn(10, 2) + y = np.random.randint(0, 2, 10) + + # Sanity check: we cannot request more memory than the size of the address + # space. Currently raises OverflowError. + huge = 2 ** (n_bits + 1) + clf = DecisionTreeClassifier(splitter="best", max_leaf_nodes=huge) + with pytest.raises(Exception): + clf.fit(X, y) + + # Non-regression test: MemoryError used to be dropped by Cython + # because of missing "except *". + huge = 2 ** (n_bits - 1) - 1 + clf = DecisionTreeClassifier(splitter="best", max_leaf_nodes=huge) + with pytest.raises(MemoryError): + clf.fit(X, y) + + +def check_sparse_input(tree, dataset, max_depth=None): + TreeEstimator = ALL_TREES[tree] + X = DATASETS[dataset]["X"] + X_sparse = DATASETS[dataset]["X_sparse"] + y = DATASETS[dataset]["y"] + + # Gain testing time + if dataset in ["digits", "diabetes"]: + n_samples = X.shape[0] // 5 + X = X[:n_samples] + X_sparse = X_sparse[:n_samples] + y = y[:n_samples] + + for sparse_format in (csr_matrix, csc_matrix, coo_matrix): + X_sparse = sparse_format(X_sparse) + + # Check the default (depth first search) + d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y) + s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y) + + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + + y_pred = d.predict(X) + if tree in CLF_TREES: + y_proba = d.predict_proba(X) + y_log_proba = d.predict_log_proba(X) + + for sparse_matrix in (csr_matrix, csc_matrix, coo_matrix): + X_sparse_test = sparse_matrix(X_sparse, dtype=np.float32) + + assert_array_almost_equal(s.predict(X_sparse_test), y_pred) + + if tree in CLF_TREES: + assert_array_almost_equal(s.predict_proba(X_sparse_test), y_proba) + assert_array_almost_equal( + s.predict_log_proba(X_sparse_test), y_log_proba + ) + + +@pytest.mark.parametrize("tree_type", SPARSE_TREES) +@pytest.mark.parametrize( + "dataset", + ( + "clf_small", + "toy", + "digits", + "multilabel", + "sparse-pos", + "sparse-neg", + "sparse-mix", + "zeros", + ), +) +def test_sparse_input(tree_type, dataset): + max_depth = 3 if dataset == "digits" else None + check_sparse_input(tree_type, dataset, max_depth) + + +@pytest.mark.parametrize("tree_type", sorted(set(SPARSE_TREES).intersection(REG_TREES))) +@pytest.mark.parametrize("dataset", ["diabetes", "reg_small"]) +def test_sparse_input_reg_trees(tree_type, dataset): + # Due to numerical instability of MSE and too strict test, we limit the + # maximal depth + check_sparse_input(tree_type, dataset, 2) + + +def check_sparse_parameters(tree, dataset): + TreeEstimator = ALL_TREES[tree] + X = DATASETS[dataset]["X"] + X_sparse = DATASETS[dataset]["X_sparse"] + y = DATASETS[dataset]["y"] + + # Check max_features + d = TreeEstimator(random_state=0, max_features=1, max_depth=2).fit(X, y) + s = TreeEstimator(random_state=0, max_features=1, max_depth=2).fit(X_sparse, y) + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + # Check min_samples_split + d = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).fit(X, y) + s = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).fit( + X_sparse, y + ) + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + # Check min_samples_leaf + d = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).fit(X, y) + s = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).fit( + X_sparse, y + ) + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + # Check best-first search + d = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X, y) + s = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X_sparse, y) + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + +def check_sparse_criterion(tree, dataset): + TreeEstimator = ALL_TREES[tree] + X = DATASETS[dataset]["X"] + X_sparse = DATASETS[dataset]["X_sparse"] + y = DATASETS[dataset]["y"] + + # Check various criterion + CRITERIONS = REG_CRITERIONS if tree in REG_TREES else CLF_CRITERIONS + for criterion in CRITERIONS: + d = TreeEstimator(random_state=0, max_depth=3, criterion=criterion).fit(X, y) + s = TreeEstimator(random_state=0, max_depth=3, criterion=criterion).fit( + X_sparse, y + ) + + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + assert_array_almost_equal(s.predict(X), d.predict(X)) + + +@pytest.mark.parametrize("tree_type", SPARSE_TREES) +@pytest.mark.parametrize("dataset", ["sparse-pos", "sparse-neg", "sparse-mix", "zeros"]) +@pytest.mark.parametrize("check", [check_sparse_parameters, check_sparse_criterion]) +def test_sparse(tree_type, dataset, check): + check(tree_type, dataset) + + +def check_explicit_sparse_zeros(tree, max_depth=3, n_features=10): + TreeEstimator = ALL_TREES[tree] + + # n_samples set n_feature to ease construction of a simultaneous + # construction of a csr and csc matrix + n_samples = n_features + samples = np.arange(n_samples) + + # Generate X, y + random_state = check_random_state(0) + indices = [] + data = [] + offset = 0 + indptr = [offset] + for i in range(n_features): + n_nonzero_i = random_state.binomial(n_samples, 0.5) + indices_i = random_state.permutation(samples)[:n_nonzero_i] + indices.append(indices_i) + data_i = random_state.binomial(3, 0.5, size=(n_nonzero_i,)) - 1 + data.append(data_i) + offset += n_nonzero_i + indptr.append(offset) + + indices = np.concatenate(indices) + data = np.array(np.concatenate(data), dtype=np.float32) + X_sparse = csc_matrix((data, indices, indptr), shape=(n_samples, n_features)) + X = X_sparse.toarray() + X_sparse_test = csr_matrix((data, indices, indptr), shape=(n_samples, n_features)) + X_test = X_sparse_test.toarray() + y = random_state.randint(0, 3, size=(n_samples,)) + + # Ensure that X_sparse_test owns its data, indices and indptr array + X_sparse_test = X_sparse_test.copy() + + # Ensure that we have explicit zeros + assert (X_sparse.data == 0.0).sum() > 0 + assert (X_sparse_test.data == 0.0).sum() > 0 + + # Perform the comparison + d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y) + s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y) + + assert_tree_equal( + d.tree_, + s.tree_, + "{0} with dense and sparse format gave different trees".format(tree), + ) + + Xs = (X_test, X_sparse_test) + for X1, X2 in product(Xs, Xs): + assert_array_almost_equal(s.tree_.apply(X1), d.tree_.apply(X2)) + assert_array_almost_equal(s.apply(X1), d.apply(X2)) + assert_array_almost_equal(s.apply(X1), s.tree_.apply(X1)) + + assert_array_almost_equal( + s.tree_.decision_path(X1).toarray(), d.tree_.decision_path(X2).toarray() + ) + assert_array_almost_equal( + s.decision_path(X1).toarray(), d.decision_path(X2).toarray() + ) + assert_array_almost_equal( + s.decision_path(X1).toarray(), s.tree_.decision_path(X1).toarray() + ) + + assert_array_almost_equal(s.predict(X1), d.predict(X2)) + + if tree in CLF_TREES: + assert_array_almost_equal(s.predict_proba(X1), d.predict_proba(X2)) + + +@pytest.mark.parametrize("tree_type", SPARSE_TREES) +def test_explicit_sparse_zeros(tree_type): + check_explicit_sparse_zeros(tree_type) + + +@ignore_warnings +def check_raise_error_on_1d_input(name): + TreeEstimator = ALL_TREES[name] + + X = iris.data[:, 0].ravel() + X_2d = iris.data[:, 0].reshape((-1, 1)) + y = iris.target + + with pytest.raises(ValueError): + TreeEstimator(random_state=0).fit(X, y) + + est = TreeEstimator(random_state=0) + est.fit(X_2d, y) + with pytest.raises(ValueError): + est.predict([X]) + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_1d_input(name): + with ignore_warnings(): + check_raise_error_on_1d_input(name) + + +def _check_min_weight_leaf_split_level(TreeEstimator, X, y, sample_weight): + est = TreeEstimator(random_state=0) + est.fit(X, y, sample_weight=sample_weight) + assert est.tree_.max_depth == 1 + + est = TreeEstimator(random_state=0, min_weight_fraction_leaf=0.4) + est.fit(X, y, sample_weight=sample_weight) + assert est.tree_.max_depth == 0 + + +def check_min_weight_leaf_split_level(name): + TreeEstimator = ALL_TREES[name] + + X = np.array([[0], [0], [0], [0], [1]]) + y = [0, 0, 0, 0, 1] + sample_weight = [0.2, 0.2, 0.2, 0.2, 0.2] + _check_min_weight_leaf_split_level(TreeEstimator, X, y, sample_weight) + + _check_min_weight_leaf_split_level(TreeEstimator, csc_matrix(X), y, sample_weight) + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_min_weight_leaf_split_level(name): + check_min_weight_leaf_split_level(name) + + +def check_public_apply(name): + X_small32 = X_small.astype(tree._tree.DTYPE, copy=False) + + est = ALL_TREES[name]() + est.fit(X_small, y_small) + assert_array_equal(est.apply(X_small), est.tree_.apply(X_small32)) + + +def check_public_apply_sparse(name): + X_small32 = csr_matrix(X_small.astype(tree._tree.DTYPE, copy=False)) + + est = ALL_TREES[name]() + est.fit(X_small, y_small) + assert_array_equal(est.apply(X_small), est.tree_.apply(X_small32)) + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_public_apply_all_trees(name): + check_public_apply(name) + + +@pytest.mark.parametrize("name", SPARSE_TREES) +def test_public_apply_sparse_trees(name): + check_public_apply_sparse(name) + + +def test_decision_path_hardcoded(): + X = iris.data + y = iris.target + est = DecisionTreeClassifier(random_state=0, max_depth=1).fit(X, y) + node_indicator = est.decision_path(X[:2]).toarray() + assert_array_equal(node_indicator, [[1, 1, 0], [1, 0, 1]]) + + +def check_decision_path(name): + X = iris.data + y = iris.target + n_samples = X.shape[0] + + TreeEstimator = ALL_TREES[name] + est = TreeEstimator(random_state=0, max_depth=2) + est.fit(X, y) + + node_indicator_csr = est.decision_path(X) + node_indicator = node_indicator_csr.toarray() + assert node_indicator.shape == (n_samples, est.tree_.node_count) + + # Assert that leaves index are correct + leaves = est.apply(X) + leave_indicator = [node_indicator[i, j] for i, j in enumerate(leaves)] + assert_array_almost_equal(leave_indicator, np.ones(shape=n_samples)) + + # Ensure only one leave node per sample + all_leaves = est.tree_.children_left == TREE_LEAF + assert_array_almost_equal( + np.dot(node_indicator, all_leaves), np.ones(shape=n_samples) + ) + + # Ensure max depth is consistent with sum of indicator + max_depth = node_indicator.sum(axis=1).max() + assert est.tree_.max_depth <= max_depth + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_decision_path(name): + check_decision_path(name) + + +def check_no_sparse_y_support(name): + X, y = X_multilabel, csr_matrix(y_multilabel) + TreeEstimator = ALL_TREES[name] + with pytest.raises(TypeError): + TreeEstimator(random_state=0).fit(X, y) + + +@pytest.mark.parametrize("name", ALL_TREES) +def test_no_sparse_y_support(name): + # Currently we don't support sparse y + check_no_sparse_y_support(name) + + +def test_mae(): + """Check MAE criterion produces correct results on small toy dataset: + + ------------------ + | X | y | weight | + ------------------ + | 3 | 3 | 0.1 | + | 5 | 3 | 0.3 | + | 8 | 4 | 1.0 | + | 3 | 6 | 0.6 | + | 5 | 7 | 0.3 | + ------------------ + |sum wt:| 2.3 | + ------------------ + + Because we are dealing with sample weights, we cannot find the median by + simply choosing/averaging the centre value(s), instead we consider the + median where 50% of the cumulative weight is found (in a y sorted data set) + . Therefore with regards to this test data, the cumulative weight is >= 50% + when y = 4. Therefore: + Median = 4 + + For all the samples, we can get the total error by summing: + Absolute(Median - y) * weight + + I.e., total error = (Absolute(4 - 3) * 0.1) + + (Absolute(4 - 3) * 0.3) + + (Absolute(4 - 4) * 1.0) + + (Absolute(4 - 6) * 0.6) + + (Absolute(4 - 7) * 0.3) + = 2.5 + + Impurity = Total error / total weight + = 2.5 / 2.3 + = 1.08695652173913 + ------------------ + + From this root node, the next best split is between X values of 3 and 5. + Thus, we have left and right child nodes: + + LEFT RIGHT + ------------------ ------------------ + | X | y | weight | | X | y | weight | + ------------------ ------------------ + | 3 | 3 | 0.1 | | 5 | 3 | 0.3 | + | 3 | 6 | 0.6 | | 8 | 4 | 1.0 | + ------------------ | 5 | 7 | 0.3 | + |sum wt:| 0.7 | ------------------ + ------------------ |sum wt:| 1.6 | + ------------------ + + Impurity is found in the same way: + Left node Median = 6 + Total error = (Absolute(6 - 3) * 0.1) + + (Absolute(6 - 6) * 0.6) + = 0.3 + + Left Impurity = Total error / total weight + = 0.3 / 0.7 + = 0.428571428571429 + ------------------- + + Likewise for Right node: + Right node Median = 4 + Total error = (Absolute(4 - 3) * 0.3) + + (Absolute(4 - 4) * 1.0) + + (Absolute(4 - 7) * 0.3) + = 1.2 + + Right Impurity = Total error / total weight + = 1.2 / 1.6 + = 0.75 + ------ + """ + dt_mae = DecisionTreeRegressor( + random_state=0, criterion="absolute_error", max_leaf_nodes=2 + ) + + # Test MAE where sample weights are non-uniform (as illustrated above): + dt_mae.fit( + X=[[3], [5], [3], [8], [5]], + y=[6, 7, 3, 4, 3], + sample_weight=[0.6, 0.3, 0.1, 1.0, 0.3], + ) + assert_allclose(dt_mae.tree_.impurity, [2.5 / 2.3, 0.3 / 0.7, 1.2 / 1.6]) + assert_array_equal(dt_mae.tree_.value.flat, [4.0, 6.0, 4.0]) + + # Test MAE where all sample weights are uniform: + dt_mae.fit(X=[[3], [5], [3], [8], [5]], y=[6, 7, 3, 4, 3], sample_weight=np.ones(5)) + assert_array_equal(dt_mae.tree_.impurity, [1.4, 1.5, 4.0 / 3.0]) + assert_array_equal(dt_mae.tree_.value.flat, [4, 4.5, 4.0]) + + # Test MAE where a `sample_weight` is not explicitly provided. + # This is equivalent to providing uniform sample weights, though + # the internal logic is different: + dt_mae.fit(X=[[3], [5], [3], [8], [5]], y=[6, 7, 3, 4, 3]) + assert_array_equal(dt_mae.tree_.impurity, [1.4, 1.5, 4.0 / 3.0]) + assert_array_equal(dt_mae.tree_.value.flat, [4, 4.5, 4.0]) + + +def test_criterion_copy(): + # Let's check whether copy of our criterion has the same type + # and properties as original + n_outputs = 3 + n_classes = np.arange(3, dtype=np.intp) + n_samples = 100 + + def _pickle_copy(obj): + return pickle.loads(pickle.dumps(obj)) + + for copy_func in [copy.copy, copy.deepcopy, _pickle_copy]: + for _, typename in CRITERIA_CLF.items(): + criteria = typename(n_outputs, n_classes) + result = copy_func(criteria).__reduce__() + typename_, (n_outputs_, n_classes_), _ = result + assert typename == typename_ + assert n_outputs == n_outputs_ + assert_array_equal(n_classes, n_classes_) + + for _, typename in CRITERIA_REG.items(): + criteria = typename(n_outputs, n_samples) + result = copy_func(criteria).__reduce__() + typename_, (n_outputs_, n_samples_), _ = result + assert typename == typename_ + assert n_outputs == n_outputs_ + assert n_samples == n_samples_ + + +def test_empty_leaf_infinite_threshold(): + # try to make empty leaf by using near infinite value. + data = np.random.RandomState(0).randn(100, 11) * 2e38 + data = np.nan_to_num(data.astype("float32")) + X_full = data[:, :-1] + X_sparse = csc_matrix(X_full) + y = data[:, -1] + for X in [X_full, X_sparse]: + tree = DecisionTreeRegressor(random_state=0).fit(X, y) + terminal_regions = tree.apply(X) + left_leaf = set(np.where(tree.tree_.children_left == TREE_LEAF)[0]) + empty_leaf = left_leaf.difference(terminal_regions) + infinite_threshold = np.where(~np.isfinite(tree.tree_.threshold))[0] + assert len(infinite_threshold) == 0 + assert len(empty_leaf) == 0 + + +@pytest.mark.parametrize("criterion", CLF_CRITERIONS) +@pytest.mark.parametrize( + "dataset", sorted(set(DATASETS.keys()) - {"reg_small", "diabetes"}) +) +@pytest.mark.parametrize("tree_cls", [DecisionTreeClassifier, ExtraTreeClassifier]) +def test_prune_tree_classifier_are_subtrees(criterion, dataset, tree_cls): + dataset = DATASETS[dataset] + X, y = dataset["X"], dataset["y"] + est = tree_cls(max_leaf_nodes=20, random_state=0) + info = est.cost_complexity_pruning_path(X, y) + + pruning_path = info.ccp_alphas + impurities = info.impurities + assert np.all(np.diff(pruning_path) >= 0) + assert np.all(np.diff(impurities) >= 0) + + assert_pruning_creates_subtree(tree_cls, X, y, pruning_path) + + +@pytest.mark.parametrize("criterion", REG_CRITERIONS) +@pytest.mark.parametrize("dataset", DATASETS.keys()) +@pytest.mark.parametrize("tree_cls", [DecisionTreeRegressor, ExtraTreeRegressor]) +def test_prune_tree_regression_are_subtrees(criterion, dataset, tree_cls): + dataset = DATASETS[dataset] + X, y = dataset["X"], dataset["y"] + + est = tree_cls(max_leaf_nodes=20, random_state=0) + info = est.cost_complexity_pruning_path(X, y) + + pruning_path = info.ccp_alphas + impurities = info.impurities + assert np.all(np.diff(pruning_path) >= 0) + assert np.all(np.diff(impurities) >= 0) + + assert_pruning_creates_subtree(tree_cls, X, y, pruning_path) + + +def test_prune_single_node_tree(): + # single node tree + clf1 = DecisionTreeClassifier(random_state=0) + clf1.fit([[0], [1]], [0, 0]) + + # pruned single node tree + clf2 = DecisionTreeClassifier(random_state=0, ccp_alpha=10) + clf2.fit([[0], [1]], [0, 0]) + + assert_is_subtree(clf1.tree_, clf2.tree_) + + +def assert_pruning_creates_subtree(estimator_cls, X, y, pruning_path): + # generate trees with increasing alphas + estimators = [] + for ccp_alpha in pruning_path: + est = estimator_cls(max_leaf_nodes=20, ccp_alpha=ccp_alpha, random_state=0).fit( + X, y + ) + estimators.append(est) + + # A pruned tree must be a subtree of the previous tree (which had a + # smaller ccp_alpha) + for prev_est, next_est in zip(estimators, estimators[1:]): + assert_is_subtree(prev_est.tree_, next_est.tree_) + + +def assert_is_subtree(tree, subtree): + assert tree.node_count >= subtree.node_count + assert tree.max_depth >= subtree.max_depth + + tree_c_left = tree.children_left + tree_c_right = tree.children_right + subtree_c_left = subtree.children_left + subtree_c_right = subtree.children_right + + stack = [(0, 0)] + while stack: + tree_node_idx, subtree_node_idx = stack.pop() + assert_array_almost_equal( + tree.value[tree_node_idx], subtree.value[subtree_node_idx] + ) + assert_almost_equal( + tree.impurity[tree_node_idx], subtree.impurity[subtree_node_idx] + ) + assert_almost_equal( + tree.n_node_samples[tree_node_idx], subtree.n_node_samples[subtree_node_idx] + ) + assert_almost_equal( + tree.weighted_n_node_samples[tree_node_idx], + subtree.weighted_n_node_samples[subtree_node_idx], + ) + + if subtree_c_left[subtree_node_idx] == subtree_c_right[subtree_node_idx]: + # is a leaf + assert_almost_equal(TREE_UNDEFINED, subtree.threshold[subtree_node_idx]) + else: + # not a leaf + assert_almost_equal( + tree.threshold[tree_node_idx], subtree.threshold[subtree_node_idx] + ) + stack.append((tree_c_left[tree_node_idx], subtree_c_left[subtree_node_idx])) + stack.append( + (tree_c_right[tree_node_idx], subtree_c_right[subtree_node_idx]) + ) + + +@pytest.mark.parametrize("name", ALL_TREES) +@pytest.mark.parametrize("splitter", ["best", "random"]) +@pytest.mark.parametrize("X_format", ["dense", "csr", "csc"]) +def test_apply_path_readonly_all_trees(name, splitter, X_format): + dataset = DATASETS["clf_small"] + X_small = dataset["X"].astype(tree._tree.DTYPE, copy=False) + if X_format == "dense": + X_readonly = create_memmap_backed_data(X_small) + else: + X_readonly = dataset["X_sparse"] # CSR + if X_format == "csc": + # Cheap CSR to CSC conversion + X_readonly = X_readonly.tocsc() + + X_readonly.data = np.array(X_readonly.data, dtype=tree._tree.DTYPE) + ( + X_readonly.data, + X_readonly.indices, + X_readonly.indptr, + ) = create_memmap_backed_data( + (X_readonly.data, X_readonly.indices, X_readonly.indptr) + ) + + y_readonly = create_memmap_backed_data(np.array(y_small, dtype=tree._tree.DTYPE)) + est = ALL_TREES[name](splitter=splitter) + est.fit(X_readonly, y_readonly) + assert_array_equal(est.predict(X_readonly), est.predict(X_small)) + assert_array_equal( + est.decision_path(X_readonly).todense(), est.decision_path(X_small).todense() + ) + + +@pytest.mark.parametrize("criterion", ["squared_error", "friedman_mse", "poisson"]) +@pytest.mark.parametrize("Tree", REG_TREES.values()) +def test_balance_property(criterion, Tree): + # Test that sum(y_pred)=sum(y_true) on training set. + # This works if the mean is predicted (should even be true for each leaf). + # MAE predicts the median and is therefore excluded from this test. + + # Choose a training set with non-negative targets (for poisson) + X, y = diabetes.data, diabetes.target + reg = Tree(criterion=criterion) + reg.fit(X, y) + assert np.sum(reg.predict(X)) == pytest.approx(np.sum(y)) + + +@pytest.mark.parametrize("seed", range(3)) +def test_poisson_zero_nodes(seed): + # Test that sum(y)=0 and therefore y_pred=0 is forbidden on nodes. + X = [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 2], [1, 2], [1, 3]] + y = [0, 0, 0, 0, 1, 2, 3, 4] + # Note that X[:, 0] == 0 is a 100% indicator for y == 0. The tree can + # easily learn that: + reg = DecisionTreeRegressor(criterion="squared_error", random_state=seed) + reg.fit(X, y) + assert np.amin(reg.predict(X)) == 0 + # whereas Poisson must predict strictly positive numbers + reg = DecisionTreeRegressor(criterion="poisson", random_state=seed) + reg.fit(X, y) + assert np.all(reg.predict(X) > 0) + + # Test additional dataset where something could go wrong. + n_features = 10 + X, y = datasets.make_regression( + effective_rank=n_features * 2 // 3, + tail_strength=0.6, + n_samples=1_000, + n_features=n_features, + n_informative=n_features * 2 // 3, + random_state=seed, + ) + # some excess zeros + y[(-1 < y) & (y < 0)] = 0 + # make sure the target is positive + y = np.abs(y) + reg = DecisionTreeRegressor(criterion="poisson", random_state=seed) + reg.fit(X, y) + assert np.all(reg.predict(X) > 0) + + +def test_poisson_vs_mse(): + # For a Poisson distributed target, Poisson loss should give better results + # than squared error measured in Poisson deviance as metric. + # We have a similar test, test_poisson(), in + # sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py + rng = np.random.RandomState(42) + n_train, n_test, n_features = 500, 500, 10 + X = datasets.make_low_rank_matrix( + n_samples=n_train + n_test, n_features=n_features, random_state=rng + ) + # We create a log-linear Poisson model and downscale coef as it will get + # exponentiated. + coef = rng.uniform(low=-2, high=2, size=n_features) / np.max(X, axis=0) + y = rng.poisson(lam=np.exp(X @ coef)) + X_train, X_test, y_train, y_test = train_test_split( + X, y, test_size=n_test, random_state=rng + ) + # We prevent some overfitting by setting min_samples_split=10. + tree_poi = DecisionTreeRegressor( + criterion="poisson", min_samples_split=10, random_state=rng + ) + tree_mse = DecisionTreeRegressor( + criterion="squared_error", min_samples_split=10, random_state=rng + ) + + tree_poi.fit(X_train, y_train) + tree_mse.fit(X_train, y_train) + dummy = DummyRegressor(strategy="mean").fit(X_train, y_train) + + for X, y, val in [(X_train, y_train, "train"), (X_test, y_test, "test")]: + metric_poi = mean_poisson_deviance(y, tree_poi.predict(X)) + # squared_error might produce non-positive predictions => clip + metric_mse = mean_poisson_deviance(y, np.clip(tree_mse.predict(X), 1e-15, None)) + metric_dummy = mean_poisson_deviance(y, dummy.predict(X)) + # As squared_error might correctly predict 0 in train set, its train + # score can be better than Poisson. This is no longer the case for the + # test set. + if val == "test": + assert metric_poi < 0.5 * metric_mse + assert metric_poi < 0.75 * metric_dummy + + +@pytest.mark.parametrize("criterion", REG_CRITERIONS) +def test_decision_tree_regressor_sample_weight_consistency(criterion): + """Test that the impact of sample_weight is consistent.""" + tree_params = dict(criterion=criterion) + tree = DecisionTreeRegressor(**tree_params, random_state=42) + for kind in ["zeros", "ones"]: + check_sample_weights_invariance( + "DecisionTreeRegressor_" + criterion, tree, kind="zeros" + ) + + rng = np.random.RandomState(0) + n_samples, n_features = 10, 5 + + X = rng.rand(n_samples, n_features) + y = np.mean(X, axis=1) + rng.rand(n_samples) + # make it positive in order to work also for poisson criterion + y += np.min(y) + 0.1 + + # check that multiplying sample_weight by 2 is equivalent + # to repeating corresponding samples twice + X2 = np.concatenate([X, X[: n_samples // 2]], axis=0) + y2 = np.concatenate([y, y[: n_samples // 2]]) + sample_weight_1 = np.ones(len(y)) + sample_weight_1[: n_samples // 2] = 2 + + tree1 = DecisionTreeRegressor(**tree_params).fit( + X, y, sample_weight=sample_weight_1 + ) + + tree2 = DecisionTreeRegressor(**tree_params).fit(X2, y2, sample_weight=None) + + assert tree1.tree_.node_count == tree2.tree_.node_count + # Thresholds, tree.tree_.threshold, and values, tree.tree_.value, are not + # exactly the same, but on the training set, those differences do not + # matter and thus predictions are the same. + assert_allclose(tree1.predict(X), tree2.predict(X)) + + +@pytest.mark.parametrize("Tree", [DecisionTreeClassifier, ExtraTreeClassifier]) +@pytest.mark.parametrize("n_classes", [2, 4]) +def test_criterion_entropy_same_as_log_loss(Tree, n_classes): + """Test that criterion=entropy gives same as log_loss.""" + n_samples, n_features = 50, 5 + X, y = datasets.make_classification( + n_classes=n_classes, + n_samples=n_samples, + n_features=n_features, + n_informative=n_features, + n_redundant=0, + random_state=42, + ) + tree_log_loss = Tree(criterion="log_loss", random_state=43).fit(X, y) + tree_entropy = Tree(criterion="entropy", random_state=43).fit(X, y) + + assert_tree_equal( + tree_log_loss.tree_, + tree_entropy.tree_, + f"{Tree!r} with criterion 'entropy' and 'log_loss' gave different trees.", + ) + assert_allclose(tree_log_loss.predict(X), tree_entropy.predict(X)) + + +def test_different_endianness_pickle(): + X, y = datasets.make_classification(random_state=0) + + clf = DecisionTreeClassifier(random_state=0, max_depth=3) + clf.fit(X, y) + score = clf.score(X, y) + + def reduce_ndarray(arr): + return arr.byteswap().newbyteorder().__reduce__() + + def get_pickle_non_native_endianness(): + f = io.BytesIO() + p = pickle.Pickler(f) + p.dispatch_table = copyreg.dispatch_table.copy() + p.dispatch_table[np.ndarray] = reduce_ndarray + + p.dump(clf) + f.seek(0) + return f + + new_clf = pickle.load(get_pickle_non_native_endianness()) + new_score = new_clf.score(X, y) + assert np.isclose(score, new_score) + + +def test_different_endianness_joblib_pickle(): + X, y = datasets.make_classification(random_state=0) + + clf = DecisionTreeClassifier(random_state=0, max_depth=3) + clf.fit(X, y) + score = clf.score(X, y) + + class NonNativeEndiannessNumpyPickler(NumpyPickler): + def save(self, obj): + if isinstance(obj, np.ndarray): + obj = obj.byteswap().newbyteorder() + super().save(obj) + + def get_joblib_pickle_non_native_endianness(): + f = io.BytesIO() + p = NonNativeEndiannessNumpyPickler(f) + + p.dump(clf) + f.seek(0) + return f + + new_clf = joblib.load(get_joblib_pickle_non_native_endianness()) + new_score = new_clf.score(X, y) + assert np.isclose(score, new_score) + + +def get_different_bitness_node_ndarray(node_ndarray): + new_dtype_for_indexing_fields = np.int64 if _IS_32BIT else np.int32 + + # field names in Node struct with SIZE_t types (see sklearn/tree/_tree.pxd) + indexing_field_names = ["left_child", "right_child", "feature", "n_node_samples"] + + new_dtype_dict = { + name: dtype for name, (dtype, _) in node_ndarray.dtype.fields.items() + } + for name in indexing_field_names: + new_dtype_dict[name] = new_dtype_for_indexing_fields + + new_dtype = np.dtype( + {"names": list(new_dtype_dict.keys()), "formats": list(new_dtype_dict.values())} + ) + return node_ndarray.astype(new_dtype, casting="same_kind") + + +def get_different_alignment_node_ndarray(node_ndarray): + new_dtype_dict = { + name: dtype for name, (dtype, _) in node_ndarray.dtype.fields.items() + } + offsets = [offset for dtype, offset in node_ndarray.dtype.fields.values()] + shifted_offsets = [8 + offset for offset in offsets] + + new_dtype = np.dtype( + { + "names": list(new_dtype_dict.keys()), + "formats": list(new_dtype_dict.values()), + "offsets": shifted_offsets, + } + ) + return node_ndarray.astype(new_dtype, casting="same_kind") + + +def reduce_tree_with_different_bitness(tree): + new_dtype = np.int64 if _IS_32BIT else np.int32 + tree_cls, (n_features, n_classes, n_outputs), state = tree.__reduce__() + new_n_classes = n_classes.astype(new_dtype, casting="same_kind") + + new_state = state.copy() + new_state["nodes"] = get_different_bitness_node_ndarray(new_state["nodes"]) + + return (tree_cls, (n_features, new_n_classes, n_outputs), new_state) + + +def test_different_bitness_pickle(): + X, y = datasets.make_classification(random_state=0) + + clf = DecisionTreeClassifier(random_state=0, max_depth=3) + clf.fit(X, y) + score = clf.score(X, y) + + def pickle_dump_with_different_bitness(): + f = io.BytesIO() + p = pickle.Pickler(f) + p.dispatch_table = copyreg.dispatch_table.copy() + p.dispatch_table[CythonTree] = reduce_tree_with_different_bitness + + p.dump(clf) + f.seek(0) + return f + + new_clf = pickle.load(pickle_dump_with_different_bitness()) + new_score = new_clf.score(X, y) + assert score == pytest.approx(new_score) + + +def test_different_bitness_joblib_pickle(): + # Make sure that a platform specific pickle generated on a 64 bit + # platform can be converted at pickle load time into an estimator + # with Cython code that works with the host's native integer precision + # to index nodes in the tree data structure when the host is a 32 bit + # platform (and vice versa). + X, y = datasets.make_classification(random_state=0) + + clf = DecisionTreeClassifier(random_state=0, max_depth=3) + clf.fit(X, y) + score = clf.score(X, y) + + def joblib_dump_with_different_bitness(): + f = io.BytesIO() + p = NumpyPickler(f) + p.dispatch_table = copyreg.dispatch_table.copy() + p.dispatch_table[CythonTree] = reduce_tree_with_different_bitness + + p.dump(clf) + f.seek(0) + return f + + new_clf = joblib.load(joblib_dump_with_different_bitness()) + new_score = new_clf.score(X, y) + assert score == pytest.approx(new_score) + + +def test_check_n_classes(): + expected_dtype = np.dtype(np.int32) if _IS_32BIT else np.dtype(np.int64) + allowed_dtypes = [np.dtype(np.int32), np.dtype(np.int64)] + allowed_dtypes += [dt.newbyteorder() for dt in allowed_dtypes] + + n_classes = np.array([0, 1], dtype=expected_dtype) + for dt in allowed_dtypes: + _check_n_classes(n_classes.astype(dt), expected_dtype) + + with pytest.raises(ValueError, match="Wrong dimensions.+n_classes"): + wrong_dim_n_classes = np.array([[0, 1]], dtype=expected_dtype) + _check_n_classes(wrong_dim_n_classes, expected_dtype) + + with pytest.raises(ValueError, match="n_classes.+incompatible dtype"): + wrong_dtype_n_classes = n_classes.astype(np.float64) + _check_n_classes(wrong_dtype_n_classes, expected_dtype) + + +def test_check_value_ndarray(): + expected_dtype = np.dtype(np.float64) + expected_shape = (5, 1, 2) + value_ndarray = np.zeros(expected_shape, dtype=expected_dtype) + + allowed_dtypes = [expected_dtype, expected_dtype.newbyteorder()] + + for dt in allowed_dtypes: + _check_value_ndarray( + value_ndarray, expected_dtype=dt, expected_shape=expected_shape + ) + + with pytest.raises(ValueError, match="Wrong shape.+value array"): + _check_value_ndarray( + value_ndarray, expected_dtype=expected_dtype, expected_shape=(1, 2) + ) + + for problematic_arr in [value_ndarray[:, :, :1], np.asfortranarray(value_ndarray)]: + with pytest.raises(ValueError, match="value array.+C-contiguous"): + _check_value_ndarray( + problematic_arr, + expected_dtype=expected_dtype, + expected_shape=problematic_arr.shape, + ) + + with pytest.raises(ValueError, match="value array.+incompatible dtype"): + _check_value_ndarray( + value_ndarray.astype(np.float32), + expected_dtype=expected_dtype, + expected_shape=expected_shape, + ) + + +def test_check_node_ndarray(): + expected_dtype = NODE_DTYPE + + node_ndarray = np.zeros((5,), dtype=expected_dtype) + + valid_node_ndarrays = [ + node_ndarray, + get_different_bitness_node_ndarray(node_ndarray), + get_different_alignment_node_ndarray(node_ndarray), + ] + valid_node_ndarrays += [ + arr.astype(arr.dtype.newbyteorder()) for arr in valid_node_ndarrays + ] + + for arr in valid_node_ndarrays: + _check_node_ndarray(node_ndarray, expected_dtype=expected_dtype) + + with pytest.raises(ValueError, match="Wrong dimensions.+node array"): + problematic_node_ndarray = np.zeros((5, 2), dtype=expected_dtype) + _check_node_ndarray(problematic_node_ndarray, expected_dtype=expected_dtype) + + with pytest.raises(ValueError, match="node array.+C-contiguous"): + problematic_node_ndarray = node_ndarray[::2] + _check_node_ndarray(problematic_node_ndarray, expected_dtype=expected_dtype) + + dtype_dict = {name: dtype for name, (dtype, _) in node_ndarray.dtype.fields.items()} + + # array with wrong 'threshold' field dtype (int64 rather than float64) + new_dtype_dict = dtype_dict.copy() + new_dtype_dict["threshold"] = np.int64 + + new_dtype = np.dtype( + {"names": list(new_dtype_dict.keys()), "formats": list(new_dtype_dict.values())} + ) + problematic_node_ndarray = node_ndarray.astype(new_dtype) + + with pytest.raises(ValueError, match="node array.+incompatible dtype"): + _check_node_ndarray(problematic_node_ndarray, expected_dtype=expected_dtype) + + # array with wrong 'left_child' field dtype (float64 rather than int64 or int32) + new_dtype_dict = dtype_dict.copy() + new_dtype_dict["left_child"] = np.float64 + new_dtype = np.dtype( + {"names": list(new_dtype_dict.keys()), "formats": list(new_dtype_dict.values())} + ) + + problematic_node_ndarray = node_ndarray.astype(new_dtype) + + with pytest.raises(ValueError, match="node array.+incompatible dtype"): + _check_node_ndarray(problematic_node_ndarray, expected_dtype=expected_dtype) + + +# TODO(1.3): Remove +def test_max_features_auto_deprecated(): + for Tree in CLF_TREES.values(): + tree = Tree(max_features="auto") + msg = ( + "`max_features='auto'` has been deprecated in 1.1 and will be removed in" + " 1.3. To keep the past behaviour, explicitly set `max_features='sqrt'`." + ) + with pytest.warns(FutureWarning, match=msg): + tree.fit(X, y) + + for Tree in REG_TREES.values(): + tree = Tree(max_features="auto") + msg = ( + "`max_features='auto'` has been deprecated in 1.1 and will be removed in" + " 1.3. To keep the past behaviour, explicitly set `max_features=1.0'`." + ) + with pytest.warns(FutureWarning, match=msg): + tree.fit(X, y) + + +def test_tree_deserialization_from_read_only_buffer(tmpdir): + """Check that Trees can be deserialized with read only buffers. + + Non-regression test for gh-25584. + """ + pickle_path = str(tmpdir.join("clf.joblib")) + clf = DecisionTreeClassifier(random_state=0) + clf.fit(X_small, y_small) + + joblib.dump(clf, pickle_path) + loaded_clf = joblib.load(pickle_path, mmap_mode="r") + + assert_tree_equal( + loaded_clf.tree_, + clf.tree_, + "The trees of the original and loaded classifiers are not equal.", + ) + + +@pytest.mark.parametrize("Tree", ALL_TREES.values()) +def test_min_sample_split_1_error(Tree): + """Check that an error is raised when min_sample_split=1. + + non-regression test for issue gh-25481. + """ + X = np.array([[0, 0], [1, 1]]) + y = np.array([0, 1]) + + # min_samples_split=1.0 is valid + Tree(min_samples_split=1.0).fit(X, y) + + # min_samples_split=1 is invalid + tree = Tree(min_samples_split=1) + msg = ( + r"'min_samples_split' .* must be an int in the range \[2, inf\) " + r"or a float in the range \(0.0, 1.0\]" + ) + with pytest.raises(ValueError, match=msg): + tree.fit(X, y) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_arpack.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/_arpack.py new file mode 100644 index 0000000000000000000000000000000000000000..3465ac98c2e81a2fb1ad0c971e6494867d2cec1b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_arpack.py @@ -0,0 +1,30 @@ +from .validation import check_random_state + + +def _init_arpack_v0(size, random_state): + """Initialize the starting vector for iteration in ARPACK functions. + + Initialize a ndarray with values sampled from the uniform distribution on + [-1, 1]. This initialization model has been chosen to be consistent with + the ARPACK one as another initialization can lead to convergence issues. + + Parameters + ---------- + size : int + The size of the eigenvalue vector to be initialized. + + random_state : int, RandomState instance or None, default=None + The seed of the pseudo random number generator used to generate a + uniform distribution. If int, random_state is the seed used by the + random number generator; If RandomState instance, random_state is the + random number generator; If None, the random number generator is the + RandomState instance used by `np.random`. + + Returns + ------- + v0 : ndarray of shape (size,) + The initialized vector. + """ + random_state = check_random_state(random_state) + v0 = random_state.uniform(-1, 1, size) + return v0 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_array_api.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/_array_api.py new file mode 100644 index 0000000000000000000000000000000000000000..fff8e1ee33a49eb99fcbed856c2c2b48b4cc5124 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_array_api.py @@ -0,0 +1,232 @@ +"""Tools to support array_api.""" +import numpy +from .._config import get_config +import scipy.special as special + + +class _ArrayAPIWrapper: + """sklearn specific Array API compatibility wrapper + + This wrapper makes it possible for scikit-learn maintainers to + deal with discrepancies between different implementations of the + Python array API standard and its evolution over time. + + The Python array API standard specification: + https://data-apis.org/array-api/latest/ + + Documentation of the NumPy implementation: + https://numpy.org/neps/nep-0047-array-api-standard.html + """ + + def __init__(self, array_namespace): + self._namespace = array_namespace + + def __getattr__(self, name): + return getattr(self._namespace, name) + + def take(self, X, indices, *, axis): + # When array_api supports `take` we can use this directly + # https://github.com/data-apis/array-api/issues/177 + if self._namespace.__name__ == "numpy.array_api": + X_np = numpy.take(X, indices, axis=axis) + return self._namespace.asarray(X_np) + + # We only support axis in (0, 1) and ndim in (1, 2) because that is all we need + # in scikit-learn + if axis not in {0, 1}: + raise ValueError(f"Only axis in (0, 1) is supported. Got {axis}") + + if X.ndim not in {1, 2}: + raise ValueError(f"Only X.ndim in (1, 2) is supported. Got {X.ndim}") + + if axis == 0: + if X.ndim == 1: + selected = [X[i] for i in indices] + else: # X.ndim == 2 + selected = [X[i, :] for i in indices] + else: # axis == 1 + selected = [X[:, i] for i in indices] + return self._namespace.stack(selected, axis=axis) + + +class _NumPyApiWrapper: + """Array API compat wrapper for any numpy version + + NumPy < 1.22 does not expose the numpy.array_api namespace. This + wrapper makes it possible to write code that uses the standard + Array API while working with any version of NumPy supported by + scikit-learn. + + See the `get_namespace()` public function for more details. + """ + + def __getattr__(self, name): + return getattr(numpy, name) + + def astype(self, x, dtype, *, copy=True, casting="unsafe"): + # astype is not defined in the top level NumPy namespace + return x.astype(dtype, copy=copy, casting=casting) + + def asarray(self, x, *, dtype=None, device=None, copy=None): + # Support copy in NumPy namespace + if copy is True: + return numpy.array(x, copy=True, dtype=dtype) + else: + return numpy.asarray(x, dtype=dtype) + + def unique_inverse(self, x): + return numpy.unique(x, return_inverse=True) + + def unique_counts(self, x): + return numpy.unique(x, return_counts=True) + + def unique_values(self, x): + return numpy.unique(x) + + def concat(self, arrays, *, axis=None): + return numpy.concatenate(arrays, axis=axis) + + +def get_namespace(*arrays): + """Get namespace of arrays. + + Introspect `arrays` arguments and return their common Array API + compatible namespace object, if any. NumPy 1.22 and later can + construct such containers using the `numpy.array_api` namespace + for instance. + + See: https://numpy.org/neps/nep-0047-array-api-standard.html + + If `arrays` are regular numpy arrays, an instance of the + `_NumPyApiWrapper` compatibility wrapper is returned instead. + + Namespace support is not enabled by default. To enabled it + call: + + sklearn.set_config(array_api_dispatch=True) + + or: + + with sklearn.config_context(array_api_dispatch=True): + # your code here + + Otherwise an instance of the `_NumPyApiWrapper` + compatibility wrapper is always returned irrespective of + the fact that arrays implement the `__array_namespace__` + protocol or not. + + Parameters + ---------- + *arrays : array objects + Array objects. + + Returns + ------- + namespace : module + Namespace shared by array objects. + + is_array_api : bool + True of the arrays are containers that implement the Array API spec. + """ + # `arrays` contains one or more arrays, or possibly Python scalars (accepting + # those is a matter of taste, but doesn't seem unreasonable). + # Returns a tuple: (array_namespace, is_array_api) + + if not get_config()["array_api_dispatch"]: + return _NumPyApiWrapper(), False + + namespaces = { + x.__array_namespace__() if hasattr(x, "__array_namespace__") else None + for x in arrays + if not isinstance(x, (bool, int, float, complex)) + } + + if not namespaces: + # one could special-case np.ndarray above or use np.asarray here if + # older numpy versions need to be supported. + raise ValueError("Unrecognized array input") + + if len(namespaces) != 1: + raise ValueError(f"Multiple namespaces for array inputs: {namespaces}") + + (xp,) = namespaces + if xp is None: + # Use numpy as default + return _NumPyApiWrapper(), False + + return _ArrayAPIWrapper(xp), True + + +def _expit(X): + xp, _ = get_namespace(X) + if xp.__name__ in {"numpy", "numpy.array_api"}: + return xp.asarray(special.expit(numpy.asarray(X))) + + return 1.0 / (1.0 + xp.exp(-X)) + + +def _asarray_with_order(array, dtype=None, order=None, copy=None, xp=None): + """Helper to support the order kwarg only for NumPy-backed arrays + + Memory layout parameter `order` is not exposed in the Array API standard, + however some input validation code in scikit-learn needs to work both + for classes and functions that will leverage Array API only operations + and for code that inherently relies on NumPy backed data containers with + specific memory layout constraints (e.g. our own Cython code). The + purpose of this helper is to make it possible to share code for data + container validation without memory copies for both downstream use cases: + the `order` parameter is only enforced if the input array implementation + is NumPy based, otherwise `order` is just silently ignored. + """ + if xp is None: + xp, _ = get_namespace(array) + if xp.__name__ in {"numpy", "numpy.array_api"}: + # Use NumPy API to support order + array = numpy.asarray(array, order=order, dtype=dtype) + return xp.asarray(array, copy=copy) + else: + return xp.asarray(array, dtype=dtype, copy=copy) + + +def _convert_to_numpy(array, xp): + """Convert X into a NumPy ndarray. + + Only works on cupy.array_api and numpy.array_api and is used for testing. + """ + supported_array_api = ["numpy.array_api", "cupy.array_api"] + if xp.__name__ not in supported_array_api: + support_array_api_str = ", ".join(supported_array_api) + raise ValueError(f"Supported namespaces are: {support_array_api_str}") + + if xp.__name__ == "cupy.array_api": + return array._array.get() + else: + return numpy.asarray(array) + + +def _estimator_with_converted_arrays(estimator, converter): + """Create new estimator which converting all attributes that are arrays. + + Parameters + ---------- + estimator : Estimator + Estimator to convert + + converter : callable + Callable that takes an array attribute and returns the converted array. + + Returns + ------- + new_estimator : Estimator + Convert estimator + """ + from sklearn.base import clone + + new_estimator = clone(estimator) + for key, attribute in vars(estimator).items(): + if hasattr(attribute, "__array_namespace__") or isinstance( + attribute, numpy.ndarray + ): + attribute = converter(attribute) + setattr(new_estimator, key, attribute) + return new_estimator diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_joblib.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/_joblib.py new file mode 100644 index 0000000000000000000000000000000000000000..8cbe084c94992a17c7cec434b7462a60922a248b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_joblib.py @@ -0,0 +1,31 @@ +import warnings as _warnings + +with _warnings.catch_warnings(): + _warnings.simplefilter("ignore") + # joblib imports may raise DeprecationWarning on certain Python + # versions + import joblib + from joblib import logger + from joblib import dump, load + from joblib import __version__ + from joblib import effective_n_jobs + from joblib import hash + from joblib import cpu_count, Parallel, Memory, delayed + from joblib import parallel_backend, register_parallel_backend + + +__all__ = [ + "parallel_backend", + "register_parallel_backend", + "cpu_count", + "Parallel", + "Memory", + "delayed", + "effective_n_jobs", + "hash", + "logger", + "dump", + "load", + "joblib", + "__version__", +] diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_logistic_sigmoid.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/utils/_logistic_sigmoid.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f4731acb20034f5ea15c1ff3ec84805374042bb3 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_logistic_sigmoid.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a289dcf0576538ce83dae8afd304a7eabfae9ac387e1c2603cc0acde379d6c73 +size 187849 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_mask.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..d57cf839d962f04a11d0948acff481caeb50f518 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_mask.py @@ -0,0 +1,62 @@ +import numpy as np +from scipy import sparse as sp +from contextlib import suppress + +from . import is_scalar_nan +from .fixes import _object_dtype_isnan + + +def _get_dense_mask(X, value_to_mask): + with suppress(ImportError, AttributeError): + # We also suppress `AttributeError` because older versions of pandas do + # not have `NA`. + import pandas + + if value_to_mask is pandas.NA: + return pandas.isna(X) + + if is_scalar_nan(value_to_mask): + if X.dtype.kind == "f": + Xt = np.isnan(X) + elif X.dtype.kind in ("i", "u"): + # can't have NaNs in integer array. + Xt = np.zeros(X.shape, dtype=bool) + else: + # np.isnan does not work on object dtypes. + Xt = _object_dtype_isnan(X) + else: + Xt = X == value_to_mask + + return Xt + + +def _get_mask(X, value_to_mask): + """Compute the boolean mask X == value_to_mask. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + Input data, where ``n_samples`` is the number of samples and + ``n_features`` is the number of features. + + value_to_mask : {int, float} + The value which is to be masked in X. + + Returns + ------- + X_mask : {ndarray, sparse matrix} of shape (n_samples, n_features) + Missing mask. + """ + if not sp.issparse(X): + # For all cases apart of a sparse input where we need to reconstruct + # a sparse output + return _get_dense_mask(X, value_to_mask) + + Xt = _get_dense_mask(X.data, value_to_mask) + + sparse_constructor = sp.csr_matrix if X.format == "csr" else sp.csc_matrix + Xt_sparse = sparse_constructor( + (Xt, X.indices.copy(), X.indptr.copy()), shape=X.shape, dtype=bool + ) + + return Xt_sparse diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..65e52fd968997b00a3449b051a0f5123a49bf57d Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.cpython-310-x86_64-linux-gnu.so differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.pxd b/videollama2/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e57fc9bfa6bf588ef0eb4afcb0ef288c976073ab --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.pxd @@ -0,0 +1,6 @@ +# Helpers to access OpenMP threads information +# +# Those interfaces act as indirections which allows the non-support of OpenMP +# for implementations which have been written for it. + +cdef int _openmp_thread_num() nogil diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_param_validation.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/_param_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..0672f0ab17225f23e93ca40ff652dd10d75e22ea --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_param_validation.py @@ -0,0 +1,943 @@ +from abc import ABC +from abc import abstractmethod +from collections.abc import Iterable +import functools +import math +from inspect import signature +from numbers import Integral +from numbers import Real +import operator +import re +import warnings + +import numpy as np +from scipy.sparse import issparse +from scipy.sparse import csr_matrix + +from .validation import _is_arraylike_not_scalar + + +class InvalidParameterError(ValueError, TypeError): + """Custom exception to be raised when the parameter of a class/method/function + does not have a valid type or value. + """ + + # Inherits from ValueError and TypeError to keep backward compatibility. + + +def validate_parameter_constraints(parameter_constraints, params, caller_name): + """Validate types and values of given parameters. + + Parameters + ---------- + parameter_constraints : dict or {"no_validation"} + If "no_validation", validation is skipped for this parameter. + + If a dict, it must be a dictionary `param_name: list of constraints`. + A parameter is valid if it satisfies one of the constraints from the list. + Constraints can be: + - an Interval object, representing a continuous or discrete range of numbers + - the string "array-like" + - the string "sparse matrix" + - the string "random_state" + - callable + - None, meaning that None is a valid value for the parameter + - any type, meaning that any instance of this type is valid + - an Options object, representing a set of elements of a given type + - a StrOptions object, representing a set of strings + - the string "boolean" + - the string "verbose" + - the string "cv_object" + - the string "missing_values" + - a HasMethods object, representing method(s) an object must have + - a Hidden object, representing a constraint not meant to be exposed to the user + + params : dict + A dictionary `param_name: param_value`. The parameters to validate against the + constraints. + + caller_name : str + The name of the estimator or function or method that called this function. + """ + for param_name, param_val in params.items(): + # We allow parameters to not have a constraint so that third party estimators + # can inherit from sklearn estimators without having to necessarily use the + # validation tools. + if param_name not in parameter_constraints: + continue + + constraints = parameter_constraints[param_name] + + if constraints == "no_validation": + continue + + constraints = [make_constraint(constraint) for constraint in constraints] + + for constraint in constraints: + if constraint.is_satisfied_by(param_val): + # this constraint is satisfied, no need to check further. + break + else: + # No constraint is satisfied, raise with an informative message. + + # Ignore constraints that we don't want to expose in the error message, + # i.e. options that are for internal purpose or not officially supported. + constraints = [ + constraint for constraint in constraints if not constraint.hidden + ] + + if len(constraints) == 1: + constraints_str = f"{constraints[0]}" + else: + constraints_str = ( + f"{', '.join([str(c) for c in constraints[:-1]])} or" + f" {constraints[-1]}" + ) + + raise InvalidParameterError( + f"The {param_name!r} parameter of {caller_name} must be" + f" {constraints_str}. Got {param_val!r} instead." + ) + + +def make_constraint(constraint): + """Convert the constraint into the appropriate Constraint object. + + Parameters + ---------- + constraint : object + The constraint to convert. + + Returns + ------- + constraint : instance of _Constraint + The converted constraint. + """ + if isinstance(constraint, str) and constraint == "array-like": + return _ArrayLikes() + if isinstance(constraint, str) and constraint == "sparse matrix": + return _SparseMatrices() + if isinstance(constraint, str) and constraint == "random_state": + return _RandomStates() + if constraint is callable: + return _Callables() + if constraint is None: + return _NoneConstraint() + if isinstance(constraint, type): + return _InstancesOf(constraint) + if isinstance(constraint, (Interval, StrOptions, Options, HasMethods)): + return constraint + if isinstance(constraint, str) and constraint == "boolean": + return _Booleans() + if isinstance(constraint, str) and constraint == "verbose": + return _VerboseHelper() + if isinstance(constraint, str) and constraint == "missing_values": + return _MissingValues() + if isinstance(constraint, str) and constraint == "cv_object": + return _CVObjects() + if isinstance(constraint, Hidden): + constraint = make_constraint(constraint.constraint) + constraint.hidden = True + return constraint + raise ValueError(f"Unknown constraint type: {constraint}") + + +def validate_params(parameter_constraints): + """Decorator to validate types and values of functions and methods. + + Parameters + ---------- + parameter_constraints : dict + A dictionary `param_name: list of constraints`. See the docstring of + `validate_parameter_constraints` for a description of the accepted constraints. + + Note that the *args and **kwargs parameters are not validated and must not be + present in the parameter_constraints dictionary. + + Returns + ------- + decorated_function : function or method + The decorated function. + """ + + def decorator(func): + # The dict of parameter constraints is set as an attribute of the function + # to make it possible to dynamically introspect the constraints for + # automatic testing. + setattr(func, "_skl_parameter_constraints", parameter_constraints) + + @functools.wraps(func) + def wrapper(*args, **kwargs): + + func_sig = signature(func) + + # Map *args/**kwargs to the function signature + params = func_sig.bind(*args, **kwargs) + params.apply_defaults() + + # ignore self/cls and positional/keyword markers + to_ignore = [ + p.name + for p in func_sig.parameters.values() + if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD) + ] + to_ignore += ["self", "cls"] + params = {k: v for k, v in params.arguments.items() if k not in to_ignore} + + validate_parameter_constraints( + parameter_constraints, params, caller_name=func.__qualname__ + ) + + try: + return func(*args, **kwargs) + except InvalidParameterError as e: + # When the function is just a wrapper around an estimator, we allow + # the function to delegate validation to the estimator, but we replace + # the name of the estimator by the name of the function in the error + # message to avoid confusion. + msg = re.sub( + r"parameter of \w+ must be", + f"parameter of {func.__qualname__} must be", + str(e), + ) + raise InvalidParameterError(msg) from e + + return wrapper + + return decorator + + +def _type_name(t): + """Convert type into human readable string.""" + module = t.__module__ + qualname = t.__qualname__ + if module == "builtins": + return qualname + elif t == Real: + return "float" + elif t == Integral: + return "int" + return f"{module}.{qualname}" + + +class _Constraint(ABC): + """Base class for the constraint objects.""" + + def __init__(self): + self.hidden = False + + @abstractmethod + def is_satisfied_by(self, val): + """Whether or not a value satisfies the constraint. + + Parameters + ---------- + val : object + The value to check. + + Returns + ------- + is_satisfied : bool + Whether or not the constraint is satisfied by this value. + """ + + @abstractmethod + def __str__(self): + """A human readable representational string of the constraint.""" + + +class _InstancesOf(_Constraint): + """Constraint representing instances of a given type. + + Parameters + ---------- + type : type + The valid type. + """ + + def __init__(self, type): + super().__init__() + self.type = type + + def is_satisfied_by(self, val): + return isinstance(val, self.type) + + def __str__(self): + return f"an instance of {_type_name(self.type)!r}" + + +class _NoneConstraint(_Constraint): + """Constraint representing the None singleton.""" + + def is_satisfied_by(self, val): + return val is None + + def __str__(self): + return "None" + + +class _NanConstraint(_Constraint): + """Constraint representing the indicator `np.nan`.""" + + def is_satisfied_by(self, val): + return isinstance(val, Real) and math.isnan(val) + + def __str__(self): + return "numpy.nan" + + +class _PandasNAConstraint(_Constraint): + """Constraint representing the indicator `pd.NA`.""" + + def is_satisfied_by(self, val): + try: + import pandas as pd + + return isinstance(val, type(pd.NA)) and pd.isna(val) + except ImportError: + return False + + def __str__(self): + return "pandas.NA" + + +class Options(_Constraint): + """Constraint representing a finite set of instances of a given type. + + Parameters + ---------- + type : type + + options : set + The set of valid scalars. + + deprecated : set or None, default=None + A subset of the `options` to mark as deprecated in the string + representation of the constraint. + """ + + def __init__(self, type, options, *, deprecated=None): + super().__init__() + self.type = type + self.options = options + self.deprecated = deprecated or set() + + if self.deprecated - self.options: + raise ValueError("The deprecated options must be a subset of the options.") + + def is_satisfied_by(self, val): + return isinstance(val, self.type) and val in self.options + + def _mark_if_deprecated(self, option): + """Add a deprecated mark to an option if needed.""" + option_str = f"{option!r}" + if option in self.deprecated: + option_str = f"{option_str} (deprecated)" + return option_str + + def __str__(self): + options_str = ( + f"{', '.join([self._mark_if_deprecated(o) for o in self.options])}" + ) + return f"a {_type_name(self.type)} among {{{options_str}}}" + + +class StrOptions(Options): + """Constraint representing a finite set of strings. + + Parameters + ---------- + options : set of str + The set of valid strings. + + deprecated : set of str or None, default=None + A subset of the `options` to mark as deprecated in the string + representation of the constraint. + """ + + def __init__(self, options, *, deprecated=None): + super().__init__(type=str, options=options, deprecated=deprecated) + + +class Interval(_Constraint): + """Constraint representing a typed interval. + + Parameters + ---------- + type : {numbers.Integral, numbers.Real, "real_not_int"} + The set of numbers in which to set the interval. + + If "real_not_int", only reals that don't have the integer type + are allowed. For example 1.0 is allowed but 1 is not. + + left : float or int or None + The left bound of the interval. None means left bound is -∞. + + right : float, int or None + The right bound of the interval. None means right bound is +∞. + + closed : {"left", "right", "both", "neither"} + Whether the interval is open or closed. Possible choices are: + + - `"left"`: the interval is closed on the left and open on the right. + It is equivalent to the interval `[ left, right )`. + - `"right"`: the interval is closed on the right and open on the left. + It is equivalent to the interval `( left, right ]`. + - `"both"`: the interval is closed. + It is equivalent to the interval `[ left, right ]`. + - `"neither"`: the interval is open. + It is equivalent to the interval `( left, right )`. + + Notes + ----- + Setting a bound to `None` and setting the interval closed is valid. For instance, + strictly speaking, `Interval(Real, 0, None, closed="both")` corresponds to + `[0, +∞) U {+∞}`. + """ + + def __init__(self, type, left, right, *, closed): + super().__init__() + self.type = type + self.left = left + self.right = right + self.closed = closed + + self._check_params() + + def _check_params(self): + if self.type not in (Integral, Real, "real_not_int"): + raise ValueError( + "type must be either numbers.Integral, numbers.Real or 'real_not_int'." + f" Got {self.type} instead." + ) + + if self.closed not in ("left", "right", "both", "neither"): + raise ValueError( + "closed must be either 'left', 'right', 'both' or 'neither'. " + f"Got {self.closed} instead." + ) + + if self.type is Integral: + suffix = "for an interval over the integers." + if self.left is not None and not isinstance(self.left, Integral): + raise TypeError(f"Expecting left to be an int {suffix}") + if self.right is not None and not isinstance(self.right, Integral): + raise TypeError(f"Expecting right to be an int {suffix}") + if self.left is None and self.closed in ("left", "both"): + raise ValueError( + f"left can't be None when closed == {self.closed} {suffix}" + ) + if self.right is None and self.closed in ("right", "both"): + raise ValueError( + f"right can't be None when closed == {self.closed} {suffix}" + ) + else: + if self.left is not None and not isinstance(self.left, Real): + raise TypeError("Expecting left to be a real number.") + if self.right is not None and not isinstance(self.right, Real): + raise TypeError("Expecting right to be a real number.") + + if self.right is not None and self.left is not None and self.right <= self.left: + raise ValueError( + f"right can't be less than left. Got left={self.left} and " + f"right={self.right}" + ) + + def __contains__(self, val): + if np.isnan(val): + return False + + left_cmp = operator.lt if self.closed in ("left", "both") else operator.le + right_cmp = operator.gt if self.closed in ("right", "both") else operator.ge + + left = -np.inf if self.left is None else self.left + right = np.inf if self.right is None else self.right + + if left_cmp(val, left): + return False + if right_cmp(val, right): + return False + return True + + def _has_valid_type(self, val): + if self.type == "real_not_int": + return isinstance(val, Real) and not isinstance(val, Integral) + return isinstance(val, self.type) + + def is_satisfied_by(self, val): + if not self._has_valid_type(val): + return False + + return val in self + + def __str__(self): + type_str = "an int" if self.type is Integral else "a float" + left_bracket = "[" if self.closed in ("left", "both") else "(" + left_bound = "-inf" if self.left is None else self.left + right_bound = "inf" if self.right is None else self.right + right_bracket = "]" if self.closed in ("right", "both") else ")" + return ( + f"{type_str} in the range " + f"{left_bracket}{left_bound}, {right_bound}{right_bracket}" + ) + + +class _ArrayLikes(_Constraint): + """Constraint representing array-likes""" + + def is_satisfied_by(self, val): + return _is_arraylike_not_scalar(val) + + def __str__(self): + return "an array-like" + + +class _SparseMatrices(_Constraint): + """Constraint representing sparse matrices.""" + + def is_satisfied_by(self, val): + return issparse(val) + + def __str__(self): + return "a sparse matrix" + + +class _Callables(_Constraint): + """Constraint representing callables.""" + + def is_satisfied_by(self, val): + return callable(val) + + def __str__(self): + return "a callable" + + +class _RandomStates(_Constraint): + """Constraint representing random states. + + Convenience class for + [Interval(Integral, 0, 2**32 - 1, closed="both"), np.random.RandomState, None] + """ + + def __init__(self): + super().__init__() + self._constraints = [ + Interval(Integral, 0, 2**32 - 1, closed="both"), + _InstancesOf(np.random.RandomState), + _NoneConstraint(), + ] + + def is_satisfied_by(self, val): + return any(c.is_satisfied_by(val) for c in self._constraints) + + def __str__(self): + return ( + f"{', '.join([str(c) for c in self._constraints[:-1]])} or" + f" {self._constraints[-1]}" + ) + + +class _Booleans(_Constraint): + """Constraint representing boolean likes. + + Convenience class for + [bool, np.bool_, Integral (deprecated)] + """ + + def __init__(self): + super().__init__() + self._constraints = [ + _InstancesOf(bool), + _InstancesOf(np.bool_), + _InstancesOf(Integral), + ] + + def is_satisfied_by(self, val): + # TODO(1.4) remove support for Integral. + if isinstance(val, Integral) and not isinstance(val, bool): + warnings.warn( + "Passing an int for a boolean parameter is deprecated in version 1.2 " + "and won't be supported anymore in version 1.4.", + FutureWarning, + ) + + return any(c.is_satisfied_by(val) for c in self._constraints) + + def __str__(self): + return ( + f"{', '.join([str(c) for c in self._constraints[:-1]])} or" + f" {self._constraints[-1]}" + ) + + +class _VerboseHelper(_Constraint): + """Helper constraint for the verbose parameter. + + Convenience class for + [Interval(Integral, 0, None, closed="left"), bool, numpy.bool_] + """ + + def __init__(self): + super().__init__() + self._constraints = [ + Interval(Integral, 0, None, closed="left"), + _InstancesOf(bool), + _InstancesOf(np.bool_), + ] + + def is_satisfied_by(self, val): + return any(c.is_satisfied_by(val) for c in self._constraints) + + def __str__(self): + return ( + f"{', '.join([str(c) for c in self._constraints[:-1]])} or" + f" {self._constraints[-1]}" + ) + + +class _MissingValues(_Constraint): + """Helper constraint for the `missing_values` parameters. + + Convenience for + [ + Integral, + Interval(Real, None, None, closed="both"), + str, + None, + _NanConstraint(), + _PandasNAConstraint(), + ] + """ + + def __init__(self): + super().__init__() + self._constraints = [ + _InstancesOf(Integral), + # we use an interval of Real to ignore np.nan that has its own constraint + Interval(Real, None, None, closed="both"), + _InstancesOf(str), + _NoneConstraint(), + _NanConstraint(), + _PandasNAConstraint(), + ] + + def is_satisfied_by(self, val): + return any(c.is_satisfied_by(val) for c in self._constraints) + + def __str__(self): + return ( + f"{', '.join([str(c) for c in self._constraints[:-1]])} or" + f" {self._constraints[-1]}" + ) + + +class HasMethods(_Constraint): + """Constraint representing objects that expose specific methods. + + It is useful for parameters following a protocol and where we don't want to impose + an affiliation to a specific module or class. + + Parameters + ---------- + methods : str or list of str + The method(s) that the object is expected to expose. + """ + + @validate_params({"methods": [str, list]}) + def __init__(self, methods): + super().__init__() + if isinstance(methods, str): + methods = [methods] + self.methods = methods + + def is_satisfied_by(self, val): + return all(callable(getattr(val, method, None)) for method in self.methods) + + def __str__(self): + if len(self.methods) == 1: + methods = f"{self.methods[0]!r}" + else: + methods = ( + f"{', '.join([repr(m) for m in self.methods[:-1]])} and" + f" {self.methods[-1]!r}" + ) + return f"an object implementing {methods}" + + +class _IterablesNotString(_Constraint): + """Constraint representing iterables that are not strings.""" + + def is_satisfied_by(self, val): + return isinstance(val, Iterable) and not isinstance(val, str) + + def __str__(self): + return "an iterable" + + +class _CVObjects(_Constraint): + """Constraint representing cv objects. + + Convenient class for + [ + Interval(Integral, 2, None, closed="left"), + HasMethods(["split", "get_n_splits"]), + _IterablesNotString(), + None, + ] + """ + + def __init__(self): + super().__init__() + self._constraints = [ + Interval(Integral, 2, None, closed="left"), + HasMethods(["split", "get_n_splits"]), + _IterablesNotString(), + _NoneConstraint(), + ] + + def is_satisfied_by(self, val): + return any(c.is_satisfied_by(val) for c in self._constraints) + + def __str__(self): + return ( + f"{', '.join([str(c) for c in self._constraints[:-1]])} or" + f" {self._constraints[-1]}" + ) + + +class Hidden: + """Class encapsulating a constraint not meant to be exposed to the user. + + Parameters + ---------- + constraint : str or _Constraint instance + The constraint to be used internally. + """ + + def __init__(self, constraint): + self.constraint = constraint + + +def generate_invalid_param_val(constraint, constraints=None): + """Return a value that does not satisfy the constraint. + + Raises a NotImplementedError if there exists no invalid value for this constraint. + + This is only useful for testing purpose. + + Parameters + ---------- + constraint : _Constraint instance + The constraint to generate a value for. + + constraints : list of _Constraint instances or None, default=None + The list of all constraints for this parameter. If None, the list only + containing `constraint` is used. + + Returns + ------- + val : object + A value that does not satisfy the constraint. + """ + if isinstance(constraint, StrOptions): + return f"not {' or '.join(constraint.options)}" + + if isinstance(constraint, _MissingValues): + return np.array([1, 2, 3]) + + if isinstance(constraint, _VerboseHelper): + return -1 + + if isinstance(constraint, HasMethods): + return type("HasNotMethods", (), {})() + + if isinstance(constraint, _IterablesNotString): + return "a string" + + if isinstance(constraint, _CVObjects): + return "not a cv object" + + if not isinstance(constraint, Interval): + raise NotImplementedError + + # constraint is an interval + constraints = [constraint] if constraints is None else constraints + return _generate_invalid_param_val_interval(constraint, constraints) + + +def _generate_invalid_param_val_interval(interval, constraints): + """Return a value that does not satisfy an interval constraint. + + Generating an invalid value for an integer interval depends on the other constraints + since an int is a real, meaning that it can be valid for a real interval. + Assumes that there can be at most 2 interval constraints: one integer interval + and/or one real interval. + + This is only useful for testing purpose. + + Parameters + ---------- + interval : Interval instance + The interval to generate a value for. + + constraints : list of _Constraint instances + The list of all constraints for this parameter. + + Returns + ------- + val : object + A value that does not satisfy the interval constraint. + """ + if interval.type is Real: + # generate a non-integer value such that it can't be valid even if there's also + # an integer interval constraint. + if interval.left is None and interval.right is None: + if interval.closed in ("left", "neither"): + return np.inf + elif interval.closed in ("right", "neither"): + return -np.inf + else: + raise NotImplementedError + + if interval.left is not None: + return np.floor(interval.left) - 0.5 + else: # right is not None + return np.ceil(interval.right) + 0.5 + + else: # interval.type is Integral + if interval.left is None and interval.right is None: + raise NotImplementedError + + # We need to check if there's also a real interval constraint to generate a + # value that is not valid for any of the 2 interval constraints. + real_intervals = [ + i for i in constraints if isinstance(i, Interval) and i.type is Real + ] + real_interval = real_intervals[0] if real_intervals else None + + if real_interval is None: + # Only the integer interval constraint -> easy + if interval.left is not None: + return interval.left - 1 + else: # interval.right is not None + return interval.right + 1 + + # There's also a real interval constraint. Try to find a value left to both or + # right to both or in between them. + + # redefine left and right bounds to be smallest and largest valid integers in + # both intervals. + int_left = interval.left + if int_left is not None and interval.closed in ("right", "neither"): + int_left = int_left + 1 + + int_right = interval.right + if int_right is not None and interval.closed in ("left", "neither"): + int_right = int_right - 1 + + real_left = real_interval.left + if real_interval.left is not None: + real_left = int(np.ceil(real_interval.left)) + if real_interval.closed in ("right", "neither"): + real_left = real_left + 1 + + real_right = real_interval.right + if real_interval.right is not None: + real_right = int(np.floor(real_interval.right)) + if real_interval.closed in ("left", "neither"): + real_right = real_right - 1 + + if int_left is not None and real_left is not None: + # there exists an int left to both intervals + return min(int_left, real_left) - 1 + + if int_right is not None and real_right is not None: + # there exists an int right to both intervals + return max(int_right, real_right) + 1 + + if int_left is not None: + if real_right is not None and int_left - real_right >= 2: + # there exists an int between the 2 intervals + return int_left - 1 + else: + raise NotImplementedError + else: # int_right is not None + if real_left is not None and real_left - int_right >= 2: + # there exists an int between the 2 intervals + return int_right + 1 + else: + raise NotImplementedError + + +def generate_valid_param(constraint): + """Return a value that does satisfy a constraint. + + This is only useful for testing purpose. + + Parameters + ---------- + constraint : Constraint instance + The constraint to generate a value for. + + Returns + ------- + val : object + A value that does satisfy the constraint. + """ + if isinstance(constraint, _ArrayLikes): + return np.array([1, 2, 3]) + + if isinstance(constraint, _SparseMatrices): + return csr_matrix([[0, 1], [1, 0]]) + + if isinstance(constraint, _RandomStates): + return np.random.RandomState(42) + + if isinstance(constraint, _Callables): + return lambda x: x + + if isinstance(constraint, _NoneConstraint): + return None + + if isinstance(constraint, _InstancesOf): + return constraint.type() + + if isinstance(constraint, _Booleans): + return True + + if isinstance(constraint, _VerboseHelper): + return 1 + + if isinstance(constraint, _MissingValues): + return np.nan + + if isinstance(constraint, HasMethods): + return type( + "ValidHasMethods", (), {m: lambda self: None for m in constraint.methods} + )() + + if isinstance(constraint, _IterablesNotString): + return [1, 2, 3] + + if isinstance(constraint, _CVObjects): + return 5 + + if isinstance(constraint, Options): # includes StrOptions + for option in constraint.options: + return option + + if isinstance(constraint, Interval): + interval = constraint + if interval.left is None and interval.right is None: + return 0 + elif interval.left is None: + return interval.right - 1 + elif interval.right is None: + return interval.left + 1 + else: + if interval.type is Real: + return (interval.left + interval.right) / 2 + else: + return interval.left + 1 + + raise ValueError(f"Unknown constraint type: {constraint}") diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_random.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/utils/_random.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..8fb597a5f3bc93474df4ac134a2461dbf5d6da96 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_random.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9c4f5f42a71d5792e4b1f8abd4f21f4bec97f97760346667faa773f35b1070a +size 109121 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_readonly_array_wrapper.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/utils/_readonly_array_wrapper.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..c85a2f761bb2322a1e344bb3fb2ac7b4e8001775 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_readonly_array_wrapper.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:de92483727ba785a6a37bf6d157763cf5e743f632437bcbf25d8a5d81448a8f4 +size 237217 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..448c1091ab77d31099297b50c596171eaf0458de --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:41af9dbb90669834261523880b5bbb692b99d301148fa010b3eed979e8c99303 +size 158369 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_show_versions.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/_show_versions.py new file mode 100644 index 0000000000000000000000000000000000000000..066c7fc1bd6763bb882babc9892d4aa90550d04b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_show_versions.py @@ -0,0 +1,108 @@ +""" +Utility methods to print system info for debugging + +adapted from :func:`pandas.show_versions` +""" +# License: BSD 3 clause + +import platform +import sys +from ..utils.fixes import threadpool_info +from .. import __version__ + + +from ._openmp_helpers import _openmp_parallelism_enabled + + +def _get_sys_info(): + """System information + + Returns + ------- + sys_info : dict + system and Python version information + + """ + python = sys.version.replace("\n", " ") + + blob = [ + ("python", python), + ("executable", sys.executable), + ("machine", platform.platform()), + ] + + return dict(blob) + + +def _get_deps_info(): + """Overview of the installed version of main dependencies + + This function does not import the modules to collect the version numbers + but instead relies on standard Python package metadata. + + Returns + ------- + deps_info: dict + version information on relevant Python libraries + + """ + deps = [ + "pip", + "setuptools", + "numpy", + "scipy", + "Cython", + "pandas", + "matplotlib", + "joblib", + "threadpoolctl", + ] + + deps_info = { + "sklearn": __version__, + } + + from importlib.metadata import version, PackageNotFoundError + + for modname in deps: + try: + deps_info[modname] = version(modname) + except PackageNotFoundError: + deps_info[modname] = None + return deps_info + + +def show_versions(): + """Print useful debugging information" + + .. versionadded:: 0.20 + """ + + sys_info = _get_sys_info() + deps_info = _get_deps_info() + + print("\nSystem:") + for k, stat in sys_info.items(): + print("{k:>10}: {stat}".format(k=k, stat=stat)) + + print("\nPython dependencies:") + for k, stat in deps_info.items(): + print("{k:>13}: {stat}".format(k=k, stat=stat)) + + print( + "\n{k}: {stat}".format( + k="Built with OpenMP", stat=_openmp_parallelism_enabled() + ) + ) + + # show threadpoolctl results + threadpool_results = threadpool_info() + if threadpool_results: + print() + print("threadpoolctl info:") + + for i, result in enumerate(threadpool_results): + for key, val in result.items(): + print(f"{key:>15}: {val}") + if i != len(threadpool_results) - 1: + print() diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_sorting.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/utils/_sorting.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d9a54f3a712d33a703f231800e543a013665a7b8 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/utils/_sorting.cpython-310-x86_64-linux-gnu.so differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_tags.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/_tags.py new file mode 100644 index 0000000000000000000000000000000000000000..a275c5dd1aa84d2403dfa69e649b84934cc1c1c4 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_tags.py @@ -0,0 +1,67 @@ +import numpy as np + +_DEFAULT_TAGS = { + "non_deterministic": False, + "requires_positive_X": False, + "requires_positive_y": False, + "X_types": ["2darray"], + "poor_score": False, + "no_validation": False, + "multioutput": False, + "allow_nan": False, + "stateless": False, + "multilabel": False, + "_skip_test": False, + "_xfail_checks": False, + "multioutput_only": False, + "binary_only": False, + "requires_fit": True, + "preserves_dtype": [np.float64], + "requires_y": False, + "pairwise": False, +} + + +def _safe_tags(estimator, key=None): + """Safely get estimator tags. + + :class:`~sklearn.BaseEstimator` provides the estimator tags machinery. + However, if an estimator does not inherit from this base class, we should + fall-back to the default tags. + + For scikit-learn built-in estimators, we should still rely on + `self._get_tags()`. `_safe_tags(est)` should be used when we are not sure + where `est` comes from: typically `_safe_tags(self.base_estimator)` where + `self` is a meta-estimator, or in the common checks. + + Parameters + ---------- + estimator : estimator object + The estimator from which to get the tag. + + key : str, default=None + Tag name to get. By default (`None`), all tags are returned. + + Returns + ------- + tags : dict or tag value + The estimator tags. A single value is returned if `key` is not None. + """ + if hasattr(estimator, "_get_tags"): + tags_provider = "_get_tags()" + tags = estimator._get_tags() + elif hasattr(estimator, "_more_tags"): + tags_provider = "_more_tags()" + tags = {**_DEFAULT_TAGS, **estimator._more_tags()} + else: + tags_provider = "_DEFAULT_TAGS" + tags = _DEFAULT_TAGS + + if key is not None: + if key not in tags: + raise ValueError( + f"The key {key} is not defined in {tags_provider} for the " + f"class {estimator.__class__.__name__}." + ) + return tags[key] + return tags diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_testing.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/_testing.py new file mode 100644 index 0000000000000000000000000000000000000000..482d3ea8185634ee22d3e01d4641d8de60b6b59e --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_testing.py @@ -0,0 +1,1057 @@ +"""Testing utilities.""" + +# Copyright (c) 2011, 2012 +# Authors: Pietro Berkes, +# Andreas Muller +# Mathieu Blondel +# Olivier Grisel +# Arnaud Joly +# Denis Engemann +# Giorgio Patrini +# Thierry Guillemot +# License: BSD 3 clause +import os +import os.path as op +import inspect +import warnings +import sys +import functools +import tempfile +from subprocess import check_output, STDOUT, CalledProcessError +from subprocess import TimeoutExpired +import re +import contextlib +from collections.abc import Iterable +from collections.abc import Sequence + +import scipy as sp +from functools import wraps +from inspect import signature + +import shutil +import atexit +import unittest +from unittest import TestCase + +# WindowsError only exist on Windows +try: + WindowsError # type: ignore +except NameError: + WindowsError = None + +from numpy.testing import assert_allclose as np_assert_allclose +from numpy.testing import assert_almost_equal +from numpy.testing import assert_approx_equal +from numpy.testing import assert_array_equal +from numpy.testing import assert_array_almost_equal +from numpy.testing import assert_array_less +import numpy as np +import joblib + +import sklearn +from sklearn.utils import ( + IS_PYPY, + _IS_32BIT, + _in_unstable_openblas_configuration, +) +from sklearn.utils.multiclass import check_classification_targets +from sklearn.utils.validation import ( + check_array, + check_is_fitted, + check_X_y, +) +from sklearn.utils.fixes import threadpool_info + + +__all__ = [ + "assert_raises", + "assert_raises_regexp", + "assert_array_equal", + "assert_almost_equal", + "assert_array_almost_equal", + "assert_array_less", + "assert_approx_equal", + "assert_allclose", + "assert_run_python_script", + "SkipTest", +] + +_dummy = TestCase("__init__") +assert_raises = _dummy.assertRaises +SkipTest = unittest.case.SkipTest +assert_dict_equal = _dummy.assertDictEqual + +assert_raises_regex = _dummy.assertRaisesRegex +# assert_raises_regexp is deprecated in Python 3.4 in favor of +# assert_raises_regex but lets keep the backward compat in scikit-learn with +# the old name for now +assert_raises_regexp = assert_raises_regex + + +# To remove when we support numpy 1.7 +def assert_no_warnings(func, *args, **kw): + """ + Parameters + ---------- + func + *args + **kw + """ + # very important to avoid uncontrolled state propagation + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + + result = func(*args, **kw) + if hasattr(np, "FutureWarning"): + # Filter out numpy-specific warnings in numpy >= 1.9 + w = [e for e in w if e.category is not np.VisibleDeprecationWarning] + + if len(w) > 0: + raise AssertionError( + "Got warnings when calling %s: [%s]" + % (func.__name__, ", ".join(str(warning) for warning in w)) + ) + return result + + +def ignore_warnings(obj=None, category=Warning): + """Context manager and decorator to ignore warnings. + + Note: Using this (in both variants) will clear all warnings + from all python modules loaded. In case you need to test + cross-module-warning-logging, this is not your tool of choice. + + Parameters + ---------- + obj : callable, default=None + callable where you want to ignore the warnings. + category : warning class, default=Warning + The category to filter. If Warning, all categories will be muted. + + Examples + -------- + >>> import warnings + >>> from sklearn.utils._testing import ignore_warnings + >>> with ignore_warnings(): + ... warnings.warn('buhuhuhu') + + >>> def nasty_warn(): + ... warnings.warn('buhuhuhu') + ... print(42) + + >>> ignore_warnings(nasty_warn)() + 42 + """ + if isinstance(obj, type) and issubclass(obj, Warning): + # Avoid common pitfall of passing category as the first positional + # argument which result in the test not being run + warning_name = obj.__name__ + raise ValueError( + "'obj' should be a callable where you want to ignore warnings. " + "You passed a warning class instead: 'obj={warning_name}'. " + "If you want to pass a warning class to ignore_warnings, " + "you should use 'category={warning_name}'".format(warning_name=warning_name) + ) + elif callable(obj): + return _IgnoreWarnings(category=category)(obj) + else: + return _IgnoreWarnings(category=category) + + +class _IgnoreWarnings: + """Improved and simplified Python warnings context manager and decorator. + + This class allows the user to ignore the warnings raised by a function. + Copied from Python 2.7.5 and modified as required. + + Parameters + ---------- + category : tuple of warning class, default=Warning + The category to filter. By default, all the categories will be muted. + + """ + + def __init__(self, category): + self._record = True + self._module = sys.modules["warnings"] + self._entered = False + self.log = [] + self.category = category + + def __call__(self, fn): + """Decorator to catch and hide warnings without visual nesting.""" + + @wraps(fn) + def wrapper(*args, **kwargs): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", self.category) + return fn(*args, **kwargs) + + return wrapper + + def __repr__(self): + args = [] + if self._record: + args.append("record=True") + if self._module is not sys.modules["warnings"]: + args.append("module=%r" % self._module) + name = type(self).__name__ + return "%s(%s)" % (name, ", ".join(args)) + + def __enter__(self): + if self._entered: + raise RuntimeError("Cannot enter %r twice" % self) + self._entered = True + self._filters = self._module.filters + self._module.filters = self._filters[:] + self._showwarning = self._module.showwarning + warnings.simplefilter("ignore", self.category) + + def __exit__(self, *exc_info): + if not self._entered: + raise RuntimeError("Cannot exit %r without entering first" % self) + self._module.filters = self._filters + self._module.showwarning = self._showwarning + self.log[:] = [] + + +def assert_raise_message(exceptions, message, function, *args, **kwargs): + """Helper function to test the message raised in an exception. + + Given an exception, a callable to raise the exception, and + a message string, tests that the correct exception is raised and + that the message is a substring of the error thrown. Used to test + that the specific message thrown during an exception is correct. + + Parameters + ---------- + exceptions : exception or tuple of exception + An Exception object. + + message : str + The error message or a substring of the error message. + + function : callable + Callable object to raise error. + + *args : the positional arguments to `function`. + + **kwargs : the keyword arguments to `function`. + """ + try: + function(*args, **kwargs) + except exceptions as e: + error_message = str(e) + if message not in error_message: + raise AssertionError( + "Error message does not include the expected" + " string: %r. Observed error message: %r" % (message, error_message) + ) + else: + # concatenate exception names + if isinstance(exceptions, tuple): + names = " or ".join(e.__name__ for e in exceptions) + else: + names = exceptions.__name__ + + raise AssertionError("%s not raised by %s" % (names, function.__name__)) + + +def assert_allclose( + actual, desired, rtol=None, atol=0.0, equal_nan=True, err_msg="", verbose=True +): + """dtype-aware variant of numpy.testing.assert_allclose + + This variant introspects the least precise floating point dtype + in the input argument and automatically sets the relative tolerance + parameter to 1e-4 float32 and use 1e-7 otherwise (typically float64 + in scikit-learn). + + `atol` is always left to 0. by default. It should be adjusted manually + to an assertion-specific value in case there are null values expected + in `desired`. + + The aggregate tolerance is `atol + rtol * abs(desired)`. + + Parameters + ---------- + actual : array_like + Array obtained. + desired : array_like + Array desired. + rtol : float, optional, default=None + Relative tolerance. + If None, it is set based on the provided arrays' dtypes. + atol : float, optional, default=0. + Absolute tolerance. + equal_nan : bool, optional, default=True + If True, NaNs will compare equal. + err_msg : str, optional, default='' + The error message to be printed in case of failure. + verbose : bool, optional, default=True + If True, the conflicting values are appended to the error message. + + Raises + ------ + AssertionError + If actual and desired are not equal up to specified precision. + + See Also + -------- + numpy.testing.assert_allclose + + Examples + -------- + >>> import numpy as np + >>> from sklearn.utils._testing import assert_allclose + >>> x = [1e-5, 1e-3, 1e-1] + >>> y = np.arccos(np.cos(x)) + >>> assert_allclose(x, y, rtol=1e-5, atol=0) + >>> a = np.full(shape=10, fill_value=1e-5, dtype=np.float32) + >>> assert_allclose(a, 1e-5) + """ + dtypes = [] + + actual, desired = np.asanyarray(actual), np.asanyarray(desired) + dtypes = [actual.dtype, desired.dtype] + + if rtol is None: + rtols = [1e-4 if dtype == np.float32 else 1e-7 for dtype in dtypes] + rtol = max(rtols) + + np_assert_allclose( + actual, + desired, + rtol=rtol, + atol=atol, + equal_nan=equal_nan, + err_msg=err_msg, + verbose=verbose, + ) + + +def assert_allclose_dense_sparse(x, y, rtol=1e-07, atol=1e-9, err_msg=""): + """Assert allclose for sparse and dense data. + + Both x and y need to be either sparse or dense, they + can't be mixed. + + Parameters + ---------- + x : {array-like, sparse matrix} + First array to compare. + + y : {array-like, sparse matrix} + Second array to compare. + + rtol : float, default=1e-07 + relative tolerance; see numpy.allclose. + + atol : float, default=1e-9 + absolute tolerance; see numpy.allclose. Note that the default here is + more tolerant than the default for numpy.testing.assert_allclose, where + atol=0. + + err_msg : str, default='' + Error message to raise. + """ + if sp.sparse.issparse(x) and sp.sparse.issparse(y): + x = x.tocsr() + y = y.tocsr() + x.sum_duplicates() + y.sum_duplicates() + assert_array_equal(x.indices, y.indices, err_msg=err_msg) + assert_array_equal(x.indptr, y.indptr, err_msg=err_msg) + assert_allclose(x.data, y.data, rtol=rtol, atol=atol, err_msg=err_msg) + elif not sp.sparse.issparse(x) and not sp.sparse.issparse(y): + # both dense + assert_allclose(x, y, rtol=rtol, atol=atol, err_msg=err_msg) + else: + raise ValueError( + "Can only compare two sparse matrices, not a sparse matrix and an array." + ) + + +def set_random_state(estimator, random_state=0): + """Set random state of an estimator if it has the `random_state` param. + + Parameters + ---------- + estimator : object + The estimator. + random_state : int, RandomState instance or None, default=0 + Pseudo random number generator state. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + """ + if "random_state" in estimator.get_params(): + estimator.set_params(random_state=random_state) + + +try: + import pytest + + skip_if_32bit = pytest.mark.skipif(_IS_32BIT, reason="skipped on 32bit platforms") + fails_if_pypy = pytest.mark.xfail(IS_PYPY, reason="not compatible with PyPy") + fails_if_unstable_openblas = pytest.mark.xfail( + _in_unstable_openblas_configuration(), + reason="OpenBLAS is unstable for this configuration", + ) + skip_if_no_parallel = pytest.mark.skipif( + not joblib.parallel.mp, reason="joblib is in serial mode" + ) + + # Decorator for tests involving both BLAS calls and multiprocessing. + # + # Under POSIX (e.g. Linux or OSX), using multiprocessing in conjunction + # with some implementation of BLAS (or other libraries that manage an + # internal posix thread pool) can cause a crash or a freeze of the Python + # process. + # + # In practice all known packaged distributions (from Linux distros or + # Anaconda) of BLAS under Linux seems to be safe. So we this problem seems + # to only impact OSX users. + # + # This wrapper makes it possible to skip tests that can possibly cause + # this crash under OS X with. + # + # Under Python 3.4+ it is possible to use the `forkserver` start method + # for multiprocessing to avoid this issue. However it can cause pickling + # errors on interactively defined functions. It therefore not enabled by + # default. + + if_safe_multiprocessing_with_blas = pytest.mark.skipif( + sys.platform == "darwin", reason="Possible multi-process bug with some BLAS" + ) +except ImportError: + pass + + +def check_skip_network(): + if int(os.environ.get("SKLEARN_SKIP_NETWORK_TESTS", 0)): + raise SkipTest("Text tutorial requires large dataset download") + + +def _delete_folder(folder_path, warn=False): + """Utility function to cleanup a temporary folder if still existing. + + Copy from joblib.pool (for independence). + """ + try: + if os.path.exists(folder_path): + # This can fail under windows, + # but will succeed when called by atexit + shutil.rmtree(folder_path) + except WindowsError: + if warn: + warnings.warn("Could not delete temporary folder %s" % folder_path) + + +class TempMemmap: + """ + Parameters + ---------- + data + mmap_mode : str, default='r' + """ + + def __init__(self, data, mmap_mode="r"): + self.mmap_mode = mmap_mode + self.data = data + + def __enter__(self): + data_read_only, self.temp_folder = create_memmap_backed_data( + self.data, mmap_mode=self.mmap_mode, return_folder=True + ) + return data_read_only + + def __exit__(self, exc_type, exc_val, exc_tb): + _delete_folder(self.temp_folder) + + +def _create_memmap_backed_array(array, filename, mmap_mode): + # https://numpy.org/doc/stable/reference/generated/numpy.memmap.html + fp = np.memmap(filename, dtype=array.dtype, mode="w+", shape=array.shape) + fp[:] = array[:] # write array to memmap array + fp.flush() + memmap_backed_array = np.memmap( + filename, dtype=array.dtype, mode=mmap_mode, shape=array.shape + ) + return memmap_backed_array + + +def _create_aligned_memmap_backed_arrays(data, mmap_mode, folder): + if isinstance(data, np.ndarray): + filename = op.join(folder, "data.dat") + return _create_memmap_backed_array(data, filename, mmap_mode) + + if isinstance(data, Sequence) and all( + isinstance(each, np.ndarray) for each in data + ): + return [ + _create_memmap_backed_array( + array, op.join(folder, f"data{index}.dat"), mmap_mode + ) + for index, array in enumerate(data) + ] + + raise ValueError( + "When creating aligned memmap-backed arrays, input must be a single array or a" + " sequence of arrays" + ) + + +def create_memmap_backed_data(data, mmap_mode="r", return_folder=False, aligned=False): + """ + Parameters + ---------- + data + mmap_mode : str, default='r' + return_folder : bool, default=False + aligned : bool, default=False + If True, if input is a single numpy array and if the input array is aligned, + the memory mapped array will also be aligned. This is a workaround for + https://github.com/joblib/joblib/issues/563. + """ + temp_folder = tempfile.mkdtemp(prefix="sklearn_testing_") + atexit.register(functools.partial(_delete_folder, temp_folder, warn=True)) + # OpenBLAS is known to segfault with unaligned data on the Prescott + # architecture so force aligned=True on Prescott. For more details, see: + # https://github.com/scipy/scipy/issues/14886 + has_prescott_openblas = any( + True + for info in threadpool_info() + if info["internal_api"] == "openblas" + # Prudently assume Prescott might be the architecture if it is unknown. + and info.get("architecture", "prescott").lower() == "prescott" + ) + if has_prescott_openblas: + aligned = True + + if aligned: + memmap_backed_data = _create_aligned_memmap_backed_arrays( + data, mmap_mode, temp_folder + ) + else: + filename = op.join(temp_folder, "data.pkl") + joblib.dump(data, filename) + memmap_backed_data = joblib.load(filename, mmap_mode=mmap_mode) + result = ( + memmap_backed_data if not return_folder else (memmap_backed_data, temp_folder) + ) + return result + + +# Utils to test docstrings + + +def _get_args(function, varargs=False): + """Helper to get function arguments.""" + + try: + params = signature(function).parameters + except ValueError: + # Error on builtin C function + return [] + args = [ + key + for key, param in params.items() + if param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD) + ] + if varargs: + varargs = [ + param.name + for param in params.values() + if param.kind == param.VAR_POSITIONAL + ] + if len(varargs) == 0: + varargs = None + return args, varargs + else: + return args + + +def _get_func_name(func): + """Get function full name. + + Parameters + ---------- + func : callable + The function object. + + Returns + ------- + name : str + The function name. + """ + parts = [] + module = inspect.getmodule(func) + if module: + parts.append(module.__name__) + + qualname = func.__qualname__ + if qualname != func.__name__: + parts.append(qualname[: qualname.find(".")]) + + parts.append(func.__name__) + return ".".join(parts) + + +def check_docstring_parameters(func, doc=None, ignore=None): + """Helper to check docstring. + + Parameters + ---------- + func : callable + The function object to test. + doc : str, default=None + Docstring if it is passed manually to the test. + ignore : list, default=None + Parameters to ignore. + + Returns + ------- + incorrect : list + A list of string describing the incorrect results. + """ + from numpydoc import docscrape + + incorrect = [] + ignore = [] if ignore is None else ignore + + func_name = _get_func_name(func) + if not func_name.startswith("sklearn.") or func_name.startswith( + "sklearn.externals" + ): + return incorrect + # Don't check docstring for property-functions + if inspect.isdatadescriptor(func): + return incorrect + # Don't check docstring for setup / teardown pytest functions + if func_name.split(".")[-1] in ("setup_module", "teardown_module"): + return incorrect + # Dont check estimator_checks module + if func_name.split(".")[2] == "estimator_checks": + return incorrect + # Get the arguments from the function signature + param_signature = list(filter(lambda x: x not in ignore, _get_args(func))) + # drop self + if len(param_signature) > 0 and param_signature[0] == "self": + param_signature.remove("self") + + # Analyze function's docstring + if doc is None: + records = [] + with warnings.catch_warnings(record=True): + warnings.simplefilter("error", UserWarning) + try: + doc = docscrape.FunctionDoc(func) + except UserWarning as exp: + if "potentially wrong underline length" in str(exp): + # Catch warning raised as of numpydoc 1.2 when + # the underline length for a section of a docstring + # is not consistent. + message = str(exp).split("\n")[:3] + incorrect += [f"In function: {func_name}"] + message + return incorrect + records.append(str(exp)) + except Exception as exp: + incorrect += [func_name + " parsing error: " + str(exp)] + return incorrect + if len(records): + raise RuntimeError("Error for %s:\n%s" % (func_name, records[0])) + + param_docs = [] + for name, type_definition, param_doc in doc["Parameters"]: + # Type hints are empty only if parameter name ended with : + if not type_definition.strip(): + if ":" in name and name[: name.index(":")][-1:].strip(): + incorrect += [ + func_name + + " There was no space between the param name and colon (%r)" % name + ] + elif name.rstrip().endswith(":"): + incorrect += [ + func_name + + " Parameter %r has an empty type spec. Remove the colon" + % (name.lstrip()) + ] + + # Create a list of parameters to compare with the parameters gotten + # from the func signature + if "*" not in name: + param_docs.append(name.split(":")[0].strip("` ")) + + # If one of the docstring's parameters had an error then return that + # incorrect message + if len(incorrect) > 0: + return incorrect + + # Remove the parameters that should be ignored from list + param_docs = list(filter(lambda x: x not in ignore, param_docs)) + + # The following is derived from pytest, Copyright (c) 2004-2017 Holger + # Krekel and others, Licensed under MIT License. See + # https://github.com/pytest-dev/pytest + + message = [] + for i in range(min(len(param_docs), len(param_signature))): + if param_signature[i] != param_docs[i]: + message += [ + "There's a parameter name mismatch in function" + " docstring w.r.t. function signature, at index %s" + " diff: %r != %r" % (i, param_signature[i], param_docs[i]) + ] + break + if len(param_signature) > len(param_docs): + message += [ + "Parameters in function docstring have less items w.r.t." + " function signature, first missing item: %s" + % param_signature[len(param_docs)] + ] + + elif len(param_signature) < len(param_docs): + message += [ + "Parameters in function docstring have more items w.r.t." + " function signature, first extra item: %s" + % param_docs[len(param_signature)] + ] + + # If there wasn't any difference in the parameters themselves between + # docstring and signature including having the same length then return + # empty list + if len(message) == 0: + return [] + + import difflib + import pprint + + param_docs_formatted = pprint.pformat(param_docs).splitlines() + param_signature_formatted = pprint.pformat(param_signature).splitlines() + + message += ["Full diff:"] + + message.extend( + line.strip() + for line in difflib.ndiff(param_signature_formatted, param_docs_formatted) + ) + + incorrect.extend(message) + + # Prepend function name + incorrect = ["In function: " + func_name] + incorrect + + return incorrect + + +def assert_run_python_script(source_code, timeout=60): + """Utility to check assertions in an independent Python subprocess. + + The script provided in the source code should return 0 and not print + anything on stderr or stdout. + + This is a port from cloudpickle https://github.com/cloudpipe/cloudpickle + + Parameters + ---------- + source_code : str + The Python source code to execute. + timeout : int, default=60 + Time in seconds before timeout. + """ + fd, source_file = tempfile.mkstemp(suffix="_src_test_sklearn.py") + os.close(fd) + try: + with open(source_file, "wb") as f: + f.write(source_code.encode("utf-8")) + cmd = [sys.executable, source_file] + cwd = op.normpath(op.join(op.dirname(sklearn.__file__), "..")) + env = os.environ.copy() + try: + env["PYTHONPATH"] = os.pathsep.join([cwd, env["PYTHONPATH"]]) + except KeyError: + env["PYTHONPATH"] = cwd + kwargs = {"cwd": cwd, "stderr": STDOUT, "env": env} + # If coverage is running, pass the config file to the subprocess + coverage_rc = os.environ.get("COVERAGE_PROCESS_START") + if coverage_rc: + kwargs["env"]["COVERAGE_PROCESS_START"] = coverage_rc + + kwargs["timeout"] = timeout + try: + try: + out = check_output(cmd, **kwargs) + except CalledProcessError as e: + raise RuntimeError( + "script errored with output:\n%s" % e.output.decode("utf-8") + ) + if out != b"": + raise AssertionError(out.decode("utf-8")) + except TimeoutExpired as e: + raise RuntimeError( + "script timeout, output so far:\n%s" % e.output.decode("utf-8") + ) + finally: + os.unlink(source_file) + + +def _convert_container(container, constructor_name, columns_name=None, dtype=None): + """Convert a given container to a specific array-like with a dtype. + + Parameters + ---------- + container : array-like + The container to convert. + constructor_name : {"list", "tuple", "array", "sparse", "dataframe", \ + "series", "index", "slice", "sparse_csr", "sparse_csc"} + The type of the returned container. + columns_name : index or array-like, default=None + For pandas container supporting `columns_names`, it will affect + specific names. + dtype : dtype, default=None + Force the dtype of the container. Does not apply to `"slice"` + container. + + Returns + ------- + converted_container + """ + if constructor_name == "list": + if dtype is None: + return list(container) + else: + return np.asarray(container, dtype=dtype).tolist() + elif constructor_name == "tuple": + if dtype is None: + return tuple(container) + else: + return tuple(np.asarray(container, dtype=dtype).tolist()) + elif constructor_name == "array": + return np.asarray(container, dtype=dtype) + elif constructor_name == "sparse": + return sp.sparse.csr_matrix(container, dtype=dtype) + elif constructor_name == "dataframe": + pd = pytest.importorskip("pandas") + return pd.DataFrame(container, columns=columns_name, dtype=dtype) + elif constructor_name == "series": + pd = pytest.importorskip("pandas") + return pd.Series(container, dtype=dtype) + elif constructor_name == "index": + pd = pytest.importorskip("pandas") + return pd.Index(container, dtype=dtype) + elif constructor_name == "slice": + return slice(container[0], container[1]) + elif constructor_name == "sparse_csr": + return sp.sparse.csr_matrix(container, dtype=dtype) + elif constructor_name == "sparse_csc": + return sp.sparse.csc_matrix(container, dtype=dtype) + + +def raises(expected_exc_type, match=None, may_pass=False, err_msg=None): + """Context manager to ensure exceptions are raised within a code block. + + This is similar to and inspired from pytest.raises, but supports a few + other cases. + + This is only intended to be used in estimator_checks.py where we don't + want to use pytest. In the rest of the code base, just use pytest.raises + instead. + + Parameters + ---------- + excepted_exc_type : Exception or list of Exception + The exception that should be raised by the block. If a list, the block + should raise one of the exceptions. + match : str or list of str, default=None + A regex that the exception message should match. If a list, one of + the entries must match. If None, match isn't enforced. + may_pass : bool, default=False + If True, the block is allowed to not raise an exception. Useful in + cases where some estimators may support a feature but others must + fail with an appropriate error message. By default, the context + manager will raise an exception if the block does not raise an + exception. + err_msg : str, default=None + If the context manager fails (e.g. the block fails to raise the + proper exception, or fails to match), then an AssertionError is + raised with this message. By default, an AssertionError is raised + with a default error message (depends on the kind of failure). Use + this to indicate how users should fix their estimators to pass the + checks. + + Attributes + ---------- + raised_and_matched : bool + True if an exception was raised and a match was found, False otherwise. + """ + return _Raises(expected_exc_type, match, may_pass, err_msg) + + +class _Raises(contextlib.AbstractContextManager): + # see raises() for parameters + def __init__(self, expected_exc_type, match, may_pass, err_msg): + self.expected_exc_types = ( + expected_exc_type + if isinstance(expected_exc_type, Iterable) + else [expected_exc_type] + ) + self.matches = [match] if isinstance(match, str) else match + self.may_pass = may_pass + self.err_msg = err_msg + self.raised_and_matched = False + + def __exit__(self, exc_type, exc_value, _): + # see + # https://docs.python.org/2.5/whatsnew/pep-343.html#SECTION000910000000000000000 + + if exc_type is None: # No exception was raised in the block + if self.may_pass: + return True # CM is happy + else: + err_msg = self.err_msg or f"Did not raise: {self.expected_exc_types}" + raise AssertionError(err_msg) + + if not any( + issubclass(exc_type, expected_type) + for expected_type in self.expected_exc_types + ): + if self.err_msg is not None: + raise AssertionError(self.err_msg) from exc_value + else: + return False # will re-raise the original exception + + if self.matches is not None: + err_msg = self.err_msg or ( + "The error message should contain one of the following " + "patterns:\n{}\nGot {}".format("\n".join(self.matches), str(exc_value)) + ) + if not any(re.search(match, str(exc_value)) for match in self.matches): + raise AssertionError(err_msg) from exc_value + self.raised_and_matched = True + + return True + + +class MinimalClassifier: + """Minimal classifier implementation with inheriting from BaseEstimator. + + This estimator should be tested with: + + * `check_estimator` in `test_estimator_checks.py`; + * within a `Pipeline` in `test_pipeline.py`; + * within a `SearchCV` in `test_search.py`. + """ + + _estimator_type = "classifier" + + def __init__(self, param=None): + self.param = param + + def get_params(self, deep=True): + return {"param": self.param} + + def set_params(self, **params): + for key, value in params.items(): + setattr(self, key, value) + return self + + def fit(self, X, y): + X, y = check_X_y(X, y) + check_classification_targets(y) + self.classes_, counts = np.unique(y, return_counts=True) + self._most_frequent_class_idx = counts.argmax() + return self + + def predict_proba(self, X): + check_is_fitted(self) + X = check_array(X) + proba_shape = (X.shape[0], self.classes_.size) + y_proba = np.zeros(shape=proba_shape, dtype=np.float64) + y_proba[:, self._most_frequent_class_idx] = 1.0 + return y_proba + + def predict(self, X): + y_proba = self.predict_proba(X) + y_pred = y_proba.argmax(axis=1) + return self.classes_[y_pred] + + def score(self, X, y): + from sklearn.metrics import accuracy_score + + return accuracy_score(y, self.predict(X)) + + +class MinimalRegressor: + """Minimal regressor implementation with inheriting from BaseEstimator. + + This estimator should be tested with: + + * `check_estimator` in `test_estimator_checks.py`; + * within a `Pipeline` in `test_pipeline.py`; + * within a `SearchCV` in `test_search.py`. + """ + + _estimator_type = "regressor" + + def __init__(self, param=None): + self.param = param + + def get_params(self, deep=True): + return {"param": self.param} + + def set_params(self, **params): + for key, value in params.items(): + setattr(self, key, value) + return self + + def fit(self, X, y): + X, y = check_X_y(X, y) + self.is_fitted_ = True + self._mean = np.mean(y) + return self + + def predict(self, X): + check_is_fitted(self) + X = check_array(X) + return np.ones(shape=(X.shape[0],)) * self._mean + + def score(self, X, y): + from sklearn.metrics import r2_score + + return r2_score(y, self.predict(X)) + + +class MinimalTransformer: + """Minimal transformer implementation with inheriting from + BaseEstimator. + + This estimator should be tested with: + + * `check_estimator` in `test_estimator_checks.py`; + * within a `Pipeline` in `test_pipeline.py`; + * within a `SearchCV` in `test_search.py`. + """ + + def __init__(self, param=None): + self.param = param + + def get_params(self, deep=True): + return {"param": self.param} + + def set_params(self, **params): + for key, value in params.items(): + setattr(self, key, value) + return self + + def fit(self, X, y=None): + check_array(X) + self.is_fitted_ = True + return self + + def transform(self, X, y=None): + check_is_fitted(self) + X = check_array(X) + return X + + def fit_transform(self, X, y=None): + return self.fit(X, y).transform(X, y) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_typedefs.pxd b/videollama2/lib/python3.10/site-packages/sklearn/utils/_typedefs.pxd new file mode 100644 index 0000000000000000000000000000000000000000..a6e390705496bd38ee79f825bec3de2ebac7491a --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_typedefs.pxd @@ -0,0 +1,28 @@ +#!python +cimport numpy as cnp + +# Floating point/data type +ctypedef cnp.float64_t DTYPE_t # WARNING: should match DTYPE in typedefs.pyx + +cdef enum: + DTYPECODE = cnp.NPY_FLOAT64 + ITYPECODE = cnp.NPY_INTP + INT32TYPECODE = cnp.NPY_INT32 + INT64TYPECODE = cnp.NPY_INT64 + +# Index/integer type. +# WARNING: ITYPE_t must be a signed integer type or you will have a bad time! +ctypedef cnp.intp_t ITYPE_t # WARNING: should match ITYPE in typedefs.pyx +ctypedef cnp.int32_t INT32TYPE_t # WARNING: should match INT32TYPE in typedefs.pyx +ctypedef cnp.int64_t INT64TYPE_t # WARNING: should match INT32TYPE in typedefs.pyx + +# scipy matrices indices dtype (namely for indptr and indices arrays) +# +# Note that indices might need to be represented as cnp.int64_t. +# Currently, we use Cython classes which do not handle fused types +# so we hardcode this type to cnp.int32_t, supporting all but edge +# cases. +# +# TODO: support cnp.int64_t for this case +# See: https://github.com/scikit-learn/scikit-learn/issues/23653 +ctypedef cnp.int32_t SPARSE_INDEX_TYPE_t diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.pxd b/videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.pxd new file mode 100644 index 0000000000000000000000000000000000000000..b3d9a3ff3261381e4a60f0c96ddd2a2bbd94e391 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.pxd @@ -0,0 +1,12 @@ +cimport numpy as cnp + +from libcpp.vector cimport vector +from ..utils._typedefs cimport ITYPE_t, DTYPE_t, INT32TYPE_t, INT64TYPE_t + +ctypedef fused vector_typed: + vector[DTYPE_t] + vector[ITYPE_t] + vector[INT32TYPE_t] + vector[INT64TYPE_t] + +cdef cnp.ndarray vector_to_nd_array(vector_typed * vect_ptr) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/discovery.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..083dca5cfcea543ecb3e529d4e3996a3f29db4dd --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/discovery.py @@ -0,0 +1,217 @@ +import pkgutil +import inspect +from importlib import import_module +from operator import itemgetter +from pathlib import Path + +_MODULE_TO_IGNORE = { + "tests", + "externals", + "setup", + "conftest", + "experimental", + "estimator_checks", +} + + +def all_estimators(type_filter=None): + """Get a list of all estimators from `sklearn`. + + This function crawls the module and gets all classes that inherit + from BaseEstimator. Classes that are defined in test-modules are not + included. + + Parameters + ---------- + type_filter : {"classifier", "regressor", "cluster", "transformer"} \ + or list of such str, default=None + Which kind of estimators should be returned. If None, no filter is + applied and all estimators are returned. Possible values are + 'classifier', 'regressor', 'cluster' and 'transformer' to get + estimators only of these specific types, or a list of these to + get the estimators that fit at least one of the types. + + Returns + ------- + estimators : list of tuples + List of (name, class), where ``name`` is the class name as string + and ``class`` is the actual type of the class. + """ + # lazy import to avoid circular imports from sklearn.base + from . import IS_PYPY + from ._testing import ignore_warnings + from ..base import ( + BaseEstimator, + ClassifierMixin, + RegressorMixin, + TransformerMixin, + ClusterMixin, + ) + + def is_abstract(c): + if not (hasattr(c, "__abstractmethods__")): + return False + if not len(c.__abstractmethods__): + return False + return True + + all_classes = [] + root = str(Path(__file__).parent.parent) # sklearn package + # Ignore deprecation warnings triggered at import time and from walking + # packages + with ignore_warnings(category=FutureWarning): + for _, module_name, _ in pkgutil.walk_packages(path=[root], prefix="sklearn."): + module_parts = module_name.split(".") + if ( + any(part in _MODULE_TO_IGNORE for part in module_parts) + or "._" in module_name + ): + continue + module = import_module(module_name) + classes = inspect.getmembers(module, inspect.isclass) + classes = [ + (name, est_cls) for name, est_cls in classes if not name.startswith("_") + ] + + # TODO: Remove when FeatureHasher is implemented in PYPY + # Skips FeatureHasher for PYPY + if IS_PYPY and "feature_extraction" in module_name: + classes = [ + (name, est_cls) + for name, est_cls in classes + if name == "FeatureHasher" + ] + + all_classes.extend(classes) + + all_classes = set(all_classes) + + estimators = [ + c + for c in all_classes + if (issubclass(c[1], BaseEstimator) and c[0] != "BaseEstimator") + ] + # get rid of abstract base classes + estimators = [c for c in estimators if not is_abstract(c[1])] + + if type_filter is not None: + if not isinstance(type_filter, list): + type_filter = [type_filter] + else: + type_filter = list(type_filter) # copy + filtered_estimators = [] + filters = { + "classifier": ClassifierMixin, + "regressor": RegressorMixin, + "transformer": TransformerMixin, + "cluster": ClusterMixin, + } + for name, mixin in filters.items(): + if name in type_filter: + type_filter.remove(name) + filtered_estimators.extend( + [est for est in estimators if issubclass(est[1], mixin)] + ) + estimators = filtered_estimators + if type_filter: + raise ValueError( + "Parameter type_filter must be 'classifier', " + "'regressor', 'transformer', 'cluster' or " + "None, got" + f" {repr(type_filter)}." + ) + + # drop duplicates, sort for reproducibility + # itemgetter is used to ensure the sort does not extend to the 2nd item of + # the tuple + return sorted(set(estimators), key=itemgetter(0)) + + +def all_displays(): + """Get a list of all displays from `sklearn`. + + Returns + ------- + displays : list of tuples + List of (name, class), where ``name`` is the display class name as + string and ``class`` is the actual type of the class. + """ + # lazy import to avoid circular imports from sklearn.base + from ._testing import ignore_warnings + + all_classes = [] + root = str(Path(__file__).parent.parent) # sklearn package + # Ignore deprecation warnings triggered at import time and from walking + # packages + with ignore_warnings(category=FutureWarning): + for _, module_name, _ in pkgutil.walk_packages(path=[root], prefix="sklearn."): + module_parts = module_name.split(".") + if ( + any(part in _MODULE_TO_IGNORE for part in module_parts) + or "._" in module_name + ): + continue + module = import_module(module_name) + classes = inspect.getmembers(module, inspect.isclass) + classes = [ + (name, display_class) + for name, display_class in classes + if not name.startswith("_") and name.endswith("Display") + ] + all_classes.extend(classes) + + return sorted(set(all_classes), key=itemgetter(0)) + + +def _is_checked_function(item): + if not inspect.isfunction(item): + return False + + if item.__name__.startswith("_"): + return False + + mod = item.__module__ + if not mod.startswith("sklearn.") or mod.endswith("estimator_checks"): + return False + + return True + + +def all_functions(): + """Get a list of all functions from `sklearn`. + + Returns + ------- + functions : list of tuples + List of (name, function), where ``name`` is the function name as + string and ``function`` is the actual function. + """ + # lazy import to avoid circular imports from sklearn.base + from ._testing import ignore_warnings + + all_functions = [] + root = str(Path(__file__).parent.parent) # sklearn package + # Ignore deprecation warnings triggered at import time and from walking + # packages + with ignore_warnings(category=FutureWarning): + for _, module_name, _ in pkgutil.walk_packages(path=[root], prefix="sklearn."): + module_parts = module_name.split(".") + if ( + any(part in _MODULE_TO_IGNORE for part in module_parts) + or "._" in module_name + ): + continue + + module = import_module(module_name) + functions = inspect.getmembers(module, _is_checked_function) + functions = [ + (func.__name__, func) + for name, func in functions + if not name.startswith("_") + ] + all_functions.extend(functions) + + # drop duplicates, sort for reproducibility + # itemgetter is used to ensure the sort does not extend to the 2nd item of + # the tuple + return sorted(set(all_functions), key=itemgetter(0)) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/estimator_checks.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/estimator_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..583788fcdb709b0b6515dd926eaeffe2f9687464 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/estimator_checks.py @@ -0,0 +1,4380 @@ +import warnings +import pickle +import re +from copy import deepcopy +from functools import partial, wraps +from inspect import signature +from numbers import Real + +import numpy as np +from scipy import sparse +from scipy.stats import rankdata +import joblib + +from . import IS_PYPY +from .. import config_context +from ._param_validation import Interval +from ._testing import _get_args +from ._testing import assert_raise_message +from ._testing import assert_array_equal +from ._testing import assert_array_almost_equal +from ._testing import assert_allclose +from ._testing import assert_allclose_dense_sparse +from ._testing import assert_array_less +from ._testing import set_random_state +from ._testing import SkipTest +from ._testing import ignore_warnings +from ._testing import create_memmap_backed_data +from ._testing import raises +from . import is_scalar_nan + +from ..linear_model import LinearRegression +from ..linear_model import LogisticRegression +from ..linear_model import RANSACRegressor +from ..linear_model import Ridge +from ..linear_model import SGDRegressor + +from ..base import ( + clone, + ClusterMixin, + is_classifier, + is_regressor, + is_outlier_detector, + RegressorMixin, +) + +from ..metrics import accuracy_score, adjusted_rand_score, f1_score +from ..random_projection import BaseRandomProjection +from ..feature_selection import SelectKBest +from ..feature_selection import SelectFromModel +from ..pipeline import make_pipeline +from ..exceptions import DataConversionWarning +from ..exceptions import NotFittedError +from ..exceptions import SkipTestWarning +from ..model_selection import train_test_split +from ..model_selection import ShuffleSplit +from ..model_selection._validation import _safe_split +from ..metrics.pairwise import rbf_kernel, linear_kernel, pairwise_distances +from ..utils.fixes import sp_version +from ..utils.fixes import parse_version +from ..utils.validation import check_is_fitted +from ..utils._param_validation import make_constraint +from ..utils._param_validation import generate_invalid_param_val +from ..utils._param_validation import InvalidParameterError + +from . import shuffle +from ._tags import ( + _DEFAULT_TAGS, + _safe_tags, +) +from .validation import has_fit_parameter, _num_samples +from ..preprocessing import StandardScaler +from ..preprocessing import scale +from ..datasets import ( + load_iris, + make_blobs, + make_multilabel_classification, + make_regression, +) + +REGRESSION_DATASET = None +CROSS_DECOMPOSITION = ["PLSCanonical", "PLSRegression", "CCA", "PLSSVD"] + + +def _yield_checks(estimator): + name = estimator.__class__.__name__ + tags = _safe_tags(estimator) + + yield check_no_attributes_set_in_init + yield check_estimators_dtypes + yield check_fit_score_takes_y + if has_fit_parameter(estimator, "sample_weight"): + yield check_sample_weights_pandas_series + yield check_sample_weights_not_an_array + yield check_sample_weights_list + if not tags["pairwise"]: + # We skip pairwise because the data is not pairwise + yield check_sample_weights_shape + yield check_sample_weights_not_overwritten + yield partial(check_sample_weights_invariance, kind="ones") + yield partial(check_sample_weights_invariance, kind="zeros") + yield check_estimators_fit_returns_self + yield partial(check_estimators_fit_returns_self, readonly_memmap=True) + + # Check that all estimator yield informative messages when + # trained on empty datasets + if not tags["no_validation"]: + yield check_complex_data + yield check_dtype_object + yield check_estimators_empty_data_messages + + if name not in CROSS_DECOMPOSITION: + # cross-decomposition's "transform" returns X and Y + yield check_pipeline_consistency + + if not tags["allow_nan"] and not tags["no_validation"]: + # Test that all estimators check their input for NaN's and infs + yield check_estimators_nan_inf + + if tags["pairwise"]: + # Check that pairwise estimator throws error on non-square input + yield check_nonsquare_error + + yield check_estimators_overwrite_params + if hasattr(estimator, "sparsify"): + yield check_sparsify_coefficients + + yield check_estimator_sparse_data + + # Test that estimators can be pickled, and once pickled + # give the same answer as before. + yield check_estimators_pickle + + yield check_estimator_get_tags_default_keys + + +def _yield_classifier_checks(classifier): + tags = _safe_tags(classifier) + + # test classifiers can handle non-array data and pandas objects + yield check_classifier_data_not_an_array + # test classifiers trained on a single label always return this label + yield check_classifiers_one_label + yield check_classifiers_one_label_sample_weights + yield check_classifiers_classes + yield check_estimators_partial_fit_n_features + if tags["multioutput"]: + yield check_classifier_multioutput + # basic consistency testing + yield check_classifiers_train + yield partial(check_classifiers_train, readonly_memmap=True) + yield partial(check_classifiers_train, readonly_memmap=True, X_dtype="float32") + yield check_classifiers_regression_target + if tags["multilabel"]: + yield check_classifiers_multilabel_representation_invariance + yield check_classifiers_multilabel_output_format_predict + yield check_classifiers_multilabel_output_format_predict_proba + yield check_classifiers_multilabel_output_format_decision_function + if not tags["no_validation"]: + yield check_supervised_y_no_nan + if not tags["multioutput_only"]: + yield check_supervised_y_2d + if tags["requires_fit"]: + yield check_estimators_unfitted + if "class_weight" in classifier.get_params().keys(): + yield check_class_weight_classifiers + + yield check_non_transformer_estimators_n_iter + # test if predict_proba is a monotonic transformation of decision_function + yield check_decision_proba_consistency + + +@ignore_warnings(category=FutureWarning) +def check_supervised_y_no_nan(name, estimator_orig): + # Checks that the Estimator targets are not NaN. + estimator = clone(estimator_orig) + rng = np.random.RandomState(888) + X = rng.standard_normal(size=(10, 5)) + + for value in [np.nan, np.inf]: + y = np.full(10, value) + y = _enforce_estimator_tags_y(estimator, y) + + module_name = estimator.__module__ + if module_name.startswith("sklearn.") and not ( + "test_" in module_name or module_name.endswith("_testing") + ): + # In scikit-learn we want the error message to mention the input + # name and be specific about the kind of unexpected value. + if np.isinf(value): + match = ( + r"Input (y|Y) contains infinity or a value too large for" + r" dtype\('float64'\)." + ) + else: + match = r"Input (y|Y) contains NaN." + else: + # Do not impose a particular error message to third-party libraries. + match = None + err_msg = ( + f"Estimator {name} should have raised error on fitting array y with inf" + " value." + ) + with raises(ValueError, match=match, err_msg=err_msg): + estimator.fit(X, y) + + +def _yield_regressor_checks(regressor): + tags = _safe_tags(regressor) + # TODO: test with intercept + # TODO: test with multiple responses + # basic testing + yield check_regressors_train + yield partial(check_regressors_train, readonly_memmap=True) + yield partial(check_regressors_train, readonly_memmap=True, X_dtype="float32") + yield check_regressor_data_not_an_array + yield check_estimators_partial_fit_n_features + if tags["multioutput"]: + yield check_regressor_multioutput + yield check_regressors_no_decision_function + if not tags["no_validation"] and not tags["multioutput_only"]: + yield check_supervised_y_2d + yield check_supervised_y_no_nan + name = regressor.__class__.__name__ + if name != "CCA": + # check that the regressor handles int input + yield check_regressors_int + if tags["requires_fit"]: + yield check_estimators_unfitted + yield check_non_transformer_estimators_n_iter + + +def _yield_transformer_checks(transformer): + tags = _safe_tags(transformer) + # All transformers should either deal with sparse data or raise an + # exception with type TypeError and an intelligible error message + if not tags["no_validation"]: + yield check_transformer_data_not_an_array + # these don't actually fit the data, so don't raise errors + yield check_transformer_general + if tags["preserves_dtype"]: + yield check_transformer_preserve_dtypes + yield partial(check_transformer_general, readonly_memmap=True) + if not _safe_tags(transformer, key="stateless"): + yield check_transformers_unfitted + # Dependent on external solvers and hence accessing the iter + # param is non-trivial. + external_solver = [ + "Isomap", + "KernelPCA", + "LocallyLinearEmbedding", + "RandomizedLasso", + "LogisticRegressionCV", + "BisectingKMeans", + ] + + name = transformer.__class__.__name__ + if name not in external_solver: + yield check_transformer_n_iter + + +def _yield_clustering_checks(clusterer): + yield check_clusterer_compute_labels_predict + name = clusterer.__class__.__name__ + if name not in ("WardAgglomeration", "FeatureAgglomeration"): + # this is clustering on the features + # let's not test that here. + yield check_clustering + yield partial(check_clustering, readonly_memmap=True) + yield check_estimators_partial_fit_n_features + if not hasattr(clusterer, "transform"): + yield check_non_transformer_estimators_n_iter + + +def _yield_outliers_checks(estimator): + + # checks for the contamination parameter + if hasattr(estimator, "contamination"): + yield check_outlier_contamination + + # checks for outlier detectors that have a fit_predict method + if hasattr(estimator, "fit_predict"): + yield check_outliers_fit_predict + + # checks for estimators that can be used on a test set + if hasattr(estimator, "predict"): + yield check_outliers_train + yield partial(check_outliers_train, readonly_memmap=True) + # test outlier detectors can handle non-array data + yield check_classifier_data_not_an_array + # test if NotFittedError is raised + if _safe_tags(estimator, key="requires_fit"): + yield check_estimators_unfitted + yield check_non_transformer_estimators_n_iter + + +def _yield_all_checks(estimator): + name = estimator.__class__.__name__ + tags = _safe_tags(estimator) + if "2darray" not in tags["X_types"]: + warnings.warn( + "Can't test estimator {} which requires input of type {}".format( + name, tags["X_types"] + ), + SkipTestWarning, + ) + return + if tags["_skip_test"]: + warnings.warn( + "Explicit SKIP via _skip_test tag for estimator {}.".format(name), + SkipTestWarning, + ) + return + + for check in _yield_checks(estimator): + yield check + if is_classifier(estimator): + for check in _yield_classifier_checks(estimator): + yield check + if is_regressor(estimator): + for check in _yield_regressor_checks(estimator): + yield check + if hasattr(estimator, "transform"): + for check in _yield_transformer_checks(estimator): + yield check + if isinstance(estimator, ClusterMixin): + for check in _yield_clustering_checks(estimator): + yield check + if is_outlier_detector(estimator): + for check in _yield_outliers_checks(estimator): + yield check + yield check_parameters_default_constructible + if not tags["non_deterministic"]: + yield check_methods_sample_order_invariance + yield check_methods_subset_invariance + yield check_fit2d_1sample + yield check_fit2d_1feature + yield check_get_params_invariance + yield check_set_params + yield check_dict_unchanged + yield check_dont_overwrite_parameters + yield check_fit_idempotent + yield check_fit_check_is_fitted + if not tags["no_validation"]: + yield check_n_features_in + yield check_fit1d + yield check_fit2d_predict1d + if tags["requires_y"]: + yield check_requires_y_none + if tags["requires_positive_X"]: + yield check_fit_non_negative + + +def _get_check_estimator_ids(obj): + """Create pytest ids for checks. + + When `obj` is an estimator, this returns the pprint version of the + estimator (with `print_changed_only=True`). When `obj` is a function, the + name of the function is returned with its keyword arguments. + + `_get_check_estimator_ids` is designed to be used as the `id` in + `pytest.mark.parametrize` where `check_estimator(..., generate_only=True)` + is yielding estimators and checks. + + Parameters + ---------- + obj : estimator or function + Items generated by `check_estimator`. + + Returns + ------- + id : str or None + + See Also + -------- + check_estimator + """ + if callable(obj): + if not isinstance(obj, partial): + return obj.__name__ + + if not obj.keywords: + return obj.func.__name__ + + kwstring = ",".join(["{}={}".format(k, v) for k, v in obj.keywords.items()]) + return "{}({})".format(obj.func.__name__, kwstring) + if hasattr(obj, "get_params"): + with config_context(print_changed_only=True): + return re.sub(r"\s", "", str(obj)) + + +def _construct_instance(Estimator): + """Construct Estimator instance if possible.""" + required_parameters = getattr(Estimator, "_required_parameters", []) + if len(required_parameters): + if required_parameters in (["estimator"], ["base_estimator"]): + # `RANSACRegressor` will raise an error with any model other + # than `LinearRegression` if we don't fix `min_samples` parameter. + # For common test, we can enforce using `LinearRegression` that + # is the default estimator in `RANSACRegressor` instead of `Ridge`. + if issubclass(Estimator, RANSACRegressor): + estimator = Estimator(LinearRegression()) + elif issubclass(Estimator, RegressorMixin): + estimator = Estimator(Ridge()) + elif issubclass(Estimator, SelectFromModel): + # Increases coverage because SGDRegressor has partial_fit + estimator = Estimator(SGDRegressor(random_state=0)) + else: + estimator = Estimator(LogisticRegression(C=1)) + elif required_parameters in (["estimators"],): + # Heterogeneous ensemble classes (i.e. stacking, voting) + if issubclass(Estimator, RegressorMixin): + estimator = Estimator( + estimators=[("est1", Ridge(alpha=0.1)), ("est2", Ridge(alpha=1))] + ) + else: + estimator = Estimator( + estimators=[ + ("est1", LogisticRegression(C=0.1)), + ("est2", LogisticRegression(C=1)), + ] + ) + else: + msg = ( + f"Can't instantiate estimator {Estimator.__name__} " + f"parameters {required_parameters}" + ) + # raise additional warning to be shown by pytest + warnings.warn(msg, SkipTestWarning) + raise SkipTest(msg) + else: + estimator = Estimator() + return estimator + + +def _maybe_mark_xfail(estimator, check, pytest): + # Mark (estimator, check) pairs as XFAIL if needed (see conditions in + # _should_be_skipped_or_marked()) + # This is similar to _maybe_skip(), but this one is used by + # @parametrize_with_checks() instead of check_estimator() + + should_be_marked, reason = _should_be_skipped_or_marked(estimator, check) + if not should_be_marked: + return estimator, check + else: + return pytest.param(estimator, check, marks=pytest.mark.xfail(reason=reason)) + + +def _maybe_skip(estimator, check): + # Wrap a check so that it's skipped if needed (see conditions in + # _should_be_skipped_or_marked()) + # This is similar to _maybe_mark_xfail(), but this one is used by + # check_estimator() instead of @parametrize_with_checks which requires + # pytest + should_be_skipped, reason = _should_be_skipped_or_marked(estimator, check) + if not should_be_skipped: + return check + + check_name = check.func.__name__ if isinstance(check, partial) else check.__name__ + + @wraps(check) + def wrapped(*args, **kwargs): + raise SkipTest( + f"Skipping {check_name} for {estimator.__class__.__name__}: {reason}" + ) + + return wrapped + + +def _should_be_skipped_or_marked(estimator, check): + # Return whether a check should be skipped (when using check_estimator()) + # or marked as XFAIL (when using @parametrize_with_checks()), along with a + # reason. + # Currently, a check should be skipped or marked if + # the check is in the _xfail_checks tag of the estimator + + check_name = check.func.__name__ if isinstance(check, partial) else check.__name__ + + xfail_checks = _safe_tags(estimator, key="_xfail_checks") or {} + if check_name in xfail_checks: + return True, xfail_checks[check_name] + + return False, "placeholder reason that will never be used" + + +def parametrize_with_checks(estimators): + """Pytest specific decorator for parametrizing estimator checks. + + The `id` of each check is set to be a pprint version of the estimator + and the name of the check with its keyword arguments. + This allows to use `pytest -k` to specify which tests to run:: + + pytest test_check_estimators.py -k check_estimators_fit_returns_self + + Parameters + ---------- + estimators : list of estimators instances + Estimators to generated checks for. + + .. versionchanged:: 0.24 + Passing a class was deprecated in version 0.23, and support for + classes was removed in 0.24. Pass an instance instead. + + .. versionadded:: 0.24 + + Returns + ------- + decorator : `pytest.mark.parametrize` + + See Also + -------- + check_estimator : Check if estimator adheres to scikit-learn conventions. + + Examples + -------- + >>> from sklearn.utils.estimator_checks import parametrize_with_checks + >>> from sklearn.linear_model import LogisticRegression + >>> from sklearn.tree import DecisionTreeRegressor + + >>> @parametrize_with_checks([LogisticRegression(), + ... DecisionTreeRegressor()]) + ... def test_sklearn_compatible_estimator(estimator, check): + ... check(estimator) + + """ + import pytest + + if any(isinstance(est, type) for est in estimators): + msg = ( + "Passing a class was deprecated in version 0.23 " + "and isn't supported anymore from 0.24." + "Please pass an instance instead." + ) + raise TypeError(msg) + + def checks_generator(): + for estimator in estimators: + name = type(estimator).__name__ + for check in _yield_all_checks(estimator): + check = partial(check, name) + yield _maybe_mark_xfail(estimator, check, pytest) + + return pytest.mark.parametrize( + "estimator, check", checks_generator(), ids=_get_check_estimator_ids + ) + + +def check_estimator(estimator=None, generate_only=False, Estimator="deprecated"): + """Check if estimator adheres to scikit-learn conventions. + + This function will run an extensive test-suite for input validation, + shapes, etc, making sure that the estimator complies with `scikit-learn` + conventions as detailed in :ref:`rolling_your_own_estimator`. + Additional tests for classifiers, regressors, clustering or transformers + will be run if the Estimator class inherits from the corresponding mixin + from sklearn.base. + + Setting `generate_only=True` returns a generator that yields (estimator, + check) tuples where the check can be called independently from each + other, i.e. `check(estimator)`. This allows all checks to be run + independently and report the checks that are failing. + + scikit-learn provides a pytest specific decorator, + :func:`~sklearn.utils.parametrize_with_checks`, making it easier to test + multiple estimators. + + Parameters + ---------- + estimator : estimator object + Estimator instance to check. + + .. versionadded:: 1.1 + Passing a class was deprecated in version 0.23, and support for + classes was removed in 0.24. + + generate_only : bool, default=False + When `False`, checks are evaluated when `check_estimator` is called. + When `True`, `check_estimator` returns a generator that yields + (estimator, check) tuples. The check is run by calling + `check(estimator)`. + + .. versionadded:: 0.22 + + Estimator : estimator object + Estimator instance to check. + + .. deprecated:: 1.1 + ``Estimator`` was deprecated in favor of ``estimator`` in version 1.1 + and will be removed in version 1.3. + + Returns + ------- + checks_generator : generator + Generator that yields (estimator, check) tuples. Returned when + `generate_only=True`. + + See Also + -------- + parametrize_with_checks : Pytest specific decorator for parametrizing estimator + checks. + """ + + if estimator is None and Estimator == "deprecated": + msg = "Either estimator or Estimator should be passed to check_estimator." + raise ValueError(msg) + + if Estimator != "deprecated": + msg = ( + "'Estimator' was deprecated in favor of 'estimator' in version 1.1 " + "and will be removed in version 1.3." + ) + warnings.warn(msg, FutureWarning) + estimator = Estimator + if isinstance(estimator, type): + msg = ( + "Passing a class was deprecated in version 0.23 " + "and isn't supported anymore from 0.24." + "Please pass an instance instead." + ) + raise TypeError(msg) + + name = type(estimator).__name__ + + def checks_generator(): + for check in _yield_all_checks(estimator): + check = _maybe_skip(estimator, check) + yield estimator, partial(check, name) + + if generate_only: + return checks_generator() + + for estimator, check in checks_generator(): + try: + check(estimator) + except SkipTest as exception: + # SkipTest is thrown when pandas can't be imported, or by checks + # that are in the xfail_checks tag + warnings.warn(str(exception), SkipTestWarning) + + +def _regression_dataset(): + global REGRESSION_DATASET + if REGRESSION_DATASET is None: + X, y = make_regression( + n_samples=200, + n_features=10, + n_informative=1, + bias=5.0, + noise=20, + random_state=42, + ) + X = StandardScaler().fit_transform(X) + REGRESSION_DATASET = X, y + return REGRESSION_DATASET + + +def _set_checking_parameters(estimator): + # set parameters to speed up some estimators and + # avoid deprecated behaviour + params = estimator.get_params() + name = estimator.__class__.__name__ + if name == "TSNE": + estimator.set_params(perplexity=2) + if "n_iter" in params and name != "TSNE": + estimator.set_params(n_iter=5) + if "max_iter" in params: + if estimator.max_iter is not None: + estimator.set_params(max_iter=min(5, estimator.max_iter)) + # LinearSVR, LinearSVC + if name in ["LinearSVR", "LinearSVC"]: + estimator.set_params(max_iter=20) + # NMF + if name == "NMF": + estimator.set_params(max_iter=500) + # MiniBatchNMF + if estimator.__class__.__name__ == "MiniBatchNMF": + estimator.set_params(max_iter=20, fresh_restarts=True) + # MLP + if name in ["MLPClassifier", "MLPRegressor"]: + estimator.set_params(max_iter=100) + # MiniBatchDictionaryLearning + if name == "MiniBatchDictionaryLearning": + estimator.set_params(max_iter=5) + + if "n_resampling" in params: + # randomized lasso + estimator.set_params(n_resampling=5) + if "n_estimators" in params: + estimator.set_params(n_estimators=min(5, estimator.n_estimators)) + if "max_trials" in params: + # RANSAC + estimator.set_params(max_trials=10) + if "n_init" in params: + # K-Means + estimator.set_params(n_init=2) + if "batch_size" in params and not name.startswith("MLP"): + estimator.set_params(batch_size=10) + + if name == "MeanShift": + # In the case of check_fit2d_1sample, bandwidth is set to None and + # is thus estimated. De facto it is 0.0 as a single sample is provided + # and this makes the test fails. Hence we give it a placeholder value. + estimator.set_params(bandwidth=1.0) + + if name == "TruncatedSVD": + # TruncatedSVD doesn't run with n_components = n_features + # This is ugly :-/ + estimator.n_components = 1 + + if name == "LassoLarsIC": + # Noise variance estimation does not work when `n_samples < n_features`. + # We need to provide the noise variance explicitly. + estimator.set_params(noise_variance=1.0) + + if hasattr(estimator, "n_clusters"): + estimator.n_clusters = min(estimator.n_clusters, 2) + + if hasattr(estimator, "n_best"): + estimator.n_best = 1 + + if name == "SelectFdr": + # be tolerant of noisy datasets (not actually speed) + estimator.set_params(alpha=0.5) + + if name == "TheilSenRegressor": + estimator.max_subpopulation = 100 + + if isinstance(estimator, BaseRandomProjection): + # Due to the jl lemma and often very few samples, the number + # of components of the random matrix projection will be probably + # greater than the number of features. + # So we impose a smaller number (avoid "auto" mode) + estimator.set_params(n_components=2) + + if isinstance(estimator, SelectKBest): + # SelectKBest has a default of k=10 + # which is more feature than we have in most case. + estimator.set_params(k=1) + + if name in ("HistGradientBoostingClassifier", "HistGradientBoostingRegressor"): + # The default min_samples_leaf (20) isn't appropriate for small + # datasets (only very shallow trees are built) that the checks use. + estimator.set_params(min_samples_leaf=5) + + if name == "DummyClassifier": + # the default strategy prior would output constant predictions and fail + # for check_classifiers_predictions + estimator.set_params(strategy="stratified") + + # Speed-up by reducing the number of CV or splits for CV estimators + loo_cv = ["RidgeCV", "RidgeClassifierCV"] + if name not in loo_cv and hasattr(estimator, "cv"): + estimator.set_params(cv=3) + if hasattr(estimator, "n_splits"): + estimator.set_params(n_splits=3) + + if name == "OneHotEncoder": + estimator.set_params(handle_unknown="ignore") + + if name == "QuantileRegressor": + # Avoid warning due to Scipy deprecating interior-point solver + solver = "highs" if sp_version >= parse_version("1.6.0") else "interior-point" + estimator.set_params(solver=solver) + + if name in CROSS_DECOMPOSITION: + estimator.set_params(n_components=1) + + # Default "auto" parameter can lead to different ordering of eigenvalues on + # windows: #24105 + if name == "SpectralEmbedding": + estimator.set_params(eigen_tol=1e-5) + + +class _NotAnArray: + """An object that is convertible to an array. + + Parameters + ---------- + data : array-like + The data. + """ + + def __init__(self, data): + self.data = np.asarray(data) + + def __array__(self, dtype=None): + return self.data + + def __array_function__(self, func, types, args, kwargs): + if func.__name__ == "may_share_memory": + return True + raise TypeError("Don't want to call array_function {}!".format(func.__name__)) + + +def _is_pairwise_metric(estimator): + """Returns True if estimator accepts pairwise metric. + + Parameters + ---------- + estimator : object + Estimator object to test. + + Returns + ------- + out : bool + True if _pairwise is set to True and False otherwise. + """ + metric = getattr(estimator, "metric", None) + + return bool(metric == "precomputed") + + +def _generate_sparse_matrix(X_csr): + """Generate sparse matrices with {32,64}bit indices of diverse format. + + Parameters + ---------- + X_csr: CSR Matrix + Input matrix in CSR format. + + Returns + ------- + out: iter(Matrices) + In format['dok', 'lil', 'dia', 'bsr', 'csr', 'csc', 'coo', + 'coo_64', 'csc_64', 'csr_64'] + """ + + assert X_csr.format == "csr" + yield "csr", X_csr.copy() + for sparse_format in ["dok", "lil", "dia", "bsr", "csc", "coo"]: + yield sparse_format, X_csr.asformat(sparse_format) + + # Generate large indices matrix only if its supported by scipy + X_coo = X_csr.asformat("coo") + X_coo.row = X_coo.row.astype("int64") + X_coo.col = X_coo.col.astype("int64") + yield "coo_64", X_coo + + for sparse_format in ["csc", "csr"]: + X = X_csr.asformat(sparse_format) + X.indices = X.indices.astype("int64") + X.indptr = X.indptr.astype("int64") + yield sparse_format + "_64", X + + +def check_estimator_sparse_data(name, estimator_orig): + rng = np.random.RandomState(0) + X = rng.uniform(size=(40, 3)) + X[X < 0.8] = 0 + X = _enforce_estimator_tags_X(estimator_orig, X) + X_csr = sparse.csr_matrix(X) + y = (4 * rng.uniform(size=40)).astype(int) + # catch deprecation warnings + with ignore_warnings(category=FutureWarning): + estimator = clone(estimator_orig) + y = _enforce_estimator_tags_y(estimator, y) + tags = _safe_tags(estimator_orig) + for matrix_format, X in _generate_sparse_matrix(X_csr): + # catch deprecation warnings + with ignore_warnings(category=FutureWarning): + estimator = clone(estimator_orig) + if name in ["Scaler", "StandardScaler"]: + estimator.set_params(with_mean=False) + # fit and predict + if "64" in matrix_format: + err_msg = ( + f"Estimator {name} doesn't seem to support {matrix_format} " + "matrix, and is not failing gracefully, e.g. by using " + "check_array(X, accept_large_sparse=False)" + ) + else: + err_msg = ( + f"Estimator {name} doesn't seem to fail gracefully on sparse " + "data: error message should state explicitly that sparse " + "input is not supported if this is not the case." + ) + with raises( + (TypeError, ValueError), + match=["sparse", "Sparse"], + may_pass=True, + err_msg=err_msg, + ): + with ignore_warnings(category=FutureWarning): + estimator.fit(X, y) + if hasattr(estimator, "predict"): + pred = estimator.predict(X) + if tags["multioutput_only"]: + assert pred.shape == (X.shape[0], 1) + else: + assert pred.shape == (X.shape[0],) + if hasattr(estimator, "predict_proba"): + probs = estimator.predict_proba(X) + if tags["binary_only"]: + expected_probs_shape = (X.shape[0], 2) + else: + expected_probs_shape = (X.shape[0], 4) + assert probs.shape == expected_probs_shape + + +@ignore_warnings(category=FutureWarning) +def check_sample_weights_pandas_series(name, estimator_orig): + # check that estimators will accept a 'sample_weight' parameter of + # type pandas.Series in the 'fit' function. + estimator = clone(estimator_orig) + try: + import pandas as pd + + X = np.array( + [ + [1, 1], + [1, 2], + [1, 3], + [1, 4], + [2, 1], + [2, 2], + [2, 3], + [2, 4], + [3, 1], + [3, 2], + [3, 3], + [3, 4], + ] + ) + X = pd.DataFrame(_enforce_estimator_tags_X(estimator_orig, X)) + y = pd.Series([1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 2, 2]) + weights = pd.Series([1] * 12) + if _safe_tags(estimator, key="multioutput_only"): + y = pd.DataFrame(y) + try: + estimator.fit(X, y, sample_weight=weights) + except ValueError: + raise ValueError( + "Estimator {0} raises error if " + "'sample_weight' parameter is of " + "type pandas.Series".format(name) + ) + except ImportError: + raise SkipTest( + "pandas is not installed: not testing for " + "input of type pandas.Series to class weight." + ) + + +@ignore_warnings(category=(FutureWarning)) +def check_sample_weights_not_an_array(name, estimator_orig): + # check that estimators will accept a 'sample_weight' parameter of + # type _NotAnArray in the 'fit' function. + estimator = clone(estimator_orig) + X = np.array( + [ + [1, 1], + [1, 2], + [1, 3], + [1, 4], + [2, 1], + [2, 2], + [2, 3], + [2, 4], + [3, 1], + [3, 2], + [3, 3], + [3, 4], + ] + ) + X = _NotAnArray(_enforce_estimator_tags_X(estimator_orig, X)) + y = _NotAnArray([1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 2, 2]) + weights = _NotAnArray([1] * 12) + if _safe_tags(estimator, key="multioutput_only"): + y = _NotAnArray(y.data.reshape(-1, 1)) + estimator.fit(X, y, sample_weight=weights) + + +@ignore_warnings(category=(FutureWarning)) +def check_sample_weights_list(name, estimator_orig): + # check that estimators will accept a 'sample_weight' parameter of + # type list in the 'fit' function. + estimator = clone(estimator_orig) + rnd = np.random.RandomState(0) + n_samples = 30 + X = _enforce_estimator_tags_X(estimator_orig, rnd.uniform(size=(n_samples, 3))) + y = np.arange(n_samples) % 3 + y = _enforce_estimator_tags_y(estimator, y) + sample_weight = [3] * n_samples + # Test that estimators don't raise any exception + estimator.fit(X, y, sample_weight=sample_weight) + + +@ignore_warnings(category=FutureWarning) +def check_sample_weights_shape(name, estimator_orig): + # check that estimators raise an error if sample_weight + # shape mismatches the input + estimator = clone(estimator_orig) + X = np.array( + [ + [1, 3], + [1, 3], + [1, 3], + [1, 3], + [2, 1], + [2, 1], + [2, 1], + [2, 1], + [3, 3], + [3, 3], + [3, 3], + [3, 3], + [4, 1], + [4, 1], + [4, 1], + [4, 1], + ] + ) + y = np.array([1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2]) + y = _enforce_estimator_tags_y(estimator, y) + + estimator.fit(X, y, sample_weight=np.ones(len(y))) + + with raises(ValueError): + estimator.fit(X, y, sample_weight=np.ones(2 * len(y))) + + with raises(ValueError): + estimator.fit(X, y, sample_weight=np.ones((len(y), 2))) + + +@ignore_warnings(category=FutureWarning) +def check_sample_weights_invariance(name, estimator_orig, kind="ones"): + # For kind="ones" check that the estimators yield same results for + # unit weights and no weights + # For kind="zeros" check that setting sample_weight to 0 is equivalent + # to removing corresponding samples. + estimator1 = clone(estimator_orig) + estimator2 = clone(estimator_orig) + set_random_state(estimator1, random_state=0) + set_random_state(estimator2, random_state=0) + + X1 = np.array( + [ + [1, 3], + [1, 3], + [1, 3], + [1, 3], + [2, 1], + [2, 1], + [2, 1], + [2, 1], + [3, 3], + [3, 3], + [3, 3], + [3, 3], + [4, 1], + [4, 1], + [4, 1], + [4, 1], + ], + dtype=np.float64, + ) + y1 = np.array([1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2], dtype=int) + + if kind == "ones": + X2 = X1 + y2 = y1 + sw2 = np.ones(shape=len(y1)) + err_msg = ( + f"For {name} sample_weight=None is not equivalent to sample_weight=ones" + ) + elif kind == "zeros": + # Construct a dataset that is very different to (X, y) if weights + # are disregarded, but identical to (X, y) given weights. + X2 = np.vstack([X1, X1 + 1]) + y2 = np.hstack([y1, 3 - y1]) + sw2 = np.ones(shape=len(y1) * 2) + sw2[len(y1) :] = 0 + X2, y2, sw2 = shuffle(X2, y2, sw2, random_state=0) + + err_msg = ( + f"For {name}, a zero sample_weight is not equivalent to removing the sample" + ) + else: # pragma: no cover + raise ValueError + + y1 = _enforce_estimator_tags_y(estimator1, y1) + y2 = _enforce_estimator_tags_y(estimator2, y2) + + estimator1.fit(X1, y=y1, sample_weight=None) + estimator2.fit(X2, y=y2, sample_weight=sw2) + + for method in ["predict", "predict_proba", "decision_function", "transform"]: + if hasattr(estimator_orig, method): + X_pred1 = getattr(estimator1, method)(X1) + X_pred2 = getattr(estimator2, method)(X1) + assert_allclose_dense_sparse(X_pred1, X_pred2, err_msg=err_msg) + + +def check_sample_weights_not_overwritten(name, estimator_orig): + # check that estimators don't override the passed sample_weight parameter + estimator = clone(estimator_orig) + set_random_state(estimator, random_state=0) + + X = np.array( + [ + [1, 3], + [1, 3], + [1, 3], + [1, 3], + [2, 1], + [2, 1], + [2, 1], + [2, 1], + [3, 3], + [3, 3], + [3, 3], + [3, 3], + [4, 1], + [4, 1], + [4, 1], + [4, 1], + ], + dtype=np.float64, + ) + y = np.array([1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2], dtype=int) + y = _enforce_estimator_tags_y(estimator, y) + + sample_weight_original = np.ones(y.shape[0]) + sample_weight_original[0] = 10.0 + + sample_weight_fit = sample_weight_original.copy() + + estimator.fit(X, y, sample_weight=sample_weight_fit) + + err_msg = f"{name} overwrote the original `sample_weight` given during fit" + assert_allclose(sample_weight_fit, sample_weight_original, err_msg=err_msg) + + +@ignore_warnings(category=(FutureWarning, UserWarning)) +def check_dtype_object(name, estimator_orig): + # check that estimators treat dtype object as numeric if possible + rng = np.random.RandomState(0) + X = _enforce_estimator_tags_X(estimator_orig, rng.uniform(size=(40, 10))) + X = X.astype(object) + tags = _safe_tags(estimator_orig) + y = (X[:, 0] * 4).astype(int) + estimator = clone(estimator_orig) + y = _enforce_estimator_tags_y(estimator, y) + + estimator.fit(X, y) + if hasattr(estimator, "predict"): + estimator.predict(X) + + if hasattr(estimator, "transform"): + estimator.transform(X) + + with raises(Exception, match="Unknown label type", may_pass=True): + estimator.fit(X, y.astype(object)) + + if "string" not in tags["X_types"]: + X[0, 0] = {"foo": "bar"} + msg = "argument must be a string.* number" + with raises(TypeError, match=msg): + estimator.fit(X, y) + else: + # Estimators supporting string will not call np.asarray to convert the + # data to numeric and therefore, the error will not be raised. + # Checking for each element dtype in the input array will be costly. + # Refer to #11401 for full discussion. + estimator.fit(X, y) + + +def check_complex_data(name, estimator_orig): + rng = np.random.RandomState(42) + # check that estimators raise an exception on providing complex data + X = rng.uniform(size=10) + 1j * rng.uniform(size=10) + X = X.reshape(-1, 1) + + # Something both valid for classification and regression + y = rng.randint(low=0, high=2, size=10) + 1j + estimator = clone(estimator_orig) + set_random_state(estimator, random_state=0) + with raises(ValueError, match="Complex data not supported"): + estimator.fit(X, y) + + +@ignore_warnings +def check_dict_unchanged(name, estimator_orig): + # this estimator raises + # ValueError: Found array with 0 feature(s) (shape=(23, 0)) + # while a minimum of 1 is required. + # error + if name in ["SpectralCoclustering"]: + return + rnd = np.random.RandomState(0) + if name in ["RANSACRegressor"]: + X = 3 * rnd.uniform(size=(20, 3)) + else: + X = 2 * rnd.uniform(size=(20, 3)) + + X = _enforce_estimator_tags_X(estimator_orig, X) + + y = X[:, 0].astype(int) + estimator = clone(estimator_orig) + y = _enforce_estimator_tags_y(estimator, y) + if hasattr(estimator, "n_components"): + estimator.n_components = 1 + + if hasattr(estimator, "n_clusters"): + estimator.n_clusters = 1 + + if hasattr(estimator, "n_best"): + estimator.n_best = 1 + + set_random_state(estimator, 1) + + estimator.fit(X, y) + for method in ["predict", "transform", "decision_function", "predict_proba"]: + if hasattr(estimator, method): + dict_before = estimator.__dict__.copy() + getattr(estimator, method)(X) + assert estimator.__dict__ == dict_before, ( + "Estimator changes __dict__ during %s" % method + ) + + +def _is_public_parameter(attr): + return not (attr.startswith("_") or attr.endswith("_")) + + +@ignore_warnings(category=FutureWarning) +def check_dont_overwrite_parameters(name, estimator_orig): + # check that fit method only changes or sets private attributes + if hasattr(estimator_orig.__init__, "deprecated_original"): + # to not check deprecated classes + return + estimator = clone(estimator_orig) + rnd = np.random.RandomState(0) + X = 3 * rnd.uniform(size=(20, 3)) + X = _enforce_estimator_tags_X(estimator_orig, X) + y = X[:, 0].astype(int) + y = _enforce_estimator_tags_y(estimator, y) + + if hasattr(estimator, "n_components"): + estimator.n_components = 1 + if hasattr(estimator, "n_clusters"): + estimator.n_clusters = 1 + + set_random_state(estimator, 1) + dict_before_fit = estimator.__dict__.copy() + estimator.fit(X, y) + + dict_after_fit = estimator.__dict__ + + public_keys_after_fit = [ + key for key in dict_after_fit.keys() if _is_public_parameter(key) + ] + + attrs_added_by_fit = [ + key for key in public_keys_after_fit if key not in dict_before_fit.keys() + ] + + # check that fit doesn't add any public attribute + assert not attrs_added_by_fit, ( + "Estimator adds public attribute(s) during" + " the fit method." + " Estimators are only allowed to add private attributes" + " either started with _ or ended" + " with _ but %s added" + % ", ".join(attrs_added_by_fit) + ) + + # check that fit doesn't change any public attribute + attrs_changed_by_fit = [ + key + for key in public_keys_after_fit + if (dict_before_fit[key] is not dict_after_fit[key]) + ] + + assert not attrs_changed_by_fit, ( + "Estimator changes public attribute(s) during" + " the fit method. Estimators are only allowed" + " to change attributes started" + " or ended with _, but" + " %s changed" + % ", ".join(attrs_changed_by_fit) + ) + + +@ignore_warnings(category=FutureWarning) +def check_fit2d_predict1d(name, estimator_orig): + # check by fitting a 2d array and predicting with a 1d array + rnd = np.random.RandomState(0) + X = 3 * rnd.uniform(size=(20, 3)) + X = _enforce_estimator_tags_X(estimator_orig, X) + y = X[:, 0].astype(int) + estimator = clone(estimator_orig) + y = _enforce_estimator_tags_y(estimator, y) + + if hasattr(estimator, "n_components"): + estimator.n_components = 1 + if hasattr(estimator, "n_clusters"): + estimator.n_clusters = 1 + + set_random_state(estimator, 1) + estimator.fit(X, y) + + for method in ["predict", "transform", "decision_function", "predict_proba"]: + if hasattr(estimator, method): + assert_raise_message( + ValueError, "Reshape your data", getattr(estimator, method), X[0] + ) + + +def _apply_on_subsets(func, X): + # apply function on the whole set and on mini batches + result_full = func(X) + n_features = X.shape[1] + result_by_batch = [func(batch.reshape(1, n_features)) for batch in X] + + # func can output tuple (e.g. score_samples) + if type(result_full) == tuple: + result_full = result_full[0] + result_by_batch = list(map(lambda x: x[0], result_by_batch)) + + if sparse.issparse(result_full): + result_full = result_full.A + result_by_batch = [x.A for x in result_by_batch] + + return np.ravel(result_full), np.ravel(result_by_batch) + + +@ignore_warnings(category=FutureWarning) +def check_methods_subset_invariance(name, estimator_orig): + # check that method gives invariant results if applied + # on mini batches or the whole set + rnd = np.random.RandomState(0) + X = 3 * rnd.uniform(size=(20, 3)) + X = _enforce_estimator_tags_X(estimator_orig, X) + y = X[:, 0].astype(int) + estimator = clone(estimator_orig) + y = _enforce_estimator_tags_y(estimator, y) + + if hasattr(estimator, "n_components"): + estimator.n_components = 1 + if hasattr(estimator, "n_clusters"): + estimator.n_clusters = 1 + + set_random_state(estimator, 1) + estimator.fit(X, y) + + for method in [ + "predict", + "transform", + "decision_function", + "score_samples", + "predict_proba", + ]: + + msg = ("{method} of {name} is not invariant when applied to a subset.").format( + method=method, name=name + ) + + if hasattr(estimator, method): + result_full, result_by_batch = _apply_on_subsets( + getattr(estimator, method), X + ) + assert_allclose(result_full, result_by_batch, atol=1e-7, err_msg=msg) + + +@ignore_warnings(category=FutureWarning) +def check_methods_sample_order_invariance(name, estimator_orig): + # check that method gives invariant results if applied + # on a subset with different sample order + rnd = np.random.RandomState(0) + X = 3 * rnd.uniform(size=(20, 3)) + X = _enforce_estimator_tags_X(estimator_orig, X) + y = X[:, 0].astype(np.int64) + if _safe_tags(estimator_orig, key="binary_only"): + y[y == 2] = 1 + estimator = clone(estimator_orig) + y = _enforce_estimator_tags_y(estimator, y) + + if hasattr(estimator, "n_components"): + estimator.n_components = 1 + if hasattr(estimator, "n_clusters"): + estimator.n_clusters = 2 + + set_random_state(estimator, 1) + estimator.fit(X, y) + + idx = np.random.permutation(X.shape[0]) + + for method in [ + "predict", + "transform", + "decision_function", + "score_samples", + "predict_proba", + ]: + msg = ( + "{method} of {name} is not invariant when applied to a dataset" + "with different sample order." + ).format(method=method, name=name) + + if hasattr(estimator, method): + assert_allclose_dense_sparse( + getattr(estimator, method)(X)[idx], + getattr(estimator, method)(X[idx]), + atol=1e-9, + err_msg=msg, + ) + + +@ignore_warnings +def check_fit2d_1sample(name, estimator_orig): + # Check that fitting a 2d array with only one sample either works or + # returns an informative message. The error message should either mention + # the number of samples or the number of classes. + rnd = np.random.RandomState(0) + X = 3 * rnd.uniform(size=(1, 10)) + X = _enforce_estimator_tags_X(estimator_orig, X) + + y = X[:, 0].astype(int) + estimator = clone(estimator_orig) + y = _enforce_estimator_tags_y(estimator, y) + + if hasattr(estimator, "n_components"): + estimator.n_components = 1 + if hasattr(estimator, "n_clusters"): + estimator.n_clusters = 1 + + set_random_state(estimator, 1) + + # min_cluster_size cannot be less than the data size for OPTICS. + if name == "OPTICS": + estimator.set_params(min_samples=1) + + # perplexity cannot be more than the number of samples for TSNE. + if name == "TSNE": + estimator.set_params(perplexity=0.5) + + msgs = [ + "1 sample", + "n_samples = 1", + "n_samples=1", + "one sample", + "1 class", + "one class", + ] + + with raises(ValueError, match=msgs, may_pass=True): + estimator.fit(X, y) + + +@ignore_warnings +def check_fit2d_1feature(name, estimator_orig): + # check fitting a 2d array with only 1 feature either works or returns + # informative message + rnd = np.random.RandomState(0) + X = 3 * rnd.uniform(size=(10, 1)) + X = _enforce_estimator_tags_X(estimator_orig, X) + y = X[:, 0].astype(int) + estimator = clone(estimator_orig) + y = _enforce_estimator_tags_y(estimator, y) + + if hasattr(estimator, "n_components"): + estimator.n_components = 1 + if hasattr(estimator, "n_clusters"): + estimator.n_clusters = 1 + # ensure two labels in subsample for RandomizedLogisticRegression + if name == "RandomizedLogisticRegression": + estimator.sample_fraction = 1 + # ensure non skipped trials for RANSACRegressor + if name == "RANSACRegressor": + estimator.residual_threshold = 0.5 + + y = _enforce_estimator_tags_y(estimator, y) + set_random_state(estimator, 1) + + msgs = [r"1 feature\(s\)", "n_features = 1", "n_features=1"] + + with raises(ValueError, match=msgs, may_pass=True): + estimator.fit(X, y) + + +@ignore_warnings +def check_fit1d(name, estimator_orig): + # check fitting 1d X array raises a ValueError + rnd = np.random.RandomState(0) + X = 3 * rnd.uniform(size=(20)) + y = X.astype(int) + estimator = clone(estimator_orig) + y = _enforce_estimator_tags_y(estimator, y) + + if hasattr(estimator, "n_components"): + estimator.n_components = 1 + if hasattr(estimator, "n_clusters"): + estimator.n_clusters = 1 + + set_random_state(estimator, 1) + with raises(ValueError): + estimator.fit(X, y) + + +@ignore_warnings(category=FutureWarning) +def check_transformer_general(name, transformer, readonly_memmap=False): + X, y = make_blobs( + n_samples=30, + centers=[[0, 0, 0], [1, 1, 1]], + random_state=0, + n_features=2, + cluster_std=0.1, + ) + X = StandardScaler().fit_transform(X) + X = _enforce_estimator_tags_X(transformer, X) + + if readonly_memmap: + X, y = create_memmap_backed_data([X, y]) + + _check_transformer(name, transformer, X, y) + + +@ignore_warnings(category=FutureWarning) +def check_transformer_data_not_an_array(name, transformer): + X, y = make_blobs( + n_samples=30, + centers=[[0, 0, 0], [1, 1, 1]], + random_state=0, + n_features=2, + cluster_std=0.1, + ) + X = StandardScaler().fit_transform(X) + X = _enforce_estimator_tags_X(transformer, X) + this_X = _NotAnArray(X) + this_y = _NotAnArray(np.asarray(y)) + _check_transformer(name, transformer, this_X, this_y) + # try the same with some list + _check_transformer(name, transformer, X.tolist(), y.tolist()) + + +@ignore_warnings(category=FutureWarning) +def check_transformers_unfitted(name, transformer): + X, y = _regression_dataset() + + transformer = clone(transformer) + with raises( + (AttributeError, ValueError), + err_msg=( + "The unfitted " + f"transformer {name} does not raise an error when " + "transform is called. Perhaps use " + "check_is_fitted in transform." + ), + ): + transformer.transform(X) + + +def _check_transformer(name, transformer_orig, X, y): + n_samples, n_features = np.asarray(X).shape + transformer = clone(transformer_orig) + set_random_state(transformer) + + # fit + + if name in CROSS_DECOMPOSITION: + y_ = np.c_[np.asarray(y), np.asarray(y)] + y_[::2, 1] *= 2 + if isinstance(X, _NotAnArray): + y_ = _NotAnArray(y_) + else: + y_ = y + + transformer.fit(X, y_) + # fit_transform method should work on non fitted estimator + transformer_clone = clone(transformer) + X_pred = transformer_clone.fit_transform(X, y=y_) + + if isinstance(X_pred, tuple): + for x_pred in X_pred: + assert x_pred.shape[0] == n_samples + else: + # check for consistent n_samples + assert X_pred.shape[0] == n_samples + + if hasattr(transformer, "transform"): + if name in CROSS_DECOMPOSITION: + X_pred2 = transformer.transform(X, y_) + X_pred3 = transformer.fit_transform(X, y=y_) + else: + X_pred2 = transformer.transform(X) + X_pred3 = transformer.fit_transform(X, y=y_) + + if _safe_tags(transformer_orig, key="non_deterministic"): + msg = name + " is non deterministic" + raise SkipTest(msg) + if isinstance(X_pred, tuple) and isinstance(X_pred2, tuple): + for x_pred, x_pred2, x_pred3 in zip(X_pred, X_pred2, X_pred3): + assert_allclose_dense_sparse( + x_pred, + x_pred2, + atol=1e-2, + err_msg="fit_transform and transform outcomes not consistent in %s" + % transformer, + ) + assert_allclose_dense_sparse( + x_pred, + x_pred3, + atol=1e-2, + err_msg="consecutive fit_transform outcomes not consistent in %s" + % transformer, + ) + else: + assert_allclose_dense_sparse( + X_pred, + X_pred2, + err_msg="fit_transform and transform outcomes not consistent in %s" + % transformer, + atol=1e-2, + ) + assert_allclose_dense_sparse( + X_pred, + X_pred3, + atol=1e-2, + err_msg="consecutive fit_transform outcomes not consistent in %s" + % transformer, + ) + assert _num_samples(X_pred2) == n_samples + assert _num_samples(X_pred3) == n_samples + + # raises error on malformed input for transform + if ( + hasattr(X, "shape") + and not _safe_tags(transformer, key="stateless") + and X.ndim == 2 + and X.shape[1] > 1 + ): + + # If it's not an array, it does not have a 'T' property + with raises( + ValueError, + err_msg=( + f"The transformer {name} does not raise an error " + "when the number of features in transform is different from " + "the number of features in fit." + ), + ): + transformer.transform(X[:, :-1]) + + +@ignore_warnings +def check_pipeline_consistency(name, estimator_orig): + if _safe_tags(estimator_orig, key="non_deterministic"): + msg = name + " is non deterministic" + raise SkipTest(msg) + + # check that make_pipeline(est) gives same score as est + X, y = make_blobs( + n_samples=30, + centers=[[0, 0, 0], [1, 1, 1]], + random_state=0, + n_features=2, + cluster_std=0.1, + ) + X = _enforce_estimator_tags_X(estimator_orig, X, kernel=rbf_kernel) + estimator = clone(estimator_orig) + y = _enforce_estimator_tags_y(estimator, y) + set_random_state(estimator) + pipeline = make_pipeline(estimator) + estimator.fit(X, y) + pipeline.fit(X, y) + + funcs = ["score", "fit_transform"] + + for func_name in funcs: + func = getattr(estimator, func_name, None) + if func is not None: + func_pipeline = getattr(pipeline, func_name) + result = func(X, y) + result_pipe = func_pipeline(X, y) + assert_allclose_dense_sparse(result, result_pipe) + + +@ignore_warnings +def check_fit_score_takes_y(name, estimator_orig): + # check that all estimators accept an optional y + # in fit and score so they can be used in pipelines + rnd = np.random.RandomState(0) + n_samples = 30 + X = rnd.uniform(size=(n_samples, 3)) + X = _enforce_estimator_tags_X(estimator_orig, X) + y = np.arange(n_samples) % 3 + estimator = clone(estimator_orig) + y = _enforce_estimator_tags_y(estimator, y) + set_random_state(estimator) + + funcs = ["fit", "score", "partial_fit", "fit_predict", "fit_transform"] + for func_name in funcs: + func = getattr(estimator, func_name, None) + if func is not None: + func(X, y) + args = [p.name for p in signature(func).parameters.values()] + if args[0] == "self": + # if_delegate_has_method makes methods into functions + # with an explicit "self", so need to shift arguments + args = args[1:] + assert args[1] in ["y", "Y"], ( + "Expected y or Y as second argument for method " + "%s of %s. Got arguments: %r." + % (func_name, type(estimator).__name__, args) + ) + + +@ignore_warnings +def check_estimators_dtypes(name, estimator_orig): + rnd = np.random.RandomState(0) + X_train_32 = 3 * rnd.uniform(size=(20, 5)).astype(np.float32) + X_train_32 = _enforce_estimator_tags_X(estimator_orig, X_train_32) + X_train_64 = X_train_32.astype(np.float64) + X_train_int_64 = X_train_32.astype(np.int64) + X_train_int_32 = X_train_32.astype(np.int32) + y = X_train_int_64[:, 0] + y = _enforce_estimator_tags_y(estimator_orig, y) + + methods = ["predict", "transform", "decision_function", "predict_proba"] + + for X_train in [X_train_32, X_train_64, X_train_int_64, X_train_int_32]: + estimator = clone(estimator_orig) + set_random_state(estimator, 1) + estimator.fit(X_train, y) + + for method in methods: + if hasattr(estimator, method): + getattr(estimator, method)(X_train) + + +def check_transformer_preserve_dtypes(name, transformer_orig): + # check that dtype are preserved meaning if input X is of some dtype + # X_transformed should be from the same dtype. + X, y = make_blobs( + n_samples=30, + centers=[[0, 0, 0], [1, 1, 1]], + random_state=0, + cluster_std=0.1, + ) + X = StandardScaler().fit_transform(X) + X = _enforce_estimator_tags_X(transformer_orig, X) + + for dtype in _safe_tags(transformer_orig, key="preserves_dtype"): + X_cast = X.astype(dtype) + transformer = clone(transformer_orig) + set_random_state(transformer) + X_trans1 = transformer.fit_transform(X_cast, y) + X_trans2 = transformer.fit(X_cast, y).transform(X_cast) + + for Xt, method in zip([X_trans1, X_trans2], ["fit_transform", "transform"]): + if isinstance(Xt, tuple): + # cross-decompostion returns a tuple of (x_scores, y_scores) + # when given y with fit_transform; only check the first element + Xt = Xt[0] + + # check that the output dtype is preserved + assert Xt.dtype == dtype, ( + f"{name} (method={method}) does not preserve dtype. " + f"Original/Expected dtype={dtype.__name__}, got dtype={Xt.dtype}." + ) + + +@ignore_warnings(category=FutureWarning) +def check_estimators_empty_data_messages(name, estimator_orig): + e = clone(estimator_orig) + set_random_state(e, 1) + + X_zero_samples = np.empty(0).reshape(0, 3) + # The precise message can change depending on whether X or y is + # validated first. Let us test the type of exception only: + err_msg = ( + f"The estimator {name} does not raise a ValueError when an " + "empty data is used to train. Perhaps use check_array in train." + ) + with raises(ValueError, err_msg=err_msg): + e.fit(X_zero_samples, []) + + X_zero_features = np.empty(0).reshape(12, 0) + # the following y should be accepted by both classifiers and regressors + # and ignored by unsupervised models + y = _enforce_estimator_tags_y(e, np.array([1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0])) + msg = r"0 feature\(s\) \(shape=\(\d*, 0\)\) while a minimum of \d* " "is required." + with raises(ValueError, match=msg): + e.fit(X_zero_features, y) + + +@ignore_warnings(category=FutureWarning) +def check_estimators_nan_inf(name, estimator_orig): + # Checks that Estimator X's do not contain NaN or inf. + rnd = np.random.RandomState(0) + X_train_finite = _enforce_estimator_tags_X( + estimator_orig, rnd.uniform(size=(10, 3)) + ) + X_train_nan = rnd.uniform(size=(10, 3)) + X_train_nan[0, 0] = np.nan + X_train_inf = rnd.uniform(size=(10, 3)) + X_train_inf[0, 0] = np.inf + y = np.ones(10) + y[:5] = 0 + y = _enforce_estimator_tags_y(estimator_orig, y) + error_string_fit = f"Estimator {name} doesn't check for NaN and inf in fit." + error_string_predict = f"Estimator {name} doesn't check for NaN and inf in predict." + error_string_transform = ( + f"Estimator {name} doesn't check for NaN and inf in transform." + ) + for X_train in [X_train_nan, X_train_inf]: + # catch deprecation warnings + with ignore_warnings(category=FutureWarning): + estimator = clone(estimator_orig) + set_random_state(estimator, 1) + # try to fit + with raises(ValueError, match=["inf", "NaN"], err_msg=error_string_fit): + estimator.fit(X_train, y) + # actually fit + estimator.fit(X_train_finite, y) + + # predict + if hasattr(estimator, "predict"): + with raises( + ValueError, + match=["inf", "NaN"], + err_msg=error_string_predict, + ): + estimator.predict(X_train) + + # transform + if hasattr(estimator, "transform"): + with raises( + ValueError, + match=["inf", "NaN"], + err_msg=error_string_transform, + ): + estimator.transform(X_train) + + +@ignore_warnings +def check_nonsquare_error(name, estimator_orig): + """Test that error is thrown when non-square data provided.""" + + X, y = make_blobs(n_samples=20, n_features=10) + estimator = clone(estimator_orig) + + with raises( + ValueError, + err_msg=( + f"The pairwise estimator {name} does not raise an error on non-square data" + ), + ): + estimator.fit(X, y) + + +@ignore_warnings +def check_estimators_pickle(name, estimator_orig): + """Test that we can pickle all estimators.""" + check_methods = ["predict", "transform", "decision_function", "predict_proba"] + + X, y = make_blobs( + n_samples=30, + centers=[[0, 0, 0], [1, 1, 1]], + random_state=0, + n_features=2, + cluster_std=0.1, + ) + + X = _enforce_estimator_tags_X(estimator_orig, X, kernel=rbf_kernel) + + tags = _safe_tags(estimator_orig) + # include NaN values when the estimator should deal with them + if tags["allow_nan"]: + # set randomly 10 elements to np.nan + rng = np.random.RandomState(42) + mask = rng.choice(X.size, 10, replace=False) + X.reshape(-1)[mask] = np.nan + + estimator = clone(estimator_orig) + + y = _enforce_estimator_tags_y(estimator, y) + + set_random_state(estimator) + estimator.fit(X, y) + + # pickle and unpickle! + pickled_estimator = pickle.dumps(estimator) + module_name = estimator.__module__ + if module_name.startswith("sklearn.") and not ( + "test_" in module_name or module_name.endswith("_testing") + ): + # strict check for sklearn estimators that are not implemented in test + # modules. + assert b"version" in pickled_estimator + unpickled_estimator = pickle.loads(pickled_estimator) + + result = dict() + for method in check_methods: + if hasattr(estimator, method): + result[method] = getattr(estimator, method)(X) + + for method in result: + unpickled_result = getattr(unpickled_estimator, method)(X) + assert_allclose_dense_sparse(result[method], unpickled_result) + + +@ignore_warnings(category=FutureWarning) +def check_estimators_partial_fit_n_features(name, estimator_orig): + # check if number of features changes between calls to partial_fit. + if not hasattr(estimator_orig, "partial_fit"): + return + estimator = clone(estimator_orig) + X, y = make_blobs(n_samples=50, random_state=1) + X = _enforce_estimator_tags_X(estimator_orig, X) + y = _enforce_estimator_tags_y(estimator_orig, y) + + try: + if is_classifier(estimator): + classes = np.unique(y) + estimator.partial_fit(X, y, classes=classes) + else: + estimator.partial_fit(X, y) + except NotImplementedError: + return + + with raises( + ValueError, + err_msg=( + f"The estimator {name} does not raise an error when the " + "number of features changes between calls to partial_fit." + ), + ): + estimator.partial_fit(X[:, :-1], y) + + +@ignore_warnings(category=FutureWarning) +def check_classifier_multioutput(name, estimator): + n_samples, n_labels, n_classes = 42, 5, 3 + tags = _safe_tags(estimator) + estimator = clone(estimator) + X, y = make_multilabel_classification( + random_state=42, n_samples=n_samples, n_labels=n_labels, n_classes=n_classes + ) + estimator.fit(X, y) + y_pred = estimator.predict(X) + + assert y_pred.shape == (n_samples, n_classes), ( + "The shape of the prediction for multioutput data is " + "incorrect. Expected {}, got {}.".format((n_samples, n_labels), y_pred.shape) + ) + assert y_pred.dtype.kind == "i" + + if hasattr(estimator, "decision_function"): + decision = estimator.decision_function(X) + assert isinstance(decision, np.ndarray) + assert decision.shape == (n_samples, n_classes), ( + "The shape of the decision function output for " + "multioutput data is incorrect. Expected {}, got {}.".format( + (n_samples, n_classes), decision.shape + ) + ) + + dec_pred = (decision > 0).astype(int) + dec_exp = estimator.classes_[dec_pred] + assert_array_equal(dec_exp, y_pred) + + if hasattr(estimator, "predict_proba"): + y_prob = estimator.predict_proba(X) + + if isinstance(y_prob, list) and not tags["poor_score"]: + for i in range(n_classes): + assert y_prob[i].shape == (n_samples, 2), ( + "The shape of the probability for multioutput data is" + " incorrect. Expected {}, got {}.".format( + (n_samples, 2), y_prob[i].shape + ) + ) + assert_array_equal( + np.argmax(y_prob[i], axis=1).astype(int), y_pred[:, i] + ) + elif not tags["poor_score"]: + assert y_prob.shape == (n_samples, n_classes), ( + "The shape of the probability for multioutput data is" + " incorrect. Expected {}, got {}.".format( + (n_samples, n_classes), y_prob.shape + ) + ) + assert_array_equal(y_prob.round().astype(int), y_pred) + + if hasattr(estimator, "decision_function") and hasattr(estimator, "predict_proba"): + for i in range(n_classes): + y_proba = estimator.predict_proba(X)[:, i] + y_decision = estimator.decision_function(X) + assert_array_equal(rankdata(y_proba), rankdata(y_decision[:, i])) + + +@ignore_warnings(category=FutureWarning) +def check_regressor_multioutput(name, estimator): + estimator = clone(estimator) + n_samples = n_features = 10 + + if not _is_pairwise_metric(estimator): + n_samples = n_samples + 1 + + X, y = make_regression( + random_state=42, n_targets=5, n_samples=n_samples, n_features=n_features + ) + X = _enforce_estimator_tags_X(estimator, X) + + estimator.fit(X, y) + y_pred = estimator.predict(X) + + assert y_pred.dtype == np.dtype("float64"), ( + "Multioutput predictions by a regressor are expected to be" + " floating-point precision. Got {} instead".format(y_pred.dtype) + ) + assert y_pred.shape == y.shape, ( + "The shape of the prediction for multioutput data is incorrect." + " Expected {}, got {}." + ) + + +@ignore_warnings(category=FutureWarning) +def check_clustering(name, clusterer_orig, readonly_memmap=False): + clusterer = clone(clusterer_orig) + X, y = make_blobs(n_samples=50, random_state=1) + X, y = shuffle(X, y, random_state=7) + X = StandardScaler().fit_transform(X) + rng = np.random.RandomState(7) + X_noise = np.concatenate([X, rng.uniform(low=-3, high=3, size=(5, 2))]) + + if readonly_memmap: + X, y, X_noise = create_memmap_backed_data([X, y, X_noise]) + + n_samples, n_features = X.shape + # catch deprecation and neighbors warnings + if hasattr(clusterer, "n_clusters"): + clusterer.set_params(n_clusters=3) + set_random_state(clusterer) + if name == "AffinityPropagation": + clusterer.set_params(preference=-100) + clusterer.set_params(max_iter=100) + + # fit + clusterer.fit(X) + # with lists + clusterer.fit(X.tolist()) + + pred = clusterer.labels_ + assert pred.shape == (n_samples,) + assert adjusted_rand_score(pred, y) > 0.4 + if _safe_tags(clusterer, key="non_deterministic"): + return + set_random_state(clusterer) + with warnings.catch_warnings(record=True): + pred2 = clusterer.fit_predict(X) + assert_array_equal(pred, pred2) + + # fit_predict(X) and labels_ should be of type int + assert pred.dtype in [np.dtype("int32"), np.dtype("int64")] + assert pred2.dtype in [np.dtype("int32"), np.dtype("int64")] + + # Add noise to X to test the possible values of the labels + labels = clusterer.fit_predict(X_noise) + + # There should be at least one sample in every cluster. Equivalently + # labels_ should contain all the consecutive values between its + # min and its max. + labels_sorted = np.unique(labels) + assert_array_equal( + labels_sorted, np.arange(labels_sorted[0], labels_sorted[-1] + 1) + ) + + # Labels are expected to start at 0 (no noise) or -1 (if noise) + assert labels_sorted[0] in [0, -1] + # Labels should be less than n_clusters - 1 + if hasattr(clusterer, "n_clusters"): + n_clusters = getattr(clusterer, "n_clusters") + assert n_clusters - 1 >= labels_sorted[-1] + # else labels should be less than max(labels_) which is necessarily true + + +@ignore_warnings(category=FutureWarning) +def check_clusterer_compute_labels_predict(name, clusterer_orig): + """Check that predict is invariant of compute_labels.""" + X, y = make_blobs(n_samples=20, random_state=0) + clusterer = clone(clusterer_orig) + set_random_state(clusterer) + + if hasattr(clusterer, "compute_labels"): + # MiniBatchKMeans + X_pred1 = clusterer.fit(X).predict(X) + clusterer.set_params(compute_labels=False) + X_pred2 = clusterer.fit(X).predict(X) + assert_array_equal(X_pred1, X_pred2) + + +@ignore_warnings(category=FutureWarning) +def check_classifiers_one_label(name, classifier_orig): + error_string_fit = "Classifier can't train when only one class is present." + error_string_predict = "Classifier can't predict when only one class is present." + rnd = np.random.RandomState(0) + X_train = rnd.uniform(size=(10, 3)) + X_test = rnd.uniform(size=(10, 3)) + y = np.ones(10) + # catch deprecation warnings + with ignore_warnings(category=FutureWarning): + classifier = clone(classifier_orig) + with raises( + ValueError, match="class", may_pass=True, err_msg=error_string_fit + ) as cm: + classifier.fit(X_train, y) + + if cm.raised_and_matched: + # ValueError was raised with proper error message + return + + assert_array_equal(classifier.predict(X_test), y, err_msg=error_string_predict) + + +@ignore_warnings(category=FutureWarning) +def check_classifiers_one_label_sample_weights(name, classifier_orig): + """Check that classifiers accepting sample_weight fit or throws a ValueError with + an explicit message if the problem is reduced to one class. + """ + error_fit = ( + f"{name} failed when fitted on one label after sample_weight trimming. Error " + "message is not explicit, it should have 'class'." + ) + error_predict = f"{name} prediction results should only output the remaining class." + rnd = np.random.RandomState(0) + # X should be square for test on SVC with precomputed kernel + X_train = rnd.uniform(size=(10, 10)) + X_test = rnd.uniform(size=(10, 10)) + y = np.arange(10) % 2 + sample_weight = y.copy() # select a single class + classifier = clone(classifier_orig) + + if has_fit_parameter(classifier, "sample_weight"): + match = [r"\bclass(es)?\b", error_predict] + err_type, err_msg = (AssertionError, ValueError), error_fit + else: + match = r"\bsample_weight\b" + err_type, err_msg = (TypeError, ValueError), None + + with raises(err_type, match=match, may_pass=True, err_msg=err_msg) as cm: + classifier.fit(X_train, y, sample_weight=sample_weight) + if cm.raised_and_matched: + # raise the proper error type with the proper error message + return + # for estimators that do not fail, they should be able to predict the only + # class remaining during fit + assert_array_equal( + classifier.predict(X_test), np.ones(10), err_msg=error_predict + ) + + +@ignore_warnings # Warnings are raised by decision function +def check_classifiers_train( + name, classifier_orig, readonly_memmap=False, X_dtype="float64" +): + X_m, y_m = make_blobs(n_samples=300, random_state=0) + X_m = X_m.astype(X_dtype) + X_m, y_m = shuffle(X_m, y_m, random_state=7) + X_m = StandardScaler().fit_transform(X_m) + # generate binary problem from multi-class one + y_b = y_m[y_m != 2] + X_b = X_m[y_m != 2] + + if name in ["BernoulliNB", "MultinomialNB", "ComplementNB", "CategoricalNB"]: + X_m -= X_m.min() + X_b -= X_b.min() + + if readonly_memmap: + X_m, y_m, X_b, y_b = create_memmap_backed_data([X_m, y_m, X_b, y_b]) + + problems = [(X_b, y_b)] + tags = _safe_tags(classifier_orig) + if not tags["binary_only"]: + problems.append((X_m, y_m)) + + for X, y in problems: + classes = np.unique(y) + n_classes = len(classes) + n_samples, n_features = X.shape + classifier = clone(classifier_orig) + X = _enforce_estimator_tags_X(classifier, X) + y = _enforce_estimator_tags_y(classifier, y) + + set_random_state(classifier) + # raises error on malformed input for fit + if not tags["no_validation"]: + with raises( + ValueError, + err_msg=( + f"The classifier {name} does not raise an error when " + "incorrect/malformed input data for fit is passed. The number " + "of training examples is not the same as the number of " + "labels. Perhaps use check_X_y in fit." + ), + ): + classifier.fit(X, y[:-1]) + + # fit + classifier.fit(X, y) + # with lists + classifier.fit(X.tolist(), y.tolist()) + assert hasattr(classifier, "classes_") + y_pred = classifier.predict(X) + + assert y_pred.shape == (n_samples,) + # training set performance + if not tags["poor_score"]: + assert accuracy_score(y, y_pred) > 0.83 + + # raises error on malformed input for predict + msg_pairwise = ( + "The classifier {} does not raise an error when shape of X in " + " {} is not equal to (n_test_samples, n_training_samples)" + ) + msg = ( + "The classifier {} does not raise an error when the number of " + "features in {} is different from the number of features in " + "fit." + ) + + if not tags["no_validation"]: + if tags["pairwise"]: + with raises( + ValueError, + err_msg=msg_pairwise.format(name, "predict"), + ): + classifier.predict(X.reshape(-1, 1)) + else: + with raises(ValueError, err_msg=msg.format(name, "predict")): + classifier.predict(X.T) + if hasattr(classifier, "decision_function"): + try: + # decision_function agrees with predict + decision = classifier.decision_function(X) + if n_classes == 2: + if not tags["multioutput_only"]: + assert decision.shape == (n_samples,) + else: + assert decision.shape == (n_samples, 1) + dec_pred = (decision.ravel() > 0).astype(int) + assert_array_equal(dec_pred, y_pred) + else: + assert decision.shape == (n_samples, n_classes) + assert_array_equal(np.argmax(decision, axis=1), y_pred) + + # raises error on malformed input for decision_function + if not tags["no_validation"]: + if tags["pairwise"]: + with raises( + ValueError, + err_msg=msg_pairwise.format(name, "decision_function"), + ): + classifier.decision_function(X.reshape(-1, 1)) + else: + with raises( + ValueError, + err_msg=msg.format(name, "decision_function"), + ): + classifier.decision_function(X.T) + except NotImplementedError: + pass + + if hasattr(classifier, "predict_proba"): + # predict_proba agrees with predict + y_prob = classifier.predict_proba(X) + assert y_prob.shape == (n_samples, n_classes) + assert_array_equal(np.argmax(y_prob, axis=1), y_pred) + # check that probas for all classes sum to one + assert_array_almost_equal(np.sum(y_prob, axis=1), np.ones(n_samples)) + if not tags["no_validation"]: + # raises error on malformed input for predict_proba + if tags["pairwise"]: + with raises( + ValueError, + err_msg=msg_pairwise.format(name, "predict_proba"), + ): + classifier.predict_proba(X.reshape(-1, 1)) + else: + with raises( + ValueError, + err_msg=msg.format(name, "predict_proba"), + ): + classifier.predict_proba(X.T) + if hasattr(classifier, "predict_log_proba"): + # predict_log_proba is a transformation of predict_proba + y_log_prob = classifier.predict_log_proba(X) + assert_allclose(y_log_prob, np.log(y_prob), 8, atol=1e-9) + assert_array_equal(np.argsort(y_log_prob), np.argsort(y_prob)) + + +def check_outlier_corruption(num_outliers, expected_outliers, decision): + # Check for deviation from the precise given contamination level that may + # be due to ties in the anomaly scores. + if num_outliers < expected_outliers: + start = num_outliers + end = expected_outliers + 1 + else: + start = expected_outliers + end = num_outliers + 1 + + # ensure that all values in the 'critical area' are tied, + # leading to the observed discrepancy between provided + # and actual contamination levels. + sorted_decision = np.sort(decision) + msg = ( + "The number of predicted outliers is not equal to the expected " + "number of outliers and this difference is not explained by the " + "number of ties in the decision_function values" + ) + assert len(np.unique(sorted_decision[start:end])) == 1, msg + + +def check_outliers_train(name, estimator_orig, readonly_memmap=True): + n_samples = 300 + X, _ = make_blobs(n_samples=n_samples, random_state=0) + X = shuffle(X, random_state=7) + + if readonly_memmap: + X = create_memmap_backed_data(X) + + n_samples, n_features = X.shape + estimator = clone(estimator_orig) + set_random_state(estimator) + + # fit + estimator.fit(X) + # with lists + estimator.fit(X.tolist()) + + y_pred = estimator.predict(X) + assert y_pred.shape == (n_samples,) + assert y_pred.dtype.kind == "i" + assert_array_equal(np.unique(y_pred), np.array([-1, 1])) + + decision = estimator.decision_function(X) + scores = estimator.score_samples(X) + for output in [decision, scores]: + assert output.dtype == np.dtype("float") + assert output.shape == (n_samples,) + + # raises error on malformed input for predict + with raises(ValueError): + estimator.predict(X.T) + + # decision_function agrees with predict + dec_pred = (decision >= 0).astype(int) + dec_pred[dec_pred == 0] = -1 + assert_array_equal(dec_pred, y_pred) + + # raises error on malformed input for decision_function + with raises(ValueError): + estimator.decision_function(X.T) + + # decision_function is a translation of score_samples + y_dec = scores - estimator.offset_ + assert_allclose(y_dec, decision) + + # raises error on malformed input for score_samples + with raises(ValueError): + estimator.score_samples(X.T) + + # contamination parameter (not for OneClassSVM which has the nu parameter) + if hasattr(estimator, "contamination") and not hasattr(estimator, "novelty"): + # proportion of outliers equal to contamination parameter when not + # set to 'auto'. This is true for the training set and cannot thus be + # checked as follows for estimators with a novelty parameter such as + # LocalOutlierFactor (tested in check_outliers_fit_predict) + expected_outliers = 30 + contamination = expected_outliers / n_samples + estimator.set_params(contamination=contamination) + estimator.fit(X) + y_pred = estimator.predict(X) + + num_outliers = np.sum(y_pred != 1) + # num_outliers should be equal to expected_outliers unless + # there are ties in the decision_function values. this can + # only be tested for estimators with a decision_function + # method, i.e. all estimators except LOF which is already + # excluded from this if branch. + if num_outliers != expected_outliers: + decision = estimator.decision_function(X) + check_outlier_corruption(num_outliers, expected_outliers, decision) + + +def check_outlier_contamination(name, estimator_orig): + # Check that the contamination parameter is in (0.0, 0.5] when it is an + # interval constraint. + + if not hasattr(estimator_orig, "_parameter_constraints"): + # Only estimator implementing parameter constraints will be checked + return + + if "contamination" not in estimator_orig._parameter_constraints: + return + + contamination_constraints = estimator_orig._parameter_constraints["contamination"] + if not any([isinstance(c, Interval) for c in contamination_constraints]): + raise AssertionError( + "contamination constraints should contain a Real Interval constraint." + ) + + for constraint in contamination_constraints: + if isinstance(constraint, Interval): + assert ( + constraint.type == Real + and constraint.left >= 0.0 + and constraint.right <= 0.5 + and (constraint.left > 0 or constraint.closed in {"right", "neither"}) + ), "contamination constraint should be an interval in (0, 0.5]" + + +@ignore_warnings(category=FutureWarning) +def check_classifiers_multilabel_representation_invariance(name, classifier_orig): + X, y = make_multilabel_classification( + n_samples=100, + n_features=2, + n_classes=5, + n_labels=3, + length=50, + allow_unlabeled=True, + random_state=0, + ) + X = scale(X) + + X_train, y_train = X[:80], y[:80] + X_test = X[80:] + + y_train_list_of_lists = y_train.tolist() + y_train_list_of_arrays = list(y_train) + + classifier = clone(classifier_orig) + set_random_state(classifier) + + y_pred = classifier.fit(X_train, y_train).predict(X_test) + + y_pred_list_of_lists = classifier.fit(X_train, y_train_list_of_lists).predict( + X_test + ) + + y_pred_list_of_arrays = classifier.fit(X_train, y_train_list_of_arrays).predict( + X_test + ) + + assert_array_equal(y_pred, y_pred_list_of_arrays) + assert_array_equal(y_pred, y_pred_list_of_lists) + + assert y_pred.dtype == y_pred_list_of_arrays.dtype + assert y_pred.dtype == y_pred_list_of_lists.dtype + assert type(y_pred) == type(y_pred_list_of_arrays) + assert type(y_pred) == type(y_pred_list_of_lists) + + +@ignore_warnings(category=FutureWarning) +def check_classifiers_multilabel_output_format_predict(name, classifier_orig): + """Check the output of the `predict` method for classifiers supporting + multilabel-indicator targets.""" + classifier = clone(classifier_orig) + set_random_state(classifier) + + n_samples, test_size, n_outputs = 100, 25, 5 + X, y = make_multilabel_classification( + n_samples=n_samples, + n_features=2, + n_classes=n_outputs, + n_labels=3, + length=50, + allow_unlabeled=True, + random_state=0, + ) + X = scale(X) + + X_train, X_test = X[:-test_size], X[-test_size:] + y_train, y_test = y[:-test_size], y[-test_size:] + classifier.fit(X_train, y_train) + + response_method_name = "predict" + predict_method = getattr(classifier, response_method_name, None) + if predict_method is None: + raise SkipTest(f"{name} does not have a {response_method_name} method.") + + y_pred = predict_method(X_test) + + # y_pred.shape -> y_test.shape with the same dtype + assert isinstance(y_pred, np.ndarray), ( + f"{name}.predict is expected to output a NumPy array. Got " + f"{type(y_pred)} instead." + ) + assert y_pred.shape == y_test.shape, ( + f"{name}.predict outputs a NumPy array of shape {y_pred.shape} " + f"instead of {y_test.shape}." + ) + assert y_pred.dtype == y_test.dtype, ( + f"{name}.predict does not output the same dtype than the targets. " + f"Got {y_pred.dtype} instead of {y_test.dtype}." + ) + + +@ignore_warnings(category=FutureWarning) +def check_classifiers_multilabel_output_format_predict_proba(name, classifier_orig): + """Check the output of the `predict_proba` method for classifiers supporting + multilabel-indicator targets.""" + classifier = clone(classifier_orig) + set_random_state(classifier) + + n_samples, test_size, n_outputs = 100, 25, 5 + X, y = make_multilabel_classification( + n_samples=n_samples, + n_features=2, + n_classes=n_outputs, + n_labels=3, + length=50, + allow_unlabeled=True, + random_state=0, + ) + X = scale(X) + + X_train, X_test = X[:-test_size], X[-test_size:] + y_train = y[:-test_size] + classifier.fit(X_train, y_train) + + response_method_name = "predict_proba" + predict_proba_method = getattr(classifier, response_method_name, None) + if predict_proba_method is None: + raise SkipTest(f"{name} does not have a {response_method_name} method.") + + y_pred = predict_proba_method(X_test) + + # y_pred.shape -> 2 possibilities: + # - list of length n_outputs of shape (n_samples, 2); + # - ndarray of shape (n_samples, n_outputs). + # dtype should be floating + if isinstance(y_pred, list): + assert len(y_pred) == n_outputs, ( + f"When {name}.predict_proba returns a list, the list should " + "be of length n_outputs and contain NumPy arrays. Got length " + f"of {len(y_pred)} instead of {n_outputs}." + ) + for pred in y_pred: + assert pred.shape == (test_size, 2), ( + f"When {name}.predict_proba returns a list, this list " + "should contain NumPy arrays of shape (n_samples, 2). Got " + f"NumPy arrays of shape {pred.shape} instead of " + f"{(test_size, 2)}." + ) + assert pred.dtype.kind == "f", ( + f"When {name}.predict_proba returns a list, it should " + "contain NumPy arrays with floating dtype. Got " + f"{pred.dtype} instead." + ) + # check that we have the correct probabilities + err_msg = ( + f"When {name}.predict_proba returns a list, each NumPy " + "array should contain probabilities for each class and " + "thus each row should sum to 1 (or close to 1 due to " + "numerical errors)." + ) + assert_allclose(pred.sum(axis=1), 1, err_msg=err_msg) + elif isinstance(y_pred, np.ndarray): + assert y_pred.shape == (test_size, n_outputs), ( + f"When {name}.predict_proba returns a NumPy array, the " + f"expected shape is (n_samples, n_outputs). Got {y_pred.shape}" + f" instead of {(test_size, n_outputs)}." + ) + assert y_pred.dtype.kind == "f", ( + f"When {name}.predict_proba returns a NumPy array, the " + f"expected data type is floating. Got {y_pred.dtype} instead." + ) + err_msg = ( + f"When {name}.predict_proba returns a NumPy array, this array " + "is expected to provide probabilities of the positive class " + "and should therefore contain values between 0 and 1." + ) + assert_array_less(0, y_pred, err_msg=err_msg) + assert_array_less(y_pred, 1, err_msg=err_msg) + else: + raise ValueError( + f"Unknown returned type {type(y_pred)} by {name}." + "predict_proba. A list or a Numpy array is expected." + ) + + +@ignore_warnings(category=FutureWarning) +def check_classifiers_multilabel_output_format_decision_function(name, classifier_orig): + """Check the output of the `decision_function` method for classifiers supporting + multilabel-indicator targets.""" + classifier = clone(classifier_orig) + set_random_state(classifier) + + n_samples, test_size, n_outputs = 100, 25, 5 + X, y = make_multilabel_classification( + n_samples=n_samples, + n_features=2, + n_classes=n_outputs, + n_labels=3, + length=50, + allow_unlabeled=True, + random_state=0, + ) + X = scale(X) + + X_train, X_test = X[:-test_size], X[-test_size:] + y_train = y[:-test_size] + classifier.fit(X_train, y_train) + + response_method_name = "decision_function" + decision_function_method = getattr(classifier, response_method_name, None) + if decision_function_method is None: + raise SkipTest(f"{name} does not have a {response_method_name} method.") + + y_pred = decision_function_method(X_test) + + # y_pred.shape -> y_test.shape with floating dtype + assert isinstance(y_pred, np.ndarray), ( + f"{name}.decision_function is expected to output a NumPy array." + f" Got {type(y_pred)} instead." + ) + assert y_pred.shape == (test_size, n_outputs), ( + f"{name}.decision_function is expected to provide a NumPy array " + f"of shape (n_samples, n_outputs). Got {y_pred.shape} instead of " + f"{(test_size, n_outputs)}." + ) + assert y_pred.dtype.kind == "f", ( + f"{name}.decision_function is expected to output a floating dtype." + f" Got {y_pred.dtype} instead." + ) + + +@ignore_warnings(category=FutureWarning) +def check_get_feature_names_out_error(name, estimator_orig): + """Check the error raised by get_feature_names_out when called before fit. + + Unfitted estimators with get_feature_names_out should raise a NotFittedError. + """ + + estimator = clone(estimator_orig) + err_msg = ( + f"Estimator {name} should have raised a NotFitted error when fit is called" + " before get_feature_names_out" + ) + with raises(NotFittedError, err_msg=err_msg): + estimator.get_feature_names_out() + + +@ignore_warnings(category=FutureWarning) +def check_estimators_fit_returns_self(name, estimator_orig, readonly_memmap=False): + """Check if self is returned when calling fit.""" + X, y = make_blobs(random_state=0, n_samples=21) + X = _enforce_estimator_tags_X(estimator_orig, X) + + estimator = clone(estimator_orig) + y = _enforce_estimator_tags_y(estimator, y) + + if readonly_memmap: + X, y = create_memmap_backed_data([X, y]) + + set_random_state(estimator) + assert estimator.fit(X, y) is estimator + + +@ignore_warnings +def check_estimators_unfitted(name, estimator_orig): + """Check that predict raises an exception in an unfitted estimator. + + Unfitted estimators should raise a NotFittedError. + """ + # Common test for Regressors, Classifiers and Outlier detection estimators + X, y = _regression_dataset() + + estimator = clone(estimator_orig) + for method in ( + "decision_function", + "predict", + "predict_proba", + "predict_log_proba", + ): + if hasattr(estimator, method): + with raises(NotFittedError): + getattr(estimator, method)(X) + + +@ignore_warnings(category=FutureWarning) +def check_supervised_y_2d(name, estimator_orig): + tags = _safe_tags(estimator_orig) + rnd = np.random.RandomState(0) + n_samples = 30 + X = _enforce_estimator_tags_X(estimator_orig, rnd.uniform(size=(n_samples, 3))) + y = np.arange(n_samples) % 3 + y = _enforce_estimator_tags_y(estimator_orig, y) + estimator = clone(estimator_orig) + set_random_state(estimator) + # fit + estimator.fit(X, y) + y_pred = estimator.predict(X) + + set_random_state(estimator) + # Check that when a 2D y is given, a DataConversionWarning is + # raised + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always", DataConversionWarning) + warnings.simplefilter("ignore", RuntimeWarning) + estimator.fit(X, y[:, np.newaxis]) + y_pred_2d = estimator.predict(X) + msg = "expected 1 DataConversionWarning, got: %s" % ", ".join( + [str(w_x) for w_x in w] + ) + if not tags["multioutput"]: + # check that we warned if we don't support multi-output + assert len(w) > 0, msg + assert ( + "DataConversionWarning('A column-vector y" + " was passed when a 1d array was expected" + in msg + ) + assert_allclose(y_pred.ravel(), y_pred_2d.ravel()) + + +@ignore_warnings +def check_classifiers_predictions(X, y, name, classifier_orig): + classes = np.unique(y) + classifier = clone(classifier_orig) + if name == "BernoulliNB": + X = X > X.mean() + set_random_state(classifier) + + classifier.fit(X, y) + y_pred = classifier.predict(X) + + if hasattr(classifier, "decision_function"): + decision = classifier.decision_function(X) + assert isinstance(decision, np.ndarray) + if len(classes) == 2: + dec_pred = (decision.ravel() > 0).astype(int) + dec_exp = classifier.classes_[dec_pred] + assert_array_equal( + dec_exp, + y_pred, + err_msg=( + "decision_function does not match " + "classifier for %r: expected '%s', got '%s'" + ) + % ( + classifier, + ", ".join(map(str, dec_exp)), + ", ".join(map(str, y_pred)), + ), + ) + elif getattr(classifier, "decision_function_shape", "ovr") == "ovr": + decision_y = np.argmax(decision, axis=1).astype(int) + y_exp = classifier.classes_[decision_y] + assert_array_equal( + y_exp, + y_pred, + err_msg=( + "decision_function does not match " + "classifier for %r: expected '%s', got '%s'" + ) + % ( + classifier, + ", ".join(map(str, y_exp)), + ", ".join(map(str, y_pred)), + ), + ) + + # training set performance + if name != "ComplementNB": + # This is a pathological data set for ComplementNB. + # For some specific cases 'ComplementNB' predicts less classes + # than expected + assert_array_equal(np.unique(y), np.unique(y_pred)) + assert_array_equal( + classes, + classifier.classes_, + err_msg="Unexpected classes_ attribute for %r: expected '%s', got '%s'" + % ( + classifier, + ", ".join(map(str, classes)), + ", ".join(map(str, classifier.classes_)), + ), + ) + + +def _choose_check_classifiers_labels(name, y, y_names): + # Semisupervised classifiers use -1 as the indicator for an unlabeled + # sample. + return ( + y + if name in ["LabelPropagation", "LabelSpreading", "SelfTrainingClassifier"] + else y_names + ) + + +def check_classifiers_classes(name, classifier_orig): + X_multiclass, y_multiclass = make_blobs( + n_samples=30, random_state=0, cluster_std=0.1 + ) + X_multiclass, y_multiclass = shuffle(X_multiclass, y_multiclass, random_state=7) + X_multiclass = StandardScaler().fit_transform(X_multiclass) + + X_binary = X_multiclass[y_multiclass != 2] + y_binary = y_multiclass[y_multiclass != 2] + + X_multiclass = _enforce_estimator_tags_X(classifier_orig, X_multiclass) + X_binary = _enforce_estimator_tags_X(classifier_orig, X_binary) + + labels_multiclass = ["one", "two", "three"] + labels_binary = ["one", "two"] + + y_names_multiclass = np.take(labels_multiclass, y_multiclass) + y_names_binary = np.take(labels_binary, y_binary) + + problems = [(X_binary, y_binary, y_names_binary)] + if not _safe_tags(classifier_orig, key="binary_only"): + problems.append((X_multiclass, y_multiclass, y_names_multiclass)) + + for X, y, y_names in problems: + for y_names_i in [y_names, y_names.astype("O")]: + y_ = _choose_check_classifiers_labels(name, y, y_names_i) + check_classifiers_predictions(X, y_, name, classifier_orig) + + labels_binary = [-1, 1] + y_names_binary = np.take(labels_binary, y_binary) + y_binary = _choose_check_classifiers_labels(name, y_binary, y_names_binary) + check_classifiers_predictions(X_binary, y_binary, name, classifier_orig) + + +@ignore_warnings(category=FutureWarning) +def check_regressors_int(name, regressor_orig): + X, _ = _regression_dataset() + X = _enforce_estimator_tags_X(regressor_orig, X[:50]) + rnd = np.random.RandomState(0) + y = rnd.randint(3, size=X.shape[0]) + y = _enforce_estimator_tags_y(regressor_orig, y) + rnd = np.random.RandomState(0) + # separate estimators to control random seeds + regressor_1 = clone(regressor_orig) + regressor_2 = clone(regressor_orig) + set_random_state(regressor_1) + set_random_state(regressor_2) + + if name in CROSS_DECOMPOSITION: + y_ = np.vstack([y, 2 * y + rnd.randint(2, size=len(y))]) + y_ = y_.T + else: + y_ = y + + # fit + regressor_1.fit(X, y_) + pred1 = regressor_1.predict(X) + regressor_2.fit(X, y_.astype(float)) + pred2 = regressor_2.predict(X) + assert_allclose(pred1, pred2, atol=1e-2, err_msg=name) + + +@ignore_warnings(category=FutureWarning) +def check_regressors_train( + name, regressor_orig, readonly_memmap=False, X_dtype=np.float64 +): + X, y = _regression_dataset() + X = X.astype(X_dtype) + y = scale(y) # X is already scaled + regressor = clone(regressor_orig) + X = _enforce_estimator_tags_X(regressor, X) + y = _enforce_estimator_tags_y(regressor, y) + if name in CROSS_DECOMPOSITION: + rnd = np.random.RandomState(0) + y_ = np.vstack([y, 2 * y + rnd.randint(2, size=len(y))]) + y_ = y_.T + else: + y_ = y + + if readonly_memmap: + X, y, y_ = create_memmap_backed_data([X, y, y_]) + + if not hasattr(regressor, "alphas") and hasattr(regressor, "alpha"): + # linear regressors need to set alpha, but not generalized CV ones + regressor.alpha = 0.01 + if name == "PassiveAggressiveRegressor": + regressor.C = 0.01 + + # raises error on malformed input for fit + with raises( + ValueError, + err_msg=( + f"The classifier {name} does not raise an error when " + "incorrect/malformed input data for fit is passed. The number of " + "training examples is not the same as the number of labels. Perhaps " + "use check_X_y in fit." + ), + ): + regressor.fit(X, y[:-1]) + # fit + set_random_state(regressor) + regressor.fit(X, y_) + regressor.fit(X.tolist(), y_.tolist()) + y_pred = regressor.predict(X) + assert y_pred.shape == y_.shape + + # TODO: find out why PLS and CCA fail. RANSAC is random + # and furthermore assumes the presence of outliers, hence + # skipped + if not _safe_tags(regressor, key="poor_score"): + assert regressor.score(X, y_) > 0.5 + + +@ignore_warnings +def check_regressors_no_decision_function(name, regressor_orig): + # check that regressors don't have a decision_function, predict_proba, or + # predict_log_proba method. + rng = np.random.RandomState(0) + regressor = clone(regressor_orig) + + X = rng.normal(size=(10, 4)) + X = _enforce_estimator_tags_X(regressor_orig, X) + y = _enforce_estimator_tags_y(regressor, X[:, 0]) + + regressor.fit(X, y) + funcs = ["decision_function", "predict_proba", "predict_log_proba"] + for func_name in funcs: + assert not hasattr(regressor, func_name) + + +@ignore_warnings(category=FutureWarning) +def check_class_weight_classifiers(name, classifier_orig): + + if _safe_tags(classifier_orig, key="binary_only"): + problems = [2] + else: + problems = [2, 3] + + for n_centers in problems: + # create a very noisy dataset + X, y = make_blobs(centers=n_centers, random_state=0, cluster_std=20) + X_train, X_test, y_train, y_test = train_test_split( + X, y, test_size=0.5, random_state=0 + ) + + # can't use gram_if_pairwise() here, setting up gram matrix manually + if _safe_tags(classifier_orig, key="pairwise"): + X_test = rbf_kernel(X_test, X_train) + X_train = rbf_kernel(X_train, X_train) + + n_centers = len(np.unique(y_train)) + + if n_centers == 2: + class_weight = {0: 1000, 1: 0.0001} + else: + class_weight = {0: 1000, 1: 0.0001, 2: 0.0001} + + classifier = clone(classifier_orig).set_params(class_weight=class_weight) + if hasattr(classifier, "n_iter"): + classifier.set_params(n_iter=100) + if hasattr(classifier, "max_iter"): + classifier.set_params(max_iter=1000) + if hasattr(classifier, "min_weight_fraction_leaf"): + classifier.set_params(min_weight_fraction_leaf=0.01) + if hasattr(classifier, "n_iter_no_change"): + classifier.set_params(n_iter_no_change=20) + + set_random_state(classifier) + classifier.fit(X_train, y_train) + y_pred = classifier.predict(X_test) + # XXX: Generally can use 0.89 here. On Windows, LinearSVC gets + # 0.88 (Issue #9111) + if not _safe_tags(classifier_orig, key="poor_score"): + assert np.mean(y_pred == 0) > 0.87 + + +@ignore_warnings(category=FutureWarning) +def check_class_weight_balanced_classifiers( + name, classifier_orig, X_train, y_train, X_test, y_test, weights +): + classifier = clone(classifier_orig) + if hasattr(classifier, "n_iter"): + classifier.set_params(n_iter=100) + if hasattr(classifier, "max_iter"): + classifier.set_params(max_iter=1000) + + set_random_state(classifier) + classifier.fit(X_train, y_train) + y_pred = classifier.predict(X_test) + + classifier.set_params(class_weight="balanced") + classifier.fit(X_train, y_train) + y_pred_balanced = classifier.predict(X_test) + assert f1_score(y_test, y_pred_balanced, average="weighted") > f1_score( + y_test, y_pred, average="weighted" + ) + + +@ignore_warnings(category=FutureWarning) +def check_class_weight_balanced_linear_classifier(name, Classifier): + """Test class weights with non-contiguous class labels.""" + # this is run on classes, not instances, though this should be changed + X = np.array([[-1.0, -1.0], [-1.0, 0], [-0.8, -1.0], [1.0, 1.0], [1.0, 0.0]]) + y = np.array([1, 1, 1, -1, -1]) + + classifier = Classifier() + + if hasattr(classifier, "n_iter"): + # This is a very small dataset, default n_iter are likely to prevent + # convergence + classifier.set_params(n_iter=1000) + if hasattr(classifier, "max_iter"): + classifier.set_params(max_iter=1000) + if hasattr(classifier, "cv"): + classifier.set_params(cv=3) + set_random_state(classifier) + + # Let the model compute the class frequencies + classifier.set_params(class_weight="balanced") + coef_balanced = classifier.fit(X, y).coef_.copy() + + # Count each label occurrence to reweight manually + n_samples = len(y) + n_classes = float(len(np.unique(y))) + + class_weight = { + 1: n_samples / (np.sum(y == 1) * n_classes), + -1: n_samples / (np.sum(y == -1) * n_classes), + } + classifier.set_params(class_weight=class_weight) + coef_manual = classifier.fit(X, y).coef_.copy() + + assert_allclose( + coef_balanced, + coef_manual, + err_msg="Classifier %s is not computing class_weight=balanced properly." % name, + ) + + +@ignore_warnings(category=FutureWarning) +def check_estimators_overwrite_params(name, estimator_orig): + X, y = make_blobs(random_state=0, n_samples=21) + X = _enforce_estimator_tags_X(estimator_orig, X, kernel=rbf_kernel) + estimator = clone(estimator_orig) + y = _enforce_estimator_tags_y(estimator, y) + + set_random_state(estimator) + + # Make a physical copy of the original estimator parameters before fitting. + params = estimator.get_params() + original_params = deepcopy(params) + + # Fit the model + estimator.fit(X, y) + + # Compare the state of the model parameters with the original parameters + new_params = estimator.get_params() + for param_name, original_value in original_params.items(): + new_value = new_params[param_name] + + # We should never change or mutate the internal state of input + # parameters by default. To check this we use the joblib.hash function + # that introspects recursively any subobjects to compute a checksum. + # The only exception to this rule of immutable constructor parameters + # is possible RandomState instance but in this check we explicitly + # fixed the random_state params recursively to be integer seeds. + assert joblib.hash(new_value) == joblib.hash(original_value), ( + "Estimator %s should not change or mutate " + " the parameter %s from %s to %s during fit." + % (name, param_name, original_value, new_value) + ) + + +@ignore_warnings(category=FutureWarning) +def check_no_attributes_set_in_init(name, estimator_orig): + """Check setting during init.""" + try: + # Clone fails if the estimator does not store + # all parameters as an attribute during init + estimator = clone(estimator_orig) + except AttributeError: + raise AttributeError( + f"Estimator {name} should store all parameters as an attribute during init." + ) + + if hasattr(type(estimator).__init__, "deprecated_original"): + return + + init_params = _get_args(type(estimator).__init__) + if IS_PYPY: + # __init__ signature has additional objects in PyPy + for key in ["obj"]: + if key in init_params: + init_params.remove(key) + parents_init_params = [ + param + for params_parent in (_get_args(parent) for parent in type(estimator).__mro__) + for param in params_parent + ] + + # Test for no setting apart from parameters during init + invalid_attr = set(vars(estimator)) - set(init_params) - set(parents_init_params) + assert not invalid_attr, ( + "Estimator %s should not set any attribute apart" + " from parameters during init. Found attributes %s." + % (name, sorted(invalid_attr)) + ) + + +@ignore_warnings(category=FutureWarning) +def check_sparsify_coefficients(name, estimator_orig): + X = np.array( + [ + [-2, -1], + [-1, -1], + [-1, -2], + [1, 1], + [1, 2], + [2, 1], + [-1, -2], + [2, 2], + [-2, -2], + ] + ) + y = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3]) + y = _enforce_estimator_tags_y(estimator_orig, y) + est = clone(estimator_orig) + + est.fit(X, y) + pred_orig = est.predict(X) + + # test sparsify with dense inputs + est.sparsify() + assert sparse.issparse(est.coef_) + pred = est.predict(X) + assert_array_equal(pred, pred_orig) + + # pickle and unpickle with sparse coef_ + est = pickle.loads(pickle.dumps(est)) + assert sparse.issparse(est.coef_) + pred = est.predict(X) + assert_array_equal(pred, pred_orig) + + +@ignore_warnings(category=FutureWarning) +def check_classifier_data_not_an_array(name, estimator_orig): + X = np.array( + [ + [3, 0], + [0, 1], + [0, 2], + [1, 1], + [1, 2], + [2, 1], + [0, 3], + [1, 0], + [2, 0], + [4, 4], + [2, 3], + [3, 2], + ] + ) + X = _enforce_estimator_tags_X(estimator_orig, X) + y = np.array([1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2]) + y = _enforce_estimator_tags_y(estimator_orig, y) + for obj_type in ["NotAnArray", "PandasDataframe"]: + check_estimators_data_not_an_array(name, estimator_orig, X, y, obj_type) + + +@ignore_warnings(category=FutureWarning) +def check_regressor_data_not_an_array(name, estimator_orig): + X, y = _regression_dataset() + X = _enforce_estimator_tags_X(estimator_orig, X) + y = _enforce_estimator_tags_y(estimator_orig, y) + for obj_type in ["NotAnArray", "PandasDataframe"]: + check_estimators_data_not_an_array(name, estimator_orig, X, y, obj_type) + + +@ignore_warnings(category=FutureWarning) +def check_estimators_data_not_an_array(name, estimator_orig, X, y, obj_type): + if name in CROSS_DECOMPOSITION: + raise SkipTest( + "Skipping check_estimators_data_not_an_array " + "for cross decomposition module as estimators " + "are not deterministic." + ) + # separate estimators to control random seeds + estimator_1 = clone(estimator_orig) + estimator_2 = clone(estimator_orig) + set_random_state(estimator_1) + set_random_state(estimator_2) + + if obj_type not in ["NotAnArray", "PandasDataframe"]: + raise ValueError("Data type {0} not supported".format(obj_type)) + + if obj_type == "NotAnArray": + y_ = _NotAnArray(np.asarray(y)) + X_ = _NotAnArray(np.asarray(X)) + else: + # Here pandas objects (Series and DataFrame) are tested explicitly + # because some estimators may handle them (especially their indexing) + # specially. + try: + import pandas as pd + + y_ = np.asarray(y) + if y_.ndim == 1: + y_ = pd.Series(y_) + else: + y_ = pd.DataFrame(y_) + X_ = pd.DataFrame(np.asarray(X)) + + except ImportError: + raise SkipTest( + "pandas is not installed: not checking estimators for pandas objects." + ) + + # fit + estimator_1.fit(X_, y_) + pred1 = estimator_1.predict(X_) + estimator_2.fit(X, y) + pred2 = estimator_2.predict(X) + assert_allclose(pred1, pred2, atol=1e-2, err_msg=name) + + +def check_parameters_default_constructible(name, Estimator): + # test default-constructibility + # get rid of deprecation warnings + + Estimator = Estimator.__class__ + + with ignore_warnings(category=FutureWarning): + estimator = _construct_instance(Estimator) + # test cloning + clone(estimator) + # test __repr__ + repr(estimator) + # test that set_params returns self + assert estimator.set_params() is estimator + + # test if init does nothing but set parameters + # this is important for grid_search etc. + # We get the default parameters from init and then + # compare these against the actual values of the attributes. + + # this comes from getattr. Gets rid of deprecation decorator. + init = getattr(estimator.__init__, "deprecated_original", estimator.__init__) + + try: + + def param_filter(p): + """Identify hyper parameters of an estimator.""" + return ( + p.name != "self" + and p.kind != p.VAR_KEYWORD + and p.kind != p.VAR_POSITIONAL + ) + + init_params = [ + p for p in signature(init).parameters.values() if param_filter(p) + ] + + except (TypeError, ValueError): + # init is not a python function. + # true for mixins + return + params = estimator.get_params() + # they can need a non-default argument + init_params = init_params[len(getattr(estimator, "_required_parameters", [])) :] + + for init_param in init_params: + assert ( + init_param.default != init_param.empty + ), "parameter %s for %s has no default value" % ( + init_param.name, + type(estimator).__name__, + ) + allowed_types = { + str, + int, + float, + bool, + tuple, + type(None), + type, + } + # Any numpy numeric such as np.int32. + allowed_types.update(np.core.numerictypes.allTypes.values()) + + allowed_value = ( + type(init_param.default) in allowed_types + or + # Although callables are mutable, we accept them as argument + # default value and trust that neither the implementation of + # the callable nor of the estimator changes the state of the + # callable. + callable(init_param.default) + ) + + assert allowed_value, ( + f"Parameter '{init_param.name}' of estimator " + f"'{Estimator.__name__}' is of type " + f"{type(init_param.default).__name__} which is not allowed. " + f"'{init_param.name}' must be a callable or must be of type " + f"{set(type.__name__ for type in allowed_types)}." + ) + if init_param.name not in params.keys(): + # deprecated parameter, not in get_params + assert init_param.default is None, ( + f"Estimator parameter '{init_param.name}' of estimator " + f"'{Estimator.__name__}' is not returned by get_params. " + "If it is deprecated, set its default value to None." + ) + continue + + param_value = params[init_param.name] + if isinstance(param_value, np.ndarray): + assert_array_equal(param_value, init_param.default) + else: + failure_text = ( + f"Parameter {init_param.name} was mutated on init. All " + "parameters must be stored unchanged." + ) + if is_scalar_nan(param_value): + # Allows to set default parameters to np.nan + assert param_value is init_param.default, failure_text + else: + assert param_value == init_param.default, failure_text + + +def _enforce_estimator_tags_y(estimator, y): + # Estimators with a `requires_positive_y` tag only accept strictly positive + # data + if _safe_tags(estimator, key="requires_positive_y"): + # Create strictly positive y. The minimal increment above 0 is 1, as + # y could be of integer dtype. + y += 1 + abs(y.min()) + # Estimators with a `binary_only` tag only accept up to two unique y values + if _safe_tags(estimator, key="binary_only") and y.size > 0: + y = np.where(y == y.flat[0], y, y.flat[0] + 1) + # Estimators in mono_output_task_error raise ValueError if y is of 1-D + # Convert into a 2-D y for those estimators. + if _safe_tags(estimator, key="multioutput_only"): + return np.reshape(y, (-1, 1)) + return y + + +def _enforce_estimator_tags_X(estimator, X, kernel=linear_kernel): + # Estimators with `1darray` in `X_types` tag only accept + # X of shape (`n_samples`,) + if "1darray" in _safe_tags(estimator, key="X_types"): + X = X[:, 0] + # Estimators with a `requires_positive_X` tag only accept + # strictly positive data + if _safe_tags(estimator, key="requires_positive_X"): + X = X - X.min() + if "categorical" in _safe_tags(estimator, key="X_types"): + X = (X - X.min()).astype(np.int32) + + if estimator.__class__.__name__ == "SkewedChi2Sampler": + # SkewedChi2Sampler requires X > -skewdness in transform + X = X - X.min() + + # Pairwise estimators only accept + # X of shape (`n_samples`, `n_samples`) + if _is_pairwise_metric(estimator): + X = pairwise_distances(X, metric="euclidean") + elif _safe_tags(estimator, key="pairwise"): + X = kernel(X, X) + return X + + +@ignore_warnings(category=FutureWarning) +def check_non_transformer_estimators_n_iter(name, estimator_orig): + # Test that estimators that are not transformers with a parameter + # max_iter, return the attribute of n_iter_ at least 1. + + # These models are dependent on external solvers like + # libsvm and accessing the iter parameter is non-trivial. + # SelfTrainingClassifier does not perform an iteration if all samples are + # labeled, hence n_iter_ = 0 is valid. + not_run_check_n_iter = [ + "Ridge", + "RidgeClassifier", + "RandomizedLasso", + "LogisticRegressionCV", + "LinearSVC", + "LogisticRegression", + "SelfTrainingClassifier", + ] + + # Tested in test_transformer_n_iter + not_run_check_n_iter += CROSS_DECOMPOSITION + if name in not_run_check_n_iter: + return + + # LassoLars stops early for the default alpha=1.0 the iris dataset. + if name == "LassoLars": + estimator = clone(estimator_orig).set_params(alpha=0.0) + else: + estimator = clone(estimator_orig) + if hasattr(estimator, "max_iter"): + iris = load_iris() + X, y_ = iris.data, iris.target + y_ = _enforce_estimator_tags_y(estimator, y_) + + set_random_state(estimator, 0) + + X = _enforce_estimator_tags_X(estimator_orig, X) + + estimator.fit(X, y_) + + assert np.all(estimator.n_iter_ >= 1) + + +@ignore_warnings(category=FutureWarning) +def check_transformer_n_iter(name, estimator_orig): + # Test that transformers with a parameter max_iter, return the + # attribute of n_iter_ at least 1. + estimator = clone(estimator_orig) + if hasattr(estimator, "max_iter"): + if name in CROSS_DECOMPOSITION: + # Check using default data + X = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [2.0, 2.0, 2.0], [2.0, 5.0, 4.0]] + y_ = [[0.1, -0.2], [0.9, 1.1], [0.1, -0.5], [0.3, -0.2]] + + else: + X, y_ = make_blobs( + n_samples=30, + centers=[[0, 0, 0], [1, 1, 1]], + random_state=0, + n_features=2, + cluster_std=0.1, + ) + X = _enforce_estimator_tags_X(estimator_orig, X) + set_random_state(estimator, 0) + estimator.fit(X, y_) + + # These return a n_iter per component. + if name in CROSS_DECOMPOSITION: + for iter_ in estimator.n_iter_: + assert iter_ >= 1 + else: + assert estimator.n_iter_ >= 1 + + +@ignore_warnings(category=FutureWarning) +def check_get_params_invariance(name, estimator_orig): + # Checks if get_params(deep=False) is a subset of get_params(deep=True) + e = clone(estimator_orig) + + shallow_params = e.get_params(deep=False) + deep_params = e.get_params(deep=True) + + assert all(item in deep_params.items() for item in shallow_params.items()) + + +@ignore_warnings(category=FutureWarning) +def check_set_params(name, estimator_orig): + # Check that get_params() returns the same thing + # before and after set_params() with some fuzz + estimator = clone(estimator_orig) + + orig_params = estimator.get_params(deep=False) + msg = "get_params result does not match what was passed to set_params" + + estimator.set_params(**orig_params) + curr_params = estimator.get_params(deep=False) + assert set(orig_params.keys()) == set(curr_params.keys()), msg + for k, v in curr_params.items(): + assert orig_params[k] is v, msg + + # some fuzz values + test_values = [-np.inf, np.inf, None] + + test_params = deepcopy(orig_params) + for param_name in orig_params.keys(): + default_value = orig_params[param_name] + for value in test_values: + test_params[param_name] = value + try: + estimator.set_params(**test_params) + except (TypeError, ValueError) as e: + e_type = e.__class__.__name__ + # Exception occurred, possibly parameter validation + warnings.warn( + "{0} occurred during set_params of param {1} on " + "{2}. It is recommended to delay parameter " + "validation until fit.".format(e_type, param_name, name) + ) + + change_warning_msg = ( + "Estimator's parameters changed after set_params raised {}".format( + e_type + ) + ) + params_before_exception = curr_params + curr_params = estimator.get_params(deep=False) + try: + assert set(params_before_exception.keys()) == set( + curr_params.keys() + ) + for k, v in curr_params.items(): + assert params_before_exception[k] is v + except AssertionError: + warnings.warn(change_warning_msg) + else: + curr_params = estimator.get_params(deep=False) + assert set(test_params.keys()) == set(curr_params.keys()), msg + for k, v in curr_params.items(): + assert test_params[k] is v, msg + test_params[param_name] = default_value + + +@ignore_warnings(category=FutureWarning) +def check_classifiers_regression_target(name, estimator_orig): + # Check if classifier throws an exception when fed regression targets + + X, y = _regression_dataset() + + X = _enforce_estimator_tags_X(estimator_orig, X) + e = clone(estimator_orig) + msg = "Unknown label type: " + if not _safe_tags(e, key="no_validation"): + with raises(ValueError, match=msg): + e.fit(X, y) + + +@ignore_warnings(category=FutureWarning) +def check_decision_proba_consistency(name, estimator_orig): + # Check whether an estimator having both decision_function and + # predict_proba methods has outputs with perfect rank correlation. + + centers = [(2, 2), (4, 4)] + X, y = make_blobs( + n_samples=100, + random_state=0, + n_features=4, + centers=centers, + cluster_std=1.0, + shuffle=True, + ) + X_train, X_test, y_train, y_test = train_test_split( + X, y, test_size=0.2, random_state=0 + ) + estimator = clone(estimator_orig) + + if hasattr(estimator, "decision_function") and hasattr(estimator, "predict_proba"): + + estimator.fit(X_train, y_train) + # Since the link function from decision_function() to predict_proba() + # is sometimes not precise enough (typically expit), we round to the + # 10th decimal to avoid numerical issues: we compare the rank + # with deterministic ties rather than get platform specific rank + # inversions in case of machine level differences. + a = estimator.predict_proba(X_test)[:, 1].round(decimals=10) + b = estimator.decision_function(X_test).round(decimals=10) + + rank_proba, rank_score = rankdata(a), rankdata(b) + try: + assert_array_almost_equal(rank_proba, rank_score) + except AssertionError: + # Sometimes, the rounding applied on the probabilities will have + # ties that are not present in the scores because it is + # numerically more precise. In this case, we relax the test by + # grouping the decision function scores based on the probability + # rank and check that the score is monotonically increasing. + grouped_y_score = np.array( + [b[rank_proba == group].mean() for group in np.unique(rank_proba)] + ) + sorted_idx = np.argsort(grouped_y_score) + assert_array_equal(sorted_idx, np.arange(len(sorted_idx))) + + +def check_outliers_fit_predict(name, estimator_orig): + # Check fit_predict for outlier detectors. + + n_samples = 300 + X, _ = make_blobs(n_samples=n_samples, random_state=0) + X = shuffle(X, random_state=7) + n_samples, n_features = X.shape + estimator = clone(estimator_orig) + + set_random_state(estimator) + + y_pred = estimator.fit_predict(X) + assert y_pred.shape == (n_samples,) + assert y_pred.dtype.kind == "i" + assert_array_equal(np.unique(y_pred), np.array([-1, 1])) + + # check fit_predict = fit.predict when the estimator has both a predict and + # a fit_predict method. recall that it is already assumed here that the + # estimator has a fit_predict method + if hasattr(estimator, "predict"): + y_pred_2 = estimator.fit(X).predict(X) + assert_array_equal(y_pred, y_pred_2) + + if hasattr(estimator, "contamination"): + # proportion of outliers equal to contamination parameter when not + # set to 'auto' + expected_outliers = 30 + contamination = float(expected_outliers) / n_samples + estimator.set_params(contamination=contamination) + y_pred = estimator.fit_predict(X) + + num_outliers = np.sum(y_pred != 1) + # num_outliers should be equal to expected_outliers unless + # there are ties in the decision_function values. this can + # only be tested for estimators with a decision_function + # method + if num_outliers != expected_outliers and hasattr( + estimator, "decision_function" + ): + decision = estimator.decision_function(X) + check_outlier_corruption(num_outliers, expected_outliers, decision) + + +def check_fit_non_negative(name, estimator_orig): + # Check that proper warning is raised for non-negative X + # when tag requires_positive_X is present + X = np.array([[-1.0, 1], [-1.0, 1]]) + y = np.array([1, 2]) + estimator = clone(estimator_orig) + with raises(ValueError): + estimator.fit(X, y) + + +def check_fit_idempotent(name, estimator_orig): + # Check that est.fit(X) is the same as est.fit(X).fit(X). Ideally we would + # check that the estimated parameters during training (e.g. coefs_) are + # the same, but having a universal comparison function for those + # attributes is difficult and full of edge cases. So instead we check that + # predict(), predict_proba(), decision_function() and transform() return + # the same results. + + check_methods = ["predict", "transform", "decision_function", "predict_proba"] + rng = np.random.RandomState(0) + + estimator = clone(estimator_orig) + set_random_state(estimator) + if "warm_start" in estimator.get_params().keys(): + estimator.set_params(warm_start=False) + + n_samples = 100 + X = rng.normal(loc=100, size=(n_samples, 2)) + X = _enforce_estimator_tags_X(estimator, X) + if is_regressor(estimator_orig): + y = rng.normal(size=n_samples) + else: + y = rng.randint(low=0, high=2, size=n_samples) + y = _enforce_estimator_tags_y(estimator, y) + + train, test = next(ShuffleSplit(test_size=0.2, random_state=rng).split(X)) + X_train, y_train = _safe_split(estimator, X, y, train) + X_test, y_test = _safe_split(estimator, X, y, test, train) + + # Fit for the first time + estimator.fit(X_train, y_train) + + result = { + method: getattr(estimator, method)(X_test) + for method in check_methods + if hasattr(estimator, method) + } + + # Fit again + set_random_state(estimator) + estimator.fit(X_train, y_train) + + for method in check_methods: + if hasattr(estimator, method): + new_result = getattr(estimator, method)(X_test) + if np.issubdtype(new_result.dtype, np.floating): + tol = 2 * np.finfo(new_result.dtype).eps + else: + tol = 2 * np.finfo(np.float64).eps + assert_allclose_dense_sparse( + result[method], + new_result, + atol=max(tol, 1e-9), + rtol=max(tol, 1e-7), + err_msg="Idempotency check failed for method {}".format(method), + ) + + +def check_fit_check_is_fitted(name, estimator_orig): + # Make sure that estimator doesn't pass check_is_fitted before calling fit + # and that passes check_is_fitted once it's fit. + + rng = np.random.RandomState(42) + + estimator = clone(estimator_orig) + set_random_state(estimator) + if "warm_start" in estimator.get_params(): + estimator.set_params(warm_start=False) + + n_samples = 100 + X = rng.normal(loc=100, size=(n_samples, 2)) + X = _enforce_estimator_tags_X(estimator, X) + if is_regressor(estimator_orig): + y = rng.normal(size=n_samples) + else: + y = rng.randint(low=0, high=2, size=n_samples) + y = _enforce_estimator_tags_y(estimator, y) + + if not _safe_tags(estimator).get("stateless", False): + # stateless estimators (such as FunctionTransformer) are always "fit"! + try: + check_is_fitted(estimator) + raise AssertionError( + f"{estimator.__class__.__name__} passes check_is_fitted before being" + " fit!" + ) + except NotFittedError: + pass + estimator.fit(X, y) + try: + check_is_fitted(estimator) + except NotFittedError as e: + raise NotFittedError( + "Estimator fails to pass `check_is_fitted` even though it has been fit." + ) from e + + +def check_n_features_in(name, estimator_orig): + # Make sure that n_features_in_ attribute doesn't exist until fit is + # called, and that its value is correct. + + rng = np.random.RandomState(0) + + estimator = clone(estimator_orig) + set_random_state(estimator) + if "warm_start" in estimator.get_params(): + estimator.set_params(warm_start=False) + + n_samples = 100 + X = rng.normal(loc=100, size=(n_samples, 2)) + X = _enforce_estimator_tags_X(estimator, X) + if is_regressor(estimator_orig): + y = rng.normal(size=n_samples) + else: + y = rng.randint(low=0, high=2, size=n_samples) + y = _enforce_estimator_tags_y(estimator, y) + + assert not hasattr(estimator, "n_features_in_") + estimator.fit(X, y) + assert hasattr(estimator, "n_features_in_") + assert estimator.n_features_in_ == X.shape[1] + + +def check_requires_y_none(name, estimator_orig): + # Make sure that an estimator with requires_y=True fails gracefully when + # given y=None + + rng = np.random.RandomState(0) + + estimator = clone(estimator_orig) + set_random_state(estimator) + + n_samples = 100 + X = rng.normal(loc=100, size=(n_samples, 2)) + X = _enforce_estimator_tags_X(estimator, X) + + expected_err_msgs = ( + "requires y to be passed, but the target y is None", + "Expected array-like (array or non-string sequence), got None", + "y should be a 1d array", + ) + + try: + estimator.fit(X, None) + except ValueError as ve: + if not any(msg in str(ve) for msg in expected_err_msgs): + raise ve + + +@ignore_warnings(category=FutureWarning) +def check_n_features_in_after_fitting(name, estimator_orig): + # Make sure that n_features_in are checked after fitting + tags = _safe_tags(estimator_orig) + + is_supported_X_types = ( + "2darray" in tags["X_types"] or "categorical" in tags["X_types"] + ) + + if not is_supported_X_types or tags["no_validation"]: + return + + rng = np.random.RandomState(0) + + estimator = clone(estimator_orig) + set_random_state(estimator) + if "warm_start" in estimator.get_params(): + estimator.set_params(warm_start=False) + + n_samples = 150 + X = rng.normal(size=(n_samples, 8)) + X = _enforce_estimator_tags_X(estimator, X) + + if is_regressor(estimator): + y = rng.normal(size=n_samples) + else: + y = rng.randint(low=0, high=2, size=n_samples) + y = _enforce_estimator_tags_y(estimator, y) + + estimator.fit(X, y) + assert estimator.n_features_in_ == X.shape[1] + + # check methods will check n_features_in_ + check_methods = [ + "predict", + "transform", + "decision_function", + "predict_proba", + "score", + ] + X_bad = X[:, [1]] + + msg = f"X has 1 features, but \\w+ is expecting {X.shape[1]} features as input" + for method in check_methods: + if not hasattr(estimator, method): + continue + + callable_method = getattr(estimator, method) + if method == "score": + callable_method = partial(callable_method, y=y) + + with raises(ValueError, match=msg): + callable_method(X_bad) + + # partial_fit will check in the second call + if not hasattr(estimator, "partial_fit"): + return + + estimator = clone(estimator_orig) + if is_classifier(estimator): + estimator.partial_fit(X, y, classes=np.unique(y)) + else: + estimator.partial_fit(X, y) + assert estimator.n_features_in_ == X.shape[1] + + with raises(ValueError, match=msg): + estimator.partial_fit(X_bad, y) + + +def check_estimator_get_tags_default_keys(name, estimator_orig): + # check that if _get_tags is implemented, it contains all keys from + # _DEFAULT_KEYS + estimator = clone(estimator_orig) + if not hasattr(estimator, "_get_tags"): + return + + tags_keys = set(estimator._get_tags().keys()) + default_tags_keys = set(_DEFAULT_TAGS.keys()) + assert tags_keys.intersection(default_tags_keys) == default_tags_keys, ( + f"{name}._get_tags() is missing entries for the following default tags" + f": {default_tags_keys - tags_keys.intersection(default_tags_keys)}" + ) + + +def check_dataframe_column_names_consistency(name, estimator_orig): + try: + import pandas as pd + except ImportError: + raise SkipTest( + "pandas is not installed: not checking column name consistency for pandas" + ) + + tags = _safe_tags(estimator_orig) + is_supported_X_types = ( + "2darray" in tags["X_types"] or "categorical" in tags["X_types"] + ) + + if not is_supported_X_types or tags["no_validation"]: + return + + rng = np.random.RandomState(0) + + estimator = clone(estimator_orig) + set_random_state(estimator) + + X_orig = rng.normal(size=(150, 8)) + + X_orig = _enforce_estimator_tags_X(estimator, X_orig) + n_samples, n_features = X_orig.shape + + names = np.array([f"col_{i}" for i in range(n_features)]) + X = pd.DataFrame(X_orig, columns=names) + + if is_regressor(estimator): + y = rng.normal(size=n_samples) + else: + y = rng.randint(low=0, high=2, size=n_samples) + y = _enforce_estimator_tags_y(estimator, y) + + # Check that calling `fit` does not raise any warnings about feature names. + with warnings.catch_warnings(): + warnings.filterwarnings( + "error", + message="X does not have valid feature names", + category=UserWarning, + module="sklearn", + ) + estimator.fit(X, y) + + if not hasattr(estimator, "feature_names_in_"): + raise ValueError( + "Estimator does not have a feature_names_in_ " + "attribute after fitting with a dataframe" + ) + assert isinstance(estimator.feature_names_in_, np.ndarray) + assert estimator.feature_names_in_.dtype == object + assert_array_equal(estimator.feature_names_in_, names) + + # Only check sklearn estimators for feature_names_in_ in docstring + module_name = estimator_orig.__module__ + if ( + module_name.startswith("sklearn.") + and not ("test_" in module_name or module_name.endswith("_testing")) + and ("feature_names_in_" not in (estimator_orig.__doc__)) + ): + raise ValueError( + f"Estimator {name} does not document its feature_names_in_ attribute" + ) + + check_methods = [] + for method in ( + "predict", + "transform", + "decision_function", + "predict_proba", + "score", + "score_samples", + "predict_log_proba", + ): + if not hasattr(estimator, method): + continue + + callable_method = getattr(estimator, method) + if method == "score": + callable_method = partial(callable_method, y=y) + check_methods.append((method, callable_method)) + + for _, method in check_methods: + with warnings.catch_warnings(): + warnings.filterwarnings( + "error", + message="X does not have valid feature names", + category=UserWarning, + module="sklearn", + ) + method(X) # works without UserWarning for valid features + + invalid_names = [ + (names[::-1], "Feature names must be in the same order as they were in fit."), + ( + [f"another_prefix_{i}" for i in range(n_features)], + "Feature names unseen at fit time:\n- another_prefix_0\n-" + " another_prefix_1\n", + ), + ( + names[:3], + f"Feature names seen at fit time, yet now missing:\n- {min(names[3:])}\n", + ), + ] + params = { + key: value + for key, value in estimator.get_params().items() + if "early_stopping" in key + } + early_stopping_enabled = any(value is True for value in params.values()) + + for invalid_name, additional_message in invalid_names: + X_bad = pd.DataFrame(X, columns=invalid_name) + + expected_msg = re.escape( + "The feature names should match those that were passed during fit.\n" + f"{additional_message}" + ) + for name, method in check_methods: + with raises( + ValueError, match=expected_msg, err_msg=f"{name} did not raise" + ): + method(X_bad) + + # partial_fit checks on second call + # Do not call partial fit if early_stopping is on + if not hasattr(estimator, "partial_fit") or early_stopping_enabled: + continue + + estimator = clone(estimator_orig) + if is_classifier(estimator): + classes = np.unique(y) + estimator.partial_fit(X, y, classes=classes) + else: + estimator.partial_fit(X, y) + + with raises(ValueError, match=expected_msg): + estimator.partial_fit(X_bad, y) + + +def check_transformer_get_feature_names_out(name, transformer_orig): + tags = transformer_orig._get_tags() + if "2darray" not in tags["X_types"] or tags["no_validation"]: + return + + X, y = make_blobs( + n_samples=30, + centers=[[0, 0, 0], [1, 1, 1]], + random_state=0, + n_features=2, + cluster_std=0.1, + ) + X = StandardScaler().fit_transform(X) + + transformer = clone(transformer_orig) + X = _enforce_estimator_tags_X(transformer, X) + + n_features = X.shape[1] + set_random_state(transformer) + + y_ = y + if name in CROSS_DECOMPOSITION: + y_ = np.c_[np.asarray(y), np.asarray(y)] + y_[::2, 1] *= 2 + + X_transform = transformer.fit_transform(X, y=y_) + input_features = [f"feature{i}" for i in range(n_features)] + + # input_features names is not the same length as n_features_in_ + with raises(ValueError, match="input_features should have length equal"): + transformer.get_feature_names_out(input_features[::2]) + + feature_names_out = transformer.get_feature_names_out(input_features) + assert feature_names_out is not None + assert isinstance(feature_names_out, np.ndarray) + assert feature_names_out.dtype == object + assert all(isinstance(name, str) for name in feature_names_out) + + if isinstance(X_transform, tuple): + n_features_out = X_transform[0].shape[1] + else: + n_features_out = X_transform.shape[1] + + assert ( + len(feature_names_out) == n_features_out + ), f"Expected {n_features_out} feature names, got {len(feature_names_out)}" + + +def check_transformer_get_feature_names_out_pandas(name, transformer_orig): + try: + import pandas as pd + except ImportError: + raise SkipTest( + "pandas is not installed: not checking column name consistency for pandas" + ) + + tags = transformer_orig._get_tags() + if "2darray" not in tags["X_types"] or tags["no_validation"]: + return + + X, y = make_blobs( + n_samples=30, + centers=[[0, 0, 0], [1, 1, 1]], + random_state=0, + n_features=2, + cluster_std=0.1, + ) + X = StandardScaler().fit_transform(X) + + transformer = clone(transformer_orig) + X = _enforce_estimator_tags_X(transformer, X) + + n_features = X.shape[1] + set_random_state(transformer) + + y_ = y + if name in CROSS_DECOMPOSITION: + y_ = np.c_[np.asarray(y), np.asarray(y)] + y_[::2, 1] *= 2 + + feature_names_in = [f"col{i}" for i in range(n_features)] + df = pd.DataFrame(X, columns=feature_names_in) + X_transform = transformer.fit_transform(df, y=y_) + + # error is raised when `input_features` do not match feature_names_in + invalid_feature_names = [f"bad{i}" for i in range(n_features)] + with raises(ValueError, match="input_features is not equal to feature_names_in_"): + transformer.get_feature_names_out(invalid_feature_names) + + feature_names_out_default = transformer.get_feature_names_out() + feature_names_in_explicit_names = transformer.get_feature_names_out( + feature_names_in + ) + assert_array_equal(feature_names_out_default, feature_names_in_explicit_names) + + if isinstance(X_transform, tuple): + n_features_out = X_transform[0].shape[1] + else: + n_features_out = X_transform.shape[1] + + assert ( + len(feature_names_out_default) == n_features_out + ), f"Expected {n_features_out} feature names, got {len(feature_names_out_default)}" + + +def check_param_validation(name, estimator_orig): + # Check that an informative error is raised when the value of a constructor + # parameter does not have an appropriate type or value. + rng = np.random.RandomState(0) + X = rng.uniform(size=(20, 5)) + y = rng.randint(0, 2, size=20) + y = _enforce_estimator_tags_y(estimator_orig, y) + + estimator_params = estimator_orig.get_params(deep=False).keys() + + # check that there is a constraint for each parameter + if estimator_params: + validation_params = estimator_orig._parameter_constraints.keys() + unexpected_params = set(validation_params) - set(estimator_params) + missing_params = set(estimator_params) - set(validation_params) + err_msg = ( + f"Mismatch between _parameter_constraints and the parameters of {name}." + f"\nConsider the unexpected parameters {unexpected_params} and expected but" + f" missing parameters {missing_params}" + ) + assert validation_params == estimator_params, err_msg + + # this object does not have a valid type for sure for all params + param_with_bad_type = type("BadType", (), {})() + + fit_methods = ["fit", "partial_fit", "fit_transform", "fit_predict"] + + for param_name in estimator_params: + constraints = estimator_orig._parameter_constraints[param_name] + + if constraints == "no_validation": + # This parameter is not validated + continue + + match = rf"The '{param_name}' parameter of {name} must be .* Got .* instead." + err_msg = ( + f"{name} does not raise an informative error message when the " + f"parameter {param_name} does not have a valid type or value." + ) + + estimator = clone(estimator_orig) + + # First, check that the error is raised if param doesn't match any valid type. + estimator.set_params(**{param_name: param_with_bad_type}) + + for method in fit_methods: + if not hasattr(estimator, method): + # the method is not accessible with the current set of parameters + continue + + with raises(InvalidParameterError, match=match, err_msg=err_msg): + if any( + isinstance(X_type, str) and X_type.endswith("labels") + for X_type in _safe_tags(estimator, key="X_types") + ): + # The estimator is a label transformer and take only `y` + getattr(estimator, method)(y) + else: + getattr(estimator, method)(X, y) + + # Then, for constraints that are more than a type constraint, check that the + # error is raised if param does match a valid type but does not match any valid + # value for this type. + constraints = [make_constraint(constraint) for constraint in constraints] + + for constraint in constraints: + try: + bad_value = generate_invalid_param_val(constraint, constraints) + except NotImplementedError: + continue + + estimator.set_params(**{param_name: bad_value}) + + for method in fit_methods: + if not hasattr(estimator, method): + # the method is not accessible with the current set of parameters + continue + + with raises(InvalidParameterError, match=match, err_msg=err_msg): + if any( + X_type.endswith("labels") + for X_type in _safe_tags(estimator, key="X_types") + ): + # The estimator is a label transformer and take only `y` + getattr(estimator, method)(y) + else: + getattr(estimator, method)(X, y) + + +def check_set_output_transform(name, transformer_orig): + # Check transformer.set_output with the default configuration does not + # change the transform output. + tags = transformer_orig._get_tags() + if "2darray" not in tags["X_types"] or tags["no_validation"]: + return + + rng = np.random.RandomState(0) + transformer = clone(transformer_orig) + + X = rng.uniform(size=(20, 5)) + X = _enforce_estimator_tags_X(transformer_orig, X) + y = rng.randint(0, 2, size=20) + y = _enforce_estimator_tags_y(transformer_orig, y) + set_random_state(transformer) + + def fit_then_transform(est): + if name in CROSS_DECOMPOSITION: + return est.fit(X, y).transform(X, y) + return est.fit(X, y).transform(X) + + def fit_transform(est): + return est.fit_transform(X, y) + + transform_methods = [fit_then_transform, fit_transform] + for transform_method in transform_methods: + transformer = clone(transformer) + X_trans_no_setting = transform_method(transformer) + + # Auto wrapping only wraps the first array + if name in CROSS_DECOMPOSITION: + X_trans_no_setting = X_trans_no_setting[0] + + transformer.set_output(transform="default") + X_trans_default = transform_method(transformer) + + if name in CROSS_DECOMPOSITION: + X_trans_default = X_trans_default[0] + + # Default and no setting -> returns the same transformation + assert_allclose_dense_sparse(X_trans_no_setting, X_trans_default) + + +def _output_from_fit_transform(transformer, name, X, df, y): + """Generate output to test `set_output` for different configuration: + + - calling either `fit.transform` or `fit_transform`; + - passing either a dataframe or a numpy array to fit; + - passing either a dataframe or a numpy array to transform. + """ + outputs = {} + + # fit then transform case: + cases = [ + ("fit.transform/df/df", df, df), + ("fit.transform/df/array", df, X), + ("fit.transform/array/df", X, df), + ("fit.transform/array/array", X, X), + ] + for ( + case, + data_fit, + data_transform, + ) in cases: + transformer.fit(data_fit, y) + if name in CROSS_DECOMPOSITION: + X_trans, _ = transformer.transform(data_transform, y) + else: + X_trans = transformer.transform(data_transform) + outputs[case] = (X_trans, transformer.get_feature_names_out()) + + # fit_transform case: + cases = [ + ("fit_transform/df", df), + ("fit_transform/array", X), + ] + for case, data in cases: + if name in CROSS_DECOMPOSITION: + X_trans, _ = transformer.fit_transform(data, y) + else: + X_trans = transformer.fit_transform(data, y) + outputs[case] = (X_trans, transformer.get_feature_names_out()) + + return outputs + + +def _check_generated_dataframe(name, case, outputs_default, outputs_pandas): + import pandas as pd + + X_trans, feature_names_default = outputs_default + df_trans, feature_names_pandas = outputs_pandas + + assert isinstance(df_trans, pd.DataFrame) + # We always rely on the output of `get_feature_names_out` of the + # transformer used to generate the dataframe as a ground-truth of the + # columns. + expected_dataframe = pd.DataFrame(X_trans, columns=feature_names_pandas) + + try: + pd.testing.assert_frame_equal(df_trans, expected_dataframe) + except AssertionError as e: + raise AssertionError( + f"{name} does not generate a valid dataframe in the {case} " + "case. The generated dataframe is not equal to the expected " + f"dataframe. The error message is: {e}" + ) from e + + +def check_set_output_transform_pandas(name, transformer_orig): + # Check transformer.set_output configures the output of transform="pandas". + try: + import pandas as pd + except ImportError: + raise SkipTest( + "pandas is not installed: not checking column name consistency for pandas" + ) + + tags = transformer_orig._get_tags() + if "2darray" not in tags["X_types"] or tags["no_validation"]: + return + + rng = np.random.RandomState(0) + transformer = clone(transformer_orig) + + X = rng.uniform(size=(20, 5)) + X = _enforce_estimator_tags_X(transformer_orig, X) + y = rng.randint(0, 2, size=20) + y = _enforce_estimator_tags_y(transformer_orig, y) + set_random_state(transformer) + + feature_names_in = [f"col{i}" for i in range(X.shape[1])] + df = pd.DataFrame(X, columns=feature_names_in) + + transformer_default = clone(transformer).set_output(transform="default") + outputs_default = _output_from_fit_transform(transformer_default, name, X, df, y) + transformer_pandas = clone(transformer).set_output(transform="pandas") + try: + outputs_pandas = _output_from_fit_transform(transformer_pandas, name, X, df, y) + except ValueError as e: + # transformer does not support sparse data + assert str(e) == "Pandas output does not support sparse data.", e + return + + for case in outputs_default: + _check_generated_dataframe( + name, case, outputs_default[case], outputs_pandas[case] + ) + + +def check_global_ouptut_transform_pandas(name, transformer_orig): + """Check that setting globally the output of a transformer to pandas lead to the + right results.""" + try: + import pandas as pd + except ImportError: + raise SkipTest( + "pandas is not installed: not checking column name consistency for pandas" + ) + + tags = transformer_orig._get_tags() + if "2darray" not in tags["X_types"] or tags["no_validation"]: + return + + rng = np.random.RandomState(0) + transformer = clone(transformer_orig) + + X = rng.uniform(size=(20, 5)) + X = _enforce_estimator_tags_X(transformer_orig, X) + y = rng.randint(0, 2, size=20) + y = _enforce_estimator_tags_y(transformer_orig, y) + set_random_state(transformer) + + feature_names_in = [f"col{i}" for i in range(X.shape[1])] + df = pd.DataFrame(X, columns=feature_names_in) + + transformer_default = clone(transformer).set_output(transform="default") + outputs_default = _output_from_fit_transform(transformer_default, name, X, df, y) + transformer_pandas = clone(transformer) + try: + with config_context(transform_output="pandas"): + outputs_pandas = _output_from_fit_transform( + transformer_pandas, name, X, df, y + ) + except ValueError as e: + # transformer does not support sparse data + assert str(e) == "Pandas output does not support sparse data.", e + return + + for case in outputs_default: + _check_generated_dataframe( + name, case, outputs_default[case], outputs_pandas[case] + ) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/murmurhash.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/utils/murmurhash.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..221df5f1f4332e1dacb56e64ec1da962ad16ff14 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/murmurhash.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:451f5dae12ddc37a669aa27561bb664bbee60a44ffb4d688d5507e9ac89f5f84 +size 229345 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/parallel.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..48a31ee93d8a0dd65f58805943cc0a220730c0b1 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/parallel.py @@ -0,0 +1,123 @@ +"""Module that customize joblib tools for scikit-learn usage.""" + +import functools +import warnings +from functools import update_wrapper + +import joblib + +from .._config import config_context, get_config + + +def _with_config(delayed_func, config): + """Helper function that intends to attach a config to a delayed function.""" + if hasattr(delayed_func, "with_config"): + return delayed_func.with_config(config) + else: + warnings.warn( + "`sklearn.utils.parallel.Parallel` needs to be used in " + "conjunction with `sklearn.utils.parallel.delayed` instead of " + "`joblib.delayed` to correctly propagate the scikit-learn " + "configuration to the joblib workers.", + UserWarning, + ) + return delayed_func + + +class Parallel(joblib.Parallel): + """Tweak of :class:`joblib.Parallel` that propagates the scikit-learn configuration. + + This subclass of :class:`joblib.Parallel` ensures that the active configuration + (thread-local) of scikit-learn is propagated to the parallel workers for the + duration of the execution of the parallel tasks. + + The API does not change and you can refer to :class:`joblib.Parallel` + documentation for more details. + + .. versionadded:: 1.3 + """ + + def __call__(self, iterable): + """Dispatch the tasks and return the results. + + Parameters + ---------- + iterable : iterable + Iterable containing tuples of (delayed_function, args, kwargs) that should + be consumed. + + Returns + ------- + results : list + List of results of the tasks. + """ + # Capture the thread-local scikit-learn configuration at the time + # Parallel.__call__ is issued since the tasks can be dispatched + # in a different thread depending on the backend and on the value of + # pre_dispatch and n_jobs. + config = get_config() + iterable_with_config = ( + (_with_config(delayed_func, config), args, kwargs) + for delayed_func, args, kwargs in iterable + ) + return super().__call__(iterable_with_config) + + +# remove when https://github.com/joblib/joblib/issues/1071 is fixed +def delayed(function): + """Decorator used to capture the arguments of a function. + + This alternative to `joblib.delayed` is meant to be used in conjunction + with `sklearn.utils.parallel.Parallel`. The latter captures the the scikit- + learn configuration by calling `sklearn.get_config()` in the current + thread, prior to dispatching the first task. The captured configuration is + then propagated and enabled for the duration of the execution of the + delayed function in the joblib workers. + + .. versionchanged:: 1.3 + `delayed` was moved from `sklearn.utils.fixes` to `sklearn.utils.parallel` + in scikit-learn 1.3. + + Parameters + ---------- + function : callable + The function to be delayed. + + Returns + ------- + output: tuple + Tuple containing the delayed function, the positional arguments, and the + keyword arguments. + """ + + @functools.wraps(function) + def delayed_function(*args, **kwargs): + return _FuncWrapper(function), args, kwargs + + return delayed_function + + +class _FuncWrapper: + """Load the global configuration before calling the function.""" + + def __init__(self, function): + self.function = function + update_wrapper(self, self.function) + + def with_config(self, config): + self.config = config + return self + + def __call__(self, *args, **kwargs): + config = getattr(self, "config", None) + if config is None: + warnings.warn( + "`sklearn.utils.parallel.delayed` should be used with " + "`sklearn.utils.parallel.Parallel` to make it possible to propagate " + "the scikit-learn configuration of the current thread to the " + "joblib workers.", + UserWarning, + ) + config = {} + with config_context(**config): + return self.function(*args, **kwargs) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/sparsefuncs.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/sparsefuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..b9427f208b42ed0fa2ddae8ad09cb024e251f5b9 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/sparsefuncs.py @@ -0,0 +1,627 @@ +# Authors: Manoj Kumar +# Thomas Unterthiner +# Giorgio Patrini +# +# License: BSD 3 clause +import scipy.sparse as sp +import numpy as np + +from .sparsefuncs_fast import ( + csr_mean_variance_axis0 as _csr_mean_var_axis0, + csc_mean_variance_axis0 as _csc_mean_var_axis0, + incr_mean_variance_axis0 as _incr_mean_var_axis0, +) +from ..utils.validation import _check_sample_weight + + +def _raise_typeerror(X): + """Raises a TypeError if X is not a CSR or CSC matrix""" + input_type = X.format if sp.issparse(X) else type(X) + err = "Expected a CSR or CSC sparse matrix, got %s." % input_type + raise TypeError(err) + + +def _raise_error_wrong_axis(axis): + if axis not in (0, 1): + raise ValueError( + "Unknown axis value: %d. Use 0 for rows, or 1 for columns" % axis + ) + + +def inplace_csr_column_scale(X, scale): + """Inplace column scaling of a CSR matrix. + + Scale each feature of the data matrix by multiplying with specific scale + provided by the caller assuming a (n_samples, n_features) shape. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix to normalize using the variance of the features. + It should be of CSR format. + + scale : ndarray of shape (n_features,), dtype={np.float32, np.float64} + Array of precomputed feature-wise values to use for scaling. + """ + assert scale.shape[0] == X.shape[1] + X.data *= scale.take(X.indices, mode="clip") + + +def inplace_csr_row_scale(X, scale): + """Inplace row scaling of a CSR matrix. + + Scale each sample of the data matrix by multiplying with specific scale + provided by the caller assuming a (n_samples, n_features) shape. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix to be scaled. It should be of CSR format. + + scale : ndarray of float of shape (n_samples,) + Array of precomputed sample-wise values to use for scaling. + """ + assert scale.shape[0] == X.shape[0] + X.data *= np.repeat(scale, np.diff(X.indptr)) + + +def mean_variance_axis(X, axis, weights=None, return_sum_weights=False): + """Compute mean and variance along an axis on a CSR or CSC matrix. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Input data. It can be of CSR or CSC format. + + axis : {0, 1} + Axis along which the axis should be computed. + + weights : ndarray of shape (n_samples,) or (n_features,), default=None + If axis is set to 0 shape is (n_samples,) or + if axis is set to 1 shape is (n_features,). + If it is set to None, then samples are equally weighted. + + .. versionadded:: 0.24 + + return_sum_weights : bool, default=False + If True, returns the sum of weights seen for each feature + if `axis=0` or each sample if `axis=1`. + + .. versionadded:: 0.24 + + Returns + ------- + + means : ndarray of shape (n_features,), dtype=floating + Feature-wise means. + + variances : ndarray of shape (n_features,), dtype=floating + Feature-wise variances. + + sum_weights : ndarray of shape (n_features,), dtype=floating + Returned if `return_sum_weights` is `True`. + """ + _raise_error_wrong_axis(axis) + + if isinstance(X, sp.csr_matrix): + if axis == 0: + return _csr_mean_var_axis0( + X, weights=weights, return_sum_weights=return_sum_weights + ) + else: + return _csc_mean_var_axis0( + X.T, weights=weights, return_sum_weights=return_sum_weights + ) + elif isinstance(X, sp.csc_matrix): + if axis == 0: + return _csc_mean_var_axis0( + X, weights=weights, return_sum_weights=return_sum_weights + ) + else: + return _csr_mean_var_axis0( + X.T, weights=weights, return_sum_weights=return_sum_weights + ) + else: + _raise_typeerror(X) + + +def incr_mean_variance_axis(X, *, axis, last_mean, last_var, last_n, weights=None): + """Compute incremental mean and variance along an axis on a CSR or CSC matrix. + + last_mean, last_var are the statistics computed at the last step by this + function. Both must be initialized to 0-arrays of the proper size, i.e. + the number of features in X. last_n is the number of samples encountered + until now. + + Parameters + ---------- + X : CSR or CSC sparse matrix of shape (n_samples, n_features) + Input data. + + axis : {0, 1} + Axis along which the axis should be computed. + + last_mean : ndarray of shape (n_features,) or (n_samples,), dtype=floating + Array of means to update with the new data X. + Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1. + + last_var : ndarray of shape (n_features,) or (n_samples,), dtype=floating + Array of variances to update with the new data X. + Should be of shape (n_features,) if axis=0 or (n_samples,) if axis=1. + + last_n : float or ndarray of shape (n_features,) or (n_samples,), \ + dtype=floating + Sum of the weights seen so far, excluding the current weights + If not float, it should be of shape (n_features,) if + axis=0 or (n_samples,) if axis=1. If float it corresponds to + having same weights for all samples (or features). + + weights : ndarray of shape (n_samples,) or (n_features,), default=None + If axis is set to 0 shape is (n_samples,) or + if axis is set to 1 shape is (n_features,). + If it is set to None, then samples are equally weighted. + + .. versionadded:: 0.24 + + Returns + ------- + means : ndarray of shape (n_features,) or (n_samples,), dtype=floating + Updated feature-wise means if axis = 0 or + sample-wise means if axis = 1. + + variances : ndarray of shape (n_features,) or (n_samples,), dtype=floating + Updated feature-wise variances if axis = 0 or + sample-wise variances if axis = 1. + + n : ndarray of shape (n_features,) or (n_samples,), dtype=integral + Updated number of seen samples per feature if axis=0 + or number of seen features per sample if axis=1. + + If weights is not None, n is a sum of the weights of the seen + samples or features instead of the actual number of seen + samples or features. + + Notes + ----- + NaNs are ignored in the algorithm. + """ + _raise_error_wrong_axis(axis) + + if not isinstance(X, (sp.csr_matrix, sp.csc_matrix)): + _raise_typeerror(X) + + if np.size(last_n) == 1: + last_n = np.full(last_mean.shape, last_n, dtype=last_mean.dtype) + + if not (np.size(last_mean) == np.size(last_var) == np.size(last_n)): + raise ValueError("last_mean, last_var, last_n do not have the same shapes.") + + if axis == 1: + if np.size(last_mean) != X.shape[0]: + raise ValueError( + "If axis=1, then last_mean, last_n, last_var should be of " + f"size n_samples {X.shape[0]} (Got {np.size(last_mean)})." + ) + else: # axis == 0 + if np.size(last_mean) != X.shape[1]: + raise ValueError( + "If axis=0, then last_mean, last_n, last_var should be of " + f"size n_features {X.shape[1]} (Got {np.size(last_mean)})." + ) + + X = X.T if axis == 1 else X + + if weights is not None: + weights = _check_sample_weight(weights, X, dtype=X.dtype) + + return _incr_mean_var_axis0( + X, last_mean=last_mean, last_var=last_var, last_n=last_n, weights=weights + ) + + +def inplace_column_scale(X, scale): + """Inplace column scaling of a CSC/CSR matrix. + + Scale each feature of the data matrix by multiplying with specific scale + provided by the caller assuming a (n_samples, n_features) shape. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix to normalize using the variance of the features. It should be + of CSC or CSR format. + + scale : ndarray of shape (n_features,), dtype={np.float32, np.float64} + Array of precomputed feature-wise values to use for scaling. + """ + if isinstance(X, sp.csc_matrix): + inplace_csr_row_scale(X.T, scale) + elif isinstance(X, sp.csr_matrix): + inplace_csr_column_scale(X, scale) + else: + _raise_typeerror(X) + + +def inplace_row_scale(X, scale): + """Inplace row scaling of a CSR or CSC matrix. + + Scale each row of the data matrix by multiplying with specific scale + provided by the caller assuming a (n_samples, n_features) shape. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix to be scaled. It should be of CSR or CSC format. + + scale : ndarray of shape (n_features,), dtype={np.float32, np.float64} + Array of precomputed sample-wise values to use for scaling. + """ + if isinstance(X, sp.csc_matrix): + inplace_csr_column_scale(X.T, scale) + elif isinstance(X, sp.csr_matrix): + inplace_csr_row_scale(X, scale) + else: + _raise_typeerror(X) + + +def inplace_swap_row_csc(X, m, n): + """Swap two rows of a CSC matrix in-place. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix whose two rows are to be swapped. It should be of + CSC format. + + m : int + Index of the row of X to be swapped. + + n : int + Index of the row of X to be swapped. + """ + for t in [m, n]: + if isinstance(t, np.ndarray): + raise TypeError("m and n should be valid integers") + + if m < 0: + m += X.shape[0] + if n < 0: + n += X.shape[0] + + m_mask = X.indices == m + X.indices[X.indices == n] = m + X.indices[m_mask] = n + + +def inplace_swap_row_csr(X, m, n): + """Swap two rows of a CSR matrix in-place. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix whose two rows are to be swapped. It should be of + CSR format. + + m : int + Index of the row of X to be swapped. + + n : int + Index of the row of X to be swapped. + """ + for t in [m, n]: + if isinstance(t, np.ndarray): + raise TypeError("m and n should be valid integers") + + if m < 0: + m += X.shape[0] + if n < 0: + n += X.shape[0] + + # The following swapping makes life easier since m is assumed to be the + # smaller integer below. + if m > n: + m, n = n, m + + indptr = X.indptr + m_start = indptr[m] + m_stop = indptr[m + 1] + n_start = indptr[n] + n_stop = indptr[n + 1] + nz_m = m_stop - m_start + nz_n = n_stop - n_start + + if nz_m != nz_n: + # Modify indptr first + X.indptr[m + 2 : n] += nz_n - nz_m + X.indptr[m + 1] = m_start + nz_n + X.indptr[n] = n_stop - nz_m + + X.indices = np.concatenate( + [ + X.indices[:m_start], + X.indices[n_start:n_stop], + X.indices[m_stop:n_start], + X.indices[m_start:m_stop], + X.indices[n_stop:], + ] + ) + X.data = np.concatenate( + [ + X.data[:m_start], + X.data[n_start:n_stop], + X.data[m_stop:n_start], + X.data[m_start:m_stop], + X.data[n_stop:], + ] + ) + + +def inplace_swap_row(X, m, n): + """ + Swap two rows of a CSC/CSR matrix in-place. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix whose two rows are to be swapped. It should be of CSR or + CSC format. + + m : int + Index of the row of X to be swapped. + + n : int + Index of the row of X to be swapped. + """ + if isinstance(X, sp.csc_matrix): + inplace_swap_row_csc(X, m, n) + elif isinstance(X, sp.csr_matrix): + inplace_swap_row_csr(X, m, n) + else: + _raise_typeerror(X) + + +def inplace_swap_column(X, m, n): + """ + Swap two columns of a CSC/CSR matrix in-place. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Matrix whose two columns are to be swapped. It should be of + CSR or CSC format. + + m : int + Index of the column of X to be swapped. + + n : int + Index of the column of X to be swapped. + """ + if m < 0: + m += X.shape[1] + if n < 0: + n += X.shape[1] + if isinstance(X, sp.csc_matrix): + inplace_swap_row_csr(X, m, n) + elif isinstance(X, sp.csr_matrix): + inplace_swap_row_csc(X, m, n) + else: + _raise_typeerror(X) + + +def _minor_reduce(X, ufunc): + major_index = np.flatnonzero(np.diff(X.indptr)) + + # reduceat tries casts X.indptr to intp, which errors + # if it is int64 on a 32 bit system. + # Reinitializing prevents this where possible, see #13737 + X = type(X)((X.data, X.indices, X.indptr), shape=X.shape) + value = ufunc.reduceat(X.data, X.indptr[major_index]) + return major_index, value + + +def _min_or_max_axis(X, axis, min_or_max): + N = X.shape[axis] + if N == 0: + raise ValueError("zero-size array to reduction operation") + M = X.shape[1 - axis] + mat = X.tocsc() if axis == 0 else X.tocsr() + mat.sum_duplicates() + major_index, value = _minor_reduce(mat, min_or_max) + not_full = np.diff(mat.indptr)[major_index] < N + value[not_full] = min_or_max(value[not_full], 0) + mask = value != 0 + major_index = np.compress(mask, major_index) + value = np.compress(mask, value) + + if axis == 0: + res = sp.coo_matrix( + (value, (np.zeros(len(value)), major_index)), dtype=X.dtype, shape=(1, M) + ) + else: + res = sp.coo_matrix( + (value, (major_index, np.zeros(len(value)))), dtype=X.dtype, shape=(M, 1) + ) + return res.A.ravel() + + +def _sparse_min_or_max(X, axis, min_or_max): + if axis is None: + if 0 in X.shape: + raise ValueError("zero-size array to reduction operation") + zero = X.dtype.type(0) + if X.nnz == 0: + return zero + m = min_or_max.reduce(X.data.ravel()) + if X.nnz != np.product(X.shape): + m = min_or_max(zero, m) + return m + if axis < 0: + axis += 2 + if (axis == 0) or (axis == 1): + return _min_or_max_axis(X, axis, min_or_max) + else: + raise ValueError("invalid axis, use 0 for rows, or 1 for columns") + + +def _sparse_min_max(X, axis): + return ( + _sparse_min_or_max(X, axis, np.minimum), + _sparse_min_or_max(X, axis, np.maximum), + ) + + +def _sparse_nan_min_max(X, axis): + return (_sparse_min_or_max(X, axis, np.fmin), _sparse_min_or_max(X, axis, np.fmax)) + + +def min_max_axis(X, axis, ignore_nan=False): + """Compute minimium and maximum along an axis on a CSR or CSC matrix. + + Optionally ignore NaN values. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Input data. It should be of CSR or CSC format. + + axis : {0, 1} + Axis along which the axis should be computed. + + ignore_nan : bool, default=False + Ignore or passing through NaN values. + + .. versionadded:: 0.20 + + Returns + ------- + + mins : ndarray of shape (n_features,), dtype={np.float32, np.float64} + Feature-wise minima. + + maxs : ndarray of shape (n_features,), dtype={np.float32, np.float64} + Feature-wise maxima. + """ + if isinstance(X, (sp.csr_matrix, sp.csc_matrix)): + if ignore_nan: + return _sparse_nan_min_max(X, axis=axis) + else: + return _sparse_min_max(X, axis=axis) + else: + _raise_typeerror(X) + + +def count_nonzero(X, axis=None, sample_weight=None): + """A variant of X.getnnz() with extension to weighting on axis 0. + + Useful in efficiently calculating multilabel metrics. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_labels) + Input data. It should be of CSR format. + + axis : {0, 1}, default=None + The axis on which the data is aggregated. + + sample_weight : array-like of shape (n_samples,), default=None + Weight for each row of X. + + Returns + ------- + nnz : int, float, ndarray of shape (n_samples,) or ndarray of shape (n_features,) + Number of non-zero values in the array along a given axis. Otherwise, + the total number of non-zero values in the array is returned. + """ + if axis == -1: + axis = 1 + elif axis == -2: + axis = 0 + elif X.format != "csr": + raise TypeError("Expected CSR sparse format, got {0}".format(X.format)) + + # We rely here on the fact that np.diff(Y.indptr) for a CSR + # will return the number of nonzero entries in each row. + # A bincount over Y.indices will return the number of nonzeros + # in each column. See ``csr_matrix.getnnz`` in scipy >= 0.14. + if axis is None: + if sample_weight is None: + return X.nnz + else: + return np.dot(np.diff(X.indptr), sample_weight) + elif axis == 1: + out = np.diff(X.indptr) + if sample_weight is None: + # astype here is for consistency with axis=0 dtype + return out.astype("intp") + return out * sample_weight + elif axis == 0: + if sample_weight is None: + return np.bincount(X.indices, minlength=X.shape[1]) + else: + weights = np.repeat(sample_weight, np.diff(X.indptr)) + return np.bincount(X.indices, minlength=X.shape[1], weights=weights) + else: + raise ValueError("Unsupported axis: {0}".format(axis)) + + +def _get_median(data, n_zeros): + """Compute the median of data with n_zeros additional zeros. + + This function is used to support sparse matrices; it modifies data + in-place. + """ + n_elems = len(data) + n_zeros + if not n_elems: + return np.nan + n_negative = np.count_nonzero(data < 0) + middle, is_odd = divmod(n_elems, 2) + data.sort() + + if is_odd: + return _get_elem_at_rank(middle, data, n_negative, n_zeros) + + return ( + _get_elem_at_rank(middle - 1, data, n_negative, n_zeros) + + _get_elem_at_rank(middle, data, n_negative, n_zeros) + ) / 2.0 + + +def _get_elem_at_rank(rank, data, n_negative, n_zeros): + """Find the value in data augmented with n_zeros for the given rank""" + if rank < n_negative: + return data[rank] + if rank - n_negative < n_zeros: + return 0 + return data[rank - n_zeros] + + +def csc_median_axis_0(X): + """Find the median across axis 0 of a CSC matrix. + + It is equivalent to doing np.median(X, axis=0). + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + Input data. It should be of CSC format. + + Returns + ------- + median : ndarray of shape (n_features,) + Median. + """ + if not isinstance(X, sp.csc_matrix): + raise TypeError("Expected matrix of CSC format, got %s" % X.format) + + indptr = X.indptr + n_samples, n_features = X.shape + median = np.zeros(n_features) + + for f_ind, (start, end) in enumerate(zip(indptr[:-1], indptr[1:])): + + # Prevent modifying X in place + data = np.copy(X.data[start:end]) + nz = n_samples - data.size + median[f_ind] = _get_median(data, nz) + + return median diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/sparsefuncs_fast.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/utils/sparsefuncs_fast.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d026b5b145670ce41bd91f12d0866b12bf2f6c62 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/sparsefuncs_fast.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8f32d322c5363b535a2176eb47cc8294e945bba0349b3889b2ac4c756618024b +size 732985 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__init__.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/conftest.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..148225a481f69cd1acec70b07363911e98e33ccf --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/conftest.py @@ -0,0 +1,10 @@ +import pytest + +import sklearn + + +@pytest.fixture +def print_changed_only_false(): + sklearn.set_config(print_changed_only=False) + yield + sklearn.set_config(print_changed_only=True) # reset to default diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_arpack.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_arpack.py new file mode 100644 index 0000000000000000000000000000000000000000..ab1d622d51a08eca5ecf526b77d1bbeab17737f6 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_arpack.py @@ -0,0 +1,16 @@ +import pytest +from numpy.testing import assert_allclose + +from sklearn.utils import check_random_state +from sklearn.utils._arpack import _init_arpack_v0 + + +@pytest.mark.parametrize("seed", range(100)) +def test_init_arpack_v0(seed): + # check that the initialization a sampling from an uniform distribution + # where we can fix the random state + size = 1000 + v0 = _init_arpack_v0(size, seed) + + rng = check_random_state(seed) + assert_allclose(v0, rng.uniform(-1, 1, size=size)) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_array_api.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_array_api.py new file mode 100644 index 0000000000000000000000000000000000000000..7318382ae9d66bf67cd0140a27ad1dd6fdc13661 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_array_api.py @@ -0,0 +1,189 @@ +import numpy +from numpy.testing import assert_array_equal +import pytest + +from sklearn.base import BaseEstimator +from sklearn.utils._array_api import get_namespace +from sklearn.utils._array_api import _NumPyApiWrapper +from sklearn.utils._array_api import _ArrayAPIWrapper +from sklearn.utils._array_api import _asarray_with_order +from sklearn.utils._array_api import _convert_to_numpy +from sklearn.utils._array_api import _estimator_with_converted_arrays +from sklearn._config import config_context + +pytestmark = pytest.mark.filterwarnings( + "ignore:The numpy.array_api submodule:UserWarning" +) + + +def test_get_namespace_ndarray(): + """Test get_namespace on NumPy ndarrays.""" + pytest.importorskip("numpy.array_api") + + X_np = numpy.asarray([[1, 2, 3]]) + + # Dispatching on Numpy regardless or the value of array_api_dispatch. + for array_api_dispatch in [True, False]: + with config_context(array_api_dispatch=array_api_dispatch): + xp_out, is_array_api = get_namespace(X_np) + assert not is_array_api + assert isinstance(xp_out, _NumPyApiWrapper) + + +def test_get_namespace_array_api(): + """Test get_namespace for ArrayAPI arrays.""" + xp = pytest.importorskip("numpy.array_api") + + X_np = numpy.asarray([[1, 2, 3]]) + X_xp = xp.asarray(X_np) + with config_context(array_api_dispatch=True): + xp_out, is_array_api = get_namespace(X_xp) + assert is_array_api + assert isinstance(xp_out, _ArrayAPIWrapper) + + # check errors + with pytest.raises(ValueError, match="Multiple namespaces"): + get_namespace(X_np, X_xp) + + with pytest.raises(ValueError, match="Unrecognized array input"): + get_namespace(1) + + +class _AdjustableNameAPITestWrapper(_ArrayAPIWrapper): + """API wrapper that has an adjustable name. Used for testing.""" + + def __init__(self, array_namespace, name): + super().__init__(array_namespace=array_namespace) + self.__name__ = name + + +def test_array_api_wrapper_astype(): + """Test _ArrayAPIWrapper for ArrayAPIs that is not NumPy.""" + numpy_array_api = pytest.importorskip("numpy.array_api") + xp_ = _AdjustableNameAPITestWrapper(numpy_array_api, "wrapped_numpy.array_api") + xp = _ArrayAPIWrapper(xp_) + + X = xp.asarray(([[1, 2, 3], [3, 4, 5]]), dtype=xp.float64) + X_converted = xp.astype(X, xp.float32) + assert X_converted.dtype == xp.float32 + + X_converted = xp.asarray(X, dtype=xp.float32) + assert X_converted.dtype == xp.float32 + + +def test_array_api_wrapper_take_for_numpy_api(): + """Test that fast path is called for numpy.array_api.""" + numpy_array_api = pytest.importorskip("numpy.array_api") + # USe the same name as numpy.array_api + xp_ = _AdjustableNameAPITestWrapper(numpy_array_api, "numpy.array_api") + xp = _ArrayAPIWrapper(xp_) + + X = xp.asarray(([[1, 2, 3], [3, 4, 5]]), dtype=xp.float64) + X_take = xp.take(X, xp.asarray([1]), axis=0) + assert hasattr(X_take, "__array_namespace__") + assert_array_equal(X_take, numpy.take(X, [1], axis=0)) + + +def test_array_api_wrapper_take(): + """Test _ArrayAPIWrapper API for take.""" + numpy_array_api = pytest.importorskip("numpy.array_api") + xp_ = _AdjustableNameAPITestWrapper(numpy_array_api, "wrapped_numpy.array_api") + xp = _ArrayAPIWrapper(xp_) + + # Check take compared to NumPy's with axis=0 + X_1d = xp.asarray([1, 2, 3], dtype=xp.float64) + X_take = xp.take(X_1d, xp.asarray([1]), axis=0) + assert hasattr(X_take, "__array_namespace__") + assert_array_equal(X_take, numpy.take(X_1d, [1], axis=0)) + + X = xp.asarray(([[1, 2, 3], [3, 4, 5]]), dtype=xp.float64) + X_take = xp.take(X, xp.asarray([0]), axis=0) + assert hasattr(X_take, "__array_namespace__") + assert_array_equal(X_take, numpy.take(X, [0], axis=0)) + + # Check take compared to NumPy's with axis=1 + X_take = xp.take(X, xp.asarray([0, 2]), axis=1) + assert hasattr(X_take, "__array_namespace__") + assert_array_equal(X_take, numpy.take(X, [0, 2], axis=1)) + + with pytest.raises(ValueError, match=r"Only axis in \(0, 1\) is supported"): + xp.take(X, xp.asarray([0]), axis=2) + + with pytest.raises(ValueError, match=r"Only X.ndim in \(1, 2\) is supported"): + xp.take(xp.asarray([[[0]]]), xp.asarray([0]), axis=0) + + +@pytest.mark.parametrize("is_array_api", [True, False]) +def test_asarray_with_order(is_array_api): + """Test _asarray_with_order passes along order for NumPy arrays.""" + if is_array_api: + xp = pytest.importorskip("numpy.array_api") + else: + xp = numpy + + X = xp.asarray([1.2, 3.4, 5.1]) + X_new = _asarray_with_order(X, order="F") + + X_new_np = numpy.asarray(X_new) + assert X_new_np.flags["F_CONTIGUOUS"] + + +def test_asarray_with_order_ignored(): + """Test _asarray_with_order ignores order for Generic ArrayAPI.""" + xp = pytest.importorskip("numpy.array_api") + xp_ = _AdjustableNameAPITestWrapper(xp, "wrapped.array_api") + + X = numpy.asarray([[1.2, 3.4, 5.1], [3.4, 5.5, 1.2]], order="C") + X = xp_.asarray(X) + + X_new = _asarray_with_order(X, order="F", xp=xp_) + + X_new_np = numpy.asarray(X_new) + assert X_new_np.flags["C_CONTIGUOUS"] + assert not X_new_np.flags["F_CONTIGUOUS"] + + +def test_convert_to_numpy_error(): + """Test convert to numpy errors for unsupported namespaces.""" + xp = pytest.importorskip("numpy.array_api") + xp_ = _AdjustableNameAPITestWrapper(xp, "wrapped.array_api") + + X = xp_.asarray([1.2, 3.4]) + + with pytest.raises(ValueError, match="Supported namespaces are:"): + _convert_to_numpy(X, xp=xp_) + + +class SimpleEstimator(BaseEstimator): + def fit(self, X, y=None): + self.X_ = X + self.n_features_ = X.shape[0] + return self + + +@pytest.mark.parametrize("array_namespace", ["numpy.array_api", "cupy.array_api"]) +def test_convert_estimator_to_ndarray(array_namespace): + """Convert estimator attributes to ndarray.""" + xp = pytest.importorskip(array_namespace) + + if array_namespace == "numpy.array_api": + converter = lambda array: numpy.asarray(array) # noqa + else: # pragma: no cover + converter = lambda array: array._array.get() # noqa + + X = xp.asarray([[1.3, 4.5]]) + est = SimpleEstimator().fit(X) + + new_est = _estimator_with_converted_arrays(est, converter) + assert isinstance(new_est.X_, numpy.ndarray) + + +def test_convert_estimator_to_array_api(): + """Convert estimator attributes to ArrayAPI arrays.""" + xp = pytest.importorskip("numpy.array_api") + + X_np = numpy.asarray([[1.3, 4.5]]) + est = SimpleEstimator().fit(X_np) + + new_est = _estimator_with_converted_arrays(est, lambda array: xp.asarray(array)) + assert hasattr(new_est.X_, "__array_namespace__") diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_arrayfuncs.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_arrayfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..5c43e480d395cca571960804885989243d55178b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_arrayfuncs.py @@ -0,0 +1,26 @@ +import pytest +import numpy as np + +from sklearn.utils._testing import assert_allclose +from sklearn.utils.arrayfuncs import min_pos + + +def test_min_pos(): + # Check that min_pos returns a positive value and that it's consistent + # between float and double + X = np.random.RandomState(0).randn(100) + + min_double = min_pos(X) + min_float = min_pos(X.astype(np.float32)) + + assert_allclose(min_double, min_float) + assert min_double >= 0 + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_min_pos_no_positive(dtype): + # Check that the return value of min_pos is the maximum representable + # value of the input dtype when all input elements are <= 0 (#19328) + X = np.full(100, -1.0).astype(dtype, copy=False) + + assert min_pos(X) == np.finfo(dtype).max diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_class_weight.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_class_weight.py new file mode 100644 index 0000000000000000000000000000000000000000..61f43c69050d164c7e82d990f70b37b47cbedcfb --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_class_weight.py @@ -0,0 +1,292 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose +from scipy import sparse + +from sklearn.datasets import make_blobs +from sklearn.linear_model import LogisticRegression +from sklearn.tree import DecisionTreeClassifier + +from sklearn.utils.class_weight import compute_class_weight +from sklearn.utils.class_weight import compute_sample_weight +from sklearn.utils._testing import assert_array_almost_equal +from sklearn.utils._testing import assert_almost_equal + + +def test_compute_class_weight(): + # Test (and demo) compute_class_weight. + y = np.asarray([2, 2, 2, 3, 3, 4]) + classes = np.unique(y) + + cw = compute_class_weight("balanced", classes=classes, y=y) + # total effect of samples is preserved + class_counts = np.bincount(y)[2:] + assert_almost_equal(np.dot(cw, class_counts), y.shape[0]) + assert cw[0] < cw[1] < cw[2] + + +def test_compute_class_weight_not_present(): + # Raise error when y does not contain all class labels + classes = np.arange(4) + y = np.asarray([0, 0, 0, 1, 1, 2]) + with pytest.raises(ValueError): + compute_class_weight("balanced", classes=classes, y=y) + # Fix exception in error message formatting when missing label is a string + # https://github.com/scikit-learn/scikit-learn/issues/8312 + with pytest.raises( + ValueError, match=r"The classes, \[0, 1, 2, 3\], are not in class_weight" + ): + compute_class_weight({"label_not_present": 1.0}, classes=classes, y=y) + # Raise error when y has items not in classes + classes = np.arange(2) + with pytest.raises(ValueError): + compute_class_weight("balanced", classes=classes, y=y) + with pytest.raises(ValueError): + compute_class_weight({0: 1.0, 1: 2.0}, classes=classes, y=y) + + # y contains a unweighted class that is not in class_weights + classes = np.asarray(["cat", "dog"]) + y = np.asarray(["dog", "cat", "dog"]) + class_weights = {"dogs": 3, "cat": 2} + msg = r"The classes, \['dog'\], are not in class_weight" + + with pytest.raises(ValueError, match=msg): + compute_class_weight(class_weights, classes=classes, y=y) + + +def test_compute_class_weight_dict(): + classes = np.arange(3) + class_weights = {0: 1.0, 1: 2.0, 2: 3.0} + y = np.asarray([0, 0, 1, 2]) + cw = compute_class_weight(class_weights, classes=classes, y=y) + + # When the user specifies class weights, compute_class_weights should just + # return them. + assert_array_almost_equal(np.asarray([1.0, 2.0, 3.0]), cw) + + # When a class weight is specified that isn't in classes, the weight is ignored + class_weights = {0: 1.0, 1: 2.0, 2: 3.0, 4: 1.5} + cw = compute_class_weight(class_weights, classes=classes, y=y) + assert_allclose([1.0, 2.0, 3.0], cw) + + class_weights = {-1: 5.0, 0: 4.0, 1: 2.0, 2: 3.0} + cw = compute_class_weight(class_weights, classes=classes, y=y) + assert_allclose([4.0, 2.0, 3.0], cw) + + +def test_compute_class_weight_invariance(): + # Test that results with class_weight="balanced" is invariant wrt + # class imbalance if the number of samples is identical. + # The test uses a balanced two class dataset with 100 datapoints. + # It creates three versions, one where class 1 is duplicated + # resulting in 150 points of class 1 and 50 of class 0, + # one where there are 50 points in class 1 and 150 in class 0, + # and one where there are 100 points of each class (this one is balanced + # again). + # With balancing class weights, all three should give the same model. + X, y = make_blobs(centers=2, random_state=0) + # create dataset where class 1 is duplicated twice + X_1 = np.vstack([X] + [X[y == 1]] * 2) + y_1 = np.hstack([y] + [y[y == 1]] * 2) + # create dataset where class 0 is duplicated twice + X_0 = np.vstack([X] + [X[y == 0]] * 2) + y_0 = np.hstack([y] + [y[y == 0]] * 2) + # duplicate everything + X_ = np.vstack([X] * 2) + y_ = np.hstack([y] * 2) + # results should be identical + logreg1 = LogisticRegression(class_weight="balanced").fit(X_1, y_1) + logreg0 = LogisticRegression(class_weight="balanced").fit(X_0, y_0) + logreg = LogisticRegression(class_weight="balanced").fit(X_, y_) + assert_array_almost_equal(logreg1.coef_, logreg0.coef_) + assert_array_almost_equal(logreg.coef_, logreg0.coef_) + + +def test_compute_class_weight_balanced_negative(): + # Test compute_class_weight when labels are negative + # Test with balanced class labels. + classes = np.array([-2, -1, 0]) + y = np.asarray([-1, -1, 0, 0, -2, -2]) + + cw = compute_class_weight("balanced", classes=classes, y=y) + assert len(cw) == len(classes) + assert_array_almost_equal(cw, np.array([1.0, 1.0, 1.0])) + + # Test with unbalanced class labels. + y = np.asarray([-1, 0, 0, -2, -2, -2]) + + cw = compute_class_weight("balanced", classes=classes, y=y) + assert len(cw) == len(classes) + class_counts = np.bincount(y + 2) + assert_almost_equal(np.dot(cw, class_counts), y.shape[0]) + assert_array_almost_equal(cw, [2.0 / 3, 2.0, 1.0]) + + +def test_compute_class_weight_balanced_unordered(): + # Test compute_class_weight when classes are unordered + classes = np.array([1, 0, 3]) + y = np.asarray([1, 0, 0, 3, 3, 3]) + + cw = compute_class_weight("balanced", classes=classes, y=y) + class_counts = np.bincount(y)[classes] + assert_almost_equal(np.dot(cw, class_counts), y.shape[0]) + assert_array_almost_equal(cw, [2.0, 1.0, 2.0 / 3]) + + +def test_compute_class_weight_default(): + # Test for the case where no weight is given for a present class. + # Current behaviour is to assign the unweighted classes a weight of 1. + y = np.asarray([2, 2, 2, 3, 3, 4]) + classes = np.unique(y) + classes_len = len(classes) + + # Test for non specified weights + cw = compute_class_weight(None, classes=classes, y=y) + assert len(cw) == classes_len + assert_array_almost_equal(cw, np.ones(3)) + + # Tests for partly specified weights + cw = compute_class_weight({2: 1.5}, classes=classes, y=y) + assert len(cw) == classes_len + assert_array_almost_equal(cw, [1.5, 1.0, 1.0]) + + cw = compute_class_weight({2: 1.5, 4: 0.5}, classes=classes, y=y) + assert len(cw) == classes_len + assert_array_almost_equal(cw, [1.5, 1.0, 0.5]) + + +def test_compute_sample_weight(): + # Test (and demo) compute_sample_weight. + # Test with balanced classes + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("balanced", y) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with user-defined weights + sample_weight = compute_sample_weight({1: 2, 2: 1}, y) + assert_array_almost_equal(sample_weight, [2.0, 2.0, 2.0, 1.0, 1.0, 1.0]) + + # Test with column vector of balanced classes + y = np.asarray([[1], [1], [1], [2], [2], [2]]) + sample_weight = compute_sample_weight("balanced", y) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with unbalanced classes + y = np.asarray([1, 1, 1, 2, 2, 2, 3]) + sample_weight = compute_sample_weight("balanced", y) + expected_balanced = np.array( + [0.7777, 0.7777, 0.7777, 0.7777, 0.7777, 0.7777, 2.3333] + ) + assert_array_almost_equal(sample_weight, expected_balanced, decimal=4) + + # Test with `None` weights + sample_weight = compute_sample_weight(None, y) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with multi-output of balanced classes + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + sample_weight = compute_sample_weight("balanced", y) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with multi-output with user-defined weights + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + sample_weight = compute_sample_weight([{1: 2, 2: 1}, {0: 1, 1: 2}], y) + assert_array_almost_equal(sample_weight, [2.0, 2.0, 2.0, 2.0, 2.0, 2.0]) + + # Test with multi-output of unbalanced classes + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [3, -1]]) + sample_weight = compute_sample_weight("balanced", y) + assert_array_almost_equal(sample_weight, expected_balanced**2, decimal=3) + + +def test_compute_sample_weight_with_subsample(): + # Test compute_sample_weight with subsamples specified. + # Test with balanced classes and all samples present + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("balanced", y, indices=range(6)) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with column vector of balanced classes and all samples present + y = np.asarray([[1], [1], [1], [2], [2], [2]]) + sample_weight = compute_sample_weight("balanced", y, indices=range(6)) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + + # Test with a subsample + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("balanced", y, indices=range(4)) + assert_array_almost_equal(sample_weight, [2.0 / 3, 2.0 / 3, 2.0 / 3, 2.0, 2.0, 2.0]) + + # Test with a bootstrap subsample + y = np.asarray([1, 1, 1, 2, 2, 2]) + sample_weight = compute_sample_weight("balanced", y, indices=[0, 1, 1, 2, 2, 3]) + expected_balanced = np.asarray([0.6, 0.6, 0.6, 3.0, 3.0, 3.0]) + assert_array_almost_equal(sample_weight, expected_balanced) + + # Test with a bootstrap subsample for multi-output + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + sample_weight = compute_sample_weight("balanced", y, indices=[0, 1, 1, 2, 2, 3]) + assert_array_almost_equal(sample_weight, expected_balanced**2) + + # Test with a missing class + y = np.asarray([1, 1, 1, 2, 2, 2, 3]) + sample_weight = compute_sample_weight("balanced", y, indices=range(6)) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]) + + # Test with a missing class for multi-output + y = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1], [2, 2]]) + sample_weight = compute_sample_weight("balanced", y, indices=range(6)) + assert_array_almost_equal(sample_weight, [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]) + + +def test_compute_sample_weight_errors(): + # Test compute_sample_weight raises errors expected. + # Invalid preset string + y = np.asarray([1, 1, 1, 2, 2, 2]) + y_ = np.asarray([[1, 0], [1, 0], [1, 0], [2, 1], [2, 1], [2, 1]]) + + with pytest.raises(ValueError): + compute_sample_weight("ni", y) + with pytest.raises(ValueError): + compute_sample_weight("ni", y, indices=range(4)) + with pytest.raises(ValueError): + compute_sample_weight("ni", y_) + with pytest.raises(ValueError): + compute_sample_weight("ni", y_, indices=range(4)) + + # Not "balanced" for subsample + with pytest.raises(ValueError): + compute_sample_weight({1: 2, 2: 1}, y, indices=range(4)) + + # Not a list or preset for multi-output + with pytest.raises(ValueError): + compute_sample_weight({1: 2, 2: 1}, y_) + + # Incorrect length list for multi-output + with pytest.raises(ValueError): + compute_sample_weight([{1: 2, 2: 1}], y_) + + +def test_compute_sample_weight_more_than_32(): + # Non-regression smoke test for #12146 + y = np.arange(50) # more than 32 distinct classes + indices = np.arange(50) # use subsampling + weight = compute_sample_weight("balanced", y, indices=indices) + assert_array_almost_equal(weight, np.ones(y.shape[0])) + + +def test_class_weight_does_not_contains_more_classses(): + """Check that class_weight can contain more labels than in y. + + Non-regression test for #22413 + """ + tree = DecisionTreeClassifier(class_weight={0: 1, 1: 10, 2: 20}) + + # Does not raise + tree.fit([[0, 0, 1], [1, 0, 1], [1, 2, 0]], [0, 0, 1]) + + +def test_compute_sample_weight_sparse(): + """Check that we can compute weight for sparse `y`.""" + y = sparse.csc_matrix(np.asarray([0, 1, 1])).T + sample_weight = compute_sample_weight("balanced", y) + assert_allclose(sample_weight, [1.5, 0.75, 0.75]) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_cython_blas.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_cython_blas.py new file mode 100644 index 0000000000000000000000000000000000000000..1b311f5160db5e33abf2a754c8cc29f4992ed96d --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_cython_blas.py @@ -0,0 +1,231 @@ +import pytest + +import numpy as np + +from sklearn.utils._testing import assert_allclose +from sklearn.utils._cython_blas import _dot_memview +from sklearn.utils._cython_blas import _asum_memview +from sklearn.utils._cython_blas import _axpy_memview +from sklearn.utils._cython_blas import _nrm2_memview +from sklearn.utils._cython_blas import _copy_memview +from sklearn.utils._cython_blas import _scal_memview +from sklearn.utils._cython_blas import _rotg_memview +from sklearn.utils._cython_blas import _rot_memview +from sklearn.utils._cython_blas import _gemv_memview +from sklearn.utils._cython_blas import _ger_memview +from sklearn.utils._cython_blas import _gemm_memview +from sklearn.utils._cython_blas import RowMajor, ColMajor +from sklearn.utils._cython_blas import Trans, NoTrans + + +def _numpy_to_cython(dtype): + cython = pytest.importorskip("cython") + if dtype == np.float32: + return cython.float + elif dtype == np.float64: + return cython.double + + +RTOL = {np.float32: 1e-6, np.float64: 1e-12} +ORDER = {RowMajor: "C", ColMajor: "F"} + + +def _no_op(x): + return x + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_dot(dtype): + dot = _dot_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + y = rng.random_sample(10).astype(dtype, copy=False) + + expected = x.dot(y) + actual = dot(x, y) + + assert_allclose(actual, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_asum(dtype): + asum = _asum_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + + expected = np.abs(x).sum() + actual = asum(x) + + assert_allclose(actual, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_axpy(dtype): + axpy = _axpy_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + y = rng.random_sample(10).astype(dtype, copy=False) + alpha = 2.5 + + expected = alpha * x + y + axpy(alpha, x, y) + + assert_allclose(y, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_nrm2(dtype): + nrm2 = _nrm2_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + + expected = np.linalg.norm(x) + actual = nrm2(x) + + assert_allclose(actual, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_copy(dtype): + copy = _copy_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + y = np.empty_like(x) + + expected = x.copy() + copy(x, y) + + assert_allclose(y, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_scal(dtype): + scal = _scal_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + alpha = 2.5 + + expected = alpha * x + scal(alpha, x) + + assert_allclose(x, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_rotg(dtype): + rotg = _rotg_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + a = dtype(rng.randn()) + b = dtype(rng.randn()) + c, s = 0.0, 0.0 + + def expected_rotg(a, b): + roe = a if abs(a) > abs(b) else b + if a == 0 and b == 0: + c, s, r, z = (1, 0, 0, 0) + else: + r = np.sqrt(a**2 + b**2) * (1 if roe >= 0 else -1) + c, s = a / r, b / r + z = s if roe == a else (1 if c == 0 else 1 / c) + return r, z, c, s + + expected = expected_rotg(a, b) + actual = rotg(a, b, c, s) + + assert_allclose(actual, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_rot(dtype): + rot = _rot_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + y = rng.random_sample(10).astype(dtype, copy=False) + c = dtype(rng.randn()) + s = dtype(rng.randn()) + + expected_x = c * x + s * y + expected_y = c * y - s * x + + rot(x, y, c, s) + + assert_allclose(x, expected_x) + assert_allclose(y, expected_y) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize( + "opA, transA", [(_no_op, NoTrans), (np.transpose, Trans)], ids=["NoTrans", "Trans"] +) +@pytest.mark.parametrize("order", [RowMajor, ColMajor], ids=["RowMajor", "ColMajor"]) +def test_gemv(dtype, opA, transA, order): + gemv = _gemv_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + A = np.asarray( + opA(rng.random_sample((20, 10)).astype(dtype, copy=False)), order=ORDER[order] + ) + x = rng.random_sample(10).astype(dtype, copy=False) + y = rng.random_sample(20).astype(dtype, copy=False) + alpha, beta = 2.5, -0.5 + + expected = alpha * opA(A).dot(x) + beta * y + gemv(transA, alpha, A, x, beta, y) + + assert_allclose(y, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize("order", [RowMajor, ColMajor], ids=["RowMajor", "ColMajor"]) +def test_ger(dtype, order): + ger = _ger_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + x = rng.random_sample(10).astype(dtype, copy=False) + y = rng.random_sample(20).astype(dtype, copy=False) + A = np.asarray( + rng.random_sample((10, 20)).astype(dtype, copy=False), order=ORDER[order] + ) + alpha = 2.5 + + expected = alpha * np.outer(x, y) + A + ger(alpha, x, y, A) + + assert_allclose(A, expected, rtol=RTOL[dtype]) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize( + "opB, transB", [(_no_op, NoTrans), (np.transpose, Trans)], ids=["NoTrans", "Trans"] +) +@pytest.mark.parametrize( + "opA, transA", [(_no_op, NoTrans), (np.transpose, Trans)], ids=["NoTrans", "Trans"] +) +@pytest.mark.parametrize("order", [RowMajor, ColMajor], ids=["RowMajor", "ColMajor"]) +def test_gemm(dtype, opA, transA, opB, transB, order): + gemm = _gemm_memview[_numpy_to_cython(dtype)] + + rng = np.random.RandomState(0) + A = np.asarray( + opA(rng.random_sample((30, 10)).astype(dtype, copy=False)), order=ORDER[order] + ) + B = np.asarray( + opB(rng.random_sample((10, 20)).astype(dtype, copy=False)), order=ORDER[order] + ) + C = np.asarray( + rng.random_sample((30, 20)).astype(dtype, copy=False), order=ORDER[order] + ) + alpha, beta = 2.5, -0.5 + + expected = alpha * opA(A).dot(opB(B)) + beta * C + gemm(transA, transB, alpha, A, B, beta, C) + + assert_allclose(C, expected, rtol=RTOL[dtype]) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_estimator_html_repr.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_estimator_html_repr.py new file mode 100644 index 0000000000000000000000000000000000000000..d5bc6aab6ab8b1dbc470f21671cb9d804fb3561c --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_estimator_html_repr.py @@ -0,0 +1,333 @@ +from contextlib import closing +import html +from io import StringIO + +import pytest + +from sklearn import config_context +from sklearn.linear_model import LogisticRegression +from sklearn.neural_network import MLPClassifier +from sklearn.impute import SimpleImputer +from sklearn.decomposition import PCA +from sklearn.decomposition import TruncatedSVD +from sklearn.pipeline import Pipeline +from sklearn.pipeline import FeatureUnion +from sklearn.compose import ColumnTransformer +from sklearn.ensemble import VotingClassifier +from sklearn.feature_selection import SelectPercentile +from sklearn.cluster import Birch +from sklearn.cluster import AgglomerativeClustering +from sklearn.preprocessing import OneHotEncoder +from sklearn.preprocessing import StandardScaler +from sklearn.svm import LinearSVC +from sklearn.svm import LinearSVR +from sklearn.tree import DecisionTreeClassifier +from sklearn.multiclass import OneVsOneClassifier +from sklearn.ensemble import StackingClassifier +from sklearn.ensemble import StackingRegressor +from sklearn.gaussian_process.kernels import ExpSineSquared +from sklearn.kernel_ridge import KernelRidge + +from sklearn.model_selection import RandomizedSearchCV +from sklearn.utils._estimator_html_repr import _write_label_html +from sklearn.utils._estimator_html_repr import _get_visual_block +from sklearn.utils._estimator_html_repr import estimator_html_repr + + +@pytest.mark.parametrize("checked", [True, False]) +def test_write_label_html(checked): + # Test checking logic and labeling + name = "LogisticRegression" + tool_tip = "hello-world" + + with closing(StringIO()) as out: + _write_label_html(out, name, tool_tip, checked=checked) + html_label = out.getvalue() + assert "LogisticRegression" in html_label + assert html_label.startswith('
') + assert "
hello-world
" in html_label + if checked: + assert "checked>" in html_label + + +@pytest.mark.parametrize("est", ["passthrough", "drop", None]) +def test_get_visual_block_single_str_none(est): + # Test estimators that are represented by strings + est_html_info = _get_visual_block(est) + assert est_html_info.kind == "single" + assert est_html_info.estimators == est + assert est_html_info.names == str(est) + assert est_html_info.name_details == str(est) + + +def test_get_visual_block_single_estimator(): + est = LogisticRegression(C=10.0) + est_html_info = _get_visual_block(est) + assert est_html_info.kind == "single" + assert est_html_info.estimators == est + assert est_html_info.names == est.__class__.__name__ + assert est_html_info.name_details == str(est) + + +def test_get_visual_block_pipeline(): + pipe = Pipeline( + [ + ("imputer", SimpleImputer()), + ("do_nothing", "passthrough"), + ("do_nothing_more", None), + ("classifier", LogisticRegression()), + ] + ) + est_html_info = _get_visual_block(pipe) + assert est_html_info.kind == "serial" + assert est_html_info.estimators == tuple(step[1] for step in pipe.steps) + assert est_html_info.names == [ + "imputer: SimpleImputer", + "do_nothing: passthrough", + "do_nothing_more: passthrough", + "classifier: LogisticRegression", + ] + assert est_html_info.name_details == [str(est) for _, est in pipe.steps] + + +def test_get_visual_block_feature_union(): + f_union = FeatureUnion([("pca", PCA()), ("svd", TruncatedSVD())]) + est_html_info = _get_visual_block(f_union) + assert est_html_info.kind == "parallel" + assert est_html_info.names == ("pca", "svd") + assert est_html_info.estimators == tuple( + trans[1] for trans in f_union.transformer_list + ) + assert est_html_info.name_details == (None, None) + + +def test_get_visual_block_voting(): + clf = VotingClassifier( + [("log_reg", LogisticRegression()), ("mlp", MLPClassifier())] + ) + est_html_info = _get_visual_block(clf) + assert est_html_info.kind == "parallel" + assert est_html_info.estimators == tuple(trans[1] for trans in clf.estimators) + assert est_html_info.names == ("log_reg", "mlp") + assert est_html_info.name_details == (None, None) + + +def test_get_visual_block_column_transformer(): + ct = ColumnTransformer( + [("pca", PCA(), ["num1", "num2"]), ("svd", TruncatedSVD, [0, 3])] + ) + est_html_info = _get_visual_block(ct) + assert est_html_info.kind == "parallel" + assert est_html_info.estimators == tuple(trans[1] for trans in ct.transformers) + assert est_html_info.names == ("pca", "svd") + assert est_html_info.name_details == (["num1", "num2"], [0, 3]) + + +def test_estimator_html_repr_pipeline(): + num_trans = Pipeline( + steps=[("pass", "passthrough"), ("imputer", SimpleImputer(strategy="median"))] + ) + + cat_trans = Pipeline( + steps=[ + ("imputer", SimpleImputer(strategy="constant", missing_values="empty")), + ("one-hot", OneHotEncoder(drop="first")), + ] + ) + + preprocess = ColumnTransformer( + [ + ("num", num_trans, ["a", "b", "c", "d", "e"]), + ("cat", cat_trans, [0, 1, 2, 3]), + ] + ) + + feat_u = FeatureUnion( + [ + ("pca", PCA(n_components=1)), + ( + "tsvd", + Pipeline( + [ + ("first", TruncatedSVD(n_components=3)), + ("select", SelectPercentile()), + ] + ), + ), + ] + ) + + clf = VotingClassifier( + [ + ("lr", LogisticRegression(solver="lbfgs", random_state=1)), + ("mlp", MLPClassifier(alpha=0.001)), + ] + ) + + pipe = Pipeline( + [("preprocessor", preprocess), ("feat_u", feat_u), ("classifier", clf)] + ) + html_output = estimator_html_repr(pipe) + + # top level estimators show estimator with changes + assert html.escape(str(pipe)) in html_output + for _, est in pipe.steps: + assert ( + '
' + html.escape(str(est))
+        ) in html_output
+
+    # low level estimators do not show changes
+    with config_context(print_changed_only=True):
+        assert html.escape(str(num_trans["pass"])) in html_output
+        assert "passthrough" in html_output
+        assert html.escape(str(num_trans["imputer"])) in html_output
+
+        for _, _, cols in preprocess.transformers:
+            assert f"
{html.escape(str(cols))}
" in html_output + + # feature union + for name, _ in feat_u.transformer_list: + assert f"" in html_output + + pca = feat_u.transformer_list[0][1] + assert f"
{html.escape(str(pca))}
" in html_output + + tsvd = feat_u.transformer_list[1][1] + first = tsvd["first"] + select = tsvd["select"] + assert f"
{html.escape(str(first))}
" in html_output + assert f"
{html.escape(str(select))}
" in html_output + + # voting classifier + for name, est in clf.estimators: + assert f"" in html_output + assert f"
{html.escape(str(est))}
" in html_output + + +@pytest.mark.parametrize("final_estimator", [None, LinearSVC()]) +def test_stacking_classsifer(final_estimator): + estimators = [ + ("mlp", MLPClassifier(alpha=0.001)), + ("tree", DecisionTreeClassifier()), + ] + clf = StackingClassifier(estimators=estimators, final_estimator=final_estimator) + + html_output = estimator_html_repr(clf) + + assert html.escape(str(clf)) in html_output + # If final_estimator's default changes from LogisticRegression + # this should be updated + if final_estimator is None: + assert "LogisticRegression(" in html_output + else: + assert final_estimator.__class__.__name__ in html_output + + +@pytest.mark.parametrize("final_estimator", [None, LinearSVR()]) +def test_stacking_regressor(final_estimator): + reg = StackingRegressor( + estimators=[("svr", LinearSVR())], final_estimator=final_estimator + ) + html_output = estimator_html_repr(reg) + + assert html.escape(str(reg.estimators[0][0])) in html_output + assert "LinearSVR" in html_output + if final_estimator is None: + assert "RidgeCV" in html_output + else: + assert html.escape(final_estimator.__class__.__name__) in html_output + + +def test_birch_duck_typing_meta(): + # Test duck typing meta estimators with Birch + birch = Birch(n_clusters=AgglomerativeClustering(n_clusters=3)) + html_output = estimator_html_repr(birch) + + # inner estimators do not show changes + with config_context(print_changed_only=True): + assert f"
{html.escape(str(birch.n_clusters))}" in html_output
+        assert "AgglomerativeClustering" in html_output
+
+    # outer estimator contains all changes
+    assert f"
{html.escape(str(birch))}" in html_output
+
+
+def test_ovo_classifier_duck_typing_meta():
+    # Test duck typing metaestimators with OVO
+    ovo = OneVsOneClassifier(LinearSVC(penalty="l1"))
+    html_output = estimator_html_repr(ovo)
+
+    # inner estimators do not show changes
+    with config_context(print_changed_only=True):
+        assert f"
{html.escape(str(ovo.estimator))}" in html_output
+        assert "LinearSVC" in html_output
+
+    # outer estimator
+    assert f"
{html.escape(str(ovo))}" in html_output
+
+
+def test_duck_typing_nested_estimator():
+    # Test duck typing metaestimators with random search
+    kernel_ridge = KernelRidge(kernel=ExpSineSquared())
+    param_distributions = {"alpha": [1, 2]}
+
+    kernel_ridge_tuned = RandomizedSearchCV(
+        kernel_ridge,
+        param_distributions=param_distributions,
+    )
+    html_output = estimator_html_repr(kernel_ridge_tuned)
+    assert "estimator: KernelRidge" in html_output
+
+
+@pytest.mark.parametrize("print_changed_only", [True, False])
+def test_one_estimator_print_change_only(print_changed_only):
+    pca = PCA(n_components=10)
+
+    with config_context(print_changed_only=print_changed_only):
+        pca_repr = html.escape(str(pca))
+        html_output = estimator_html_repr(pca)
+        assert pca_repr in html_output
+
+
+def test_fallback_exists():
+    """Check that repr fallback is in the HTML."""
+    pca = PCA(n_components=10)
+    html_output = estimator_html_repr(pca)
+
+    assert (
+        f'
{html.escape(str(pca))}'
+        in html_output
+    )
+
+
+def test_show_arrow_pipeline():
+    """Show arrow in pipeline for top level in pipeline"""
+    pipe = Pipeline([("scale", StandardScaler()), ("log_Reg", LogisticRegression())])
+
+    html_output = estimator_html_repr(pipe)
+    assert (
+        'class="sk-toggleable__label sk-toggleable__label-arrow">Pipeline'
+        in html_output
+    )
+
+
+def test_invalid_parameters_in_stacking():
+    """Invalidate stacking configuration uses default repr.
+
+    Non-regression test for #24009.
+    """
+    stacker = StackingClassifier(estimators=[])
+
+    html_output = estimator_html_repr(stacker)
+    assert html.escape(str(stacker)) in html_output
+
+
+def test_estimator_get_params_return_cls():
+    """Check HTML repr works where a value in get_params is a class."""
+
+    class MyEstimator:
+        def get_params(self, deep=False):
+            return {"inner_cls": LogisticRegression}
+
+    est = MyEstimator()
+    assert "MyEstimator" in estimator_html_repr(est)
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_extmath.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_extmath.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdfb06a61c6fd125367a61442c5de1350b903885
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_extmath.py
@@ -0,0 +1,1045 @@
+# Authors: Olivier Grisel 
+#          Mathieu Blondel 
+#          Denis Engemann 
+#
+# License: BSD 3 clause
+import numpy as np
+from scipy import sparse
+from scipy import linalg
+from scipy.sparse.linalg import eigsh
+from scipy.special import expit
+
+import pytest
+from sklearn.utils import gen_batches
+from sklearn.utils._arpack import _init_arpack_v0
+from sklearn.utils._testing import assert_almost_equal
+from sklearn.utils._testing import assert_allclose
+from sklearn.utils._testing import assert_allclose_dense_sparse
+from sklearn.utils._testing import assert_array_equal
+from sklearn.utils._testing import assert_array_almost_equal
+from sklearn.utils._testing import skip_if_32bit
+from sklearn.utils.fixes import _mode, _eigh
+
+from sklearn.utils.extmath import density, _safe_accumulator_op
+from sklearn.utils.extmath import randomized_svd, _randomized_eigsh
+from sklearn.utils.extmath import row_norms
+from sklearn.utils.extmath import weighted_mode
+from sklearn.utils.extmath import cartesian
+from sklearn.utils.extmath import log_logistic
+from sklearn.utils.extmath import svd_flip
+from sklearn.utils.extmath import _incremental_mean_and_var
+from sklearn.utils.extmath import _deterministic_vector_sign_flip
+from sklearn.utils.extmath import softmax
+from sklearn.utils.extmath import stable_cumsum
+from sklearn.utils.extmath import safe_sparse_dot
+from sklearn.datasets import make_low_rank_matrix, make_sparse_spd_matrix
+
+
+def test_density():
+    rng = np.random.RandomState(0)
+    X = rng.randint(10, size=(10, 5))
+    X[1, 2] = 0
+    X[5, 3] = 0
+    X_csr = sparse.csr_matrix(X)
+    X_csc = sparse.csc_matrix(X)
+    X_coo = sparse.coo_matrix(X)
+    X_lil = sparse.lil_matrix(X)
+
+    for X_ in (X_csr, X_csc, X_coo, X_lil):
+        assert density(X_) == density(X)
+
+
+# TODO(1.4): Remove test
+def test_density_deprecated_kwargs():
+    """Check that future warning is raised when user enters keyword arguments."""
+    test_array = np.array([[1, 2, 3], [4, 5, 6]])
+    with pytest.warns(
+        FutureWarning,
+        match=(
+            "Additional keyword arguments are deprecated in version 1.2 and will be"
+            " removed in version 1.4."
+        ),
+    ):
+        density(test_array, a=1)
+
+
+def test_uniform_weights():
+    # with uniform weights, results should be identical to stats.mode
+    rng = np.random.RandomState(0)
+    x = rng.randint(10, size=(10, 5))
+    weights = np.ones(x.shape)
+
+    for axis in (None, 0, 1):
+        mode, score = _mode(x, axis)
+        mode2, score2 = weighted_mode(x, weights, axis=axis)
+
+        assert_array_equal(mode, mode2)
+        assert_array_equal(score, score2)
+
+
+def test_random_weights():
+    # set this up so that each row should have a weighted mode of 6,
+    # with a score that is easily reproduced
+    mode_result = 6
+
+    rng = np.random.RandomState(0)
+    x = rng.randint(mode_result, size=(100, 10))
+    w = rng.random_sample(x.shape)
+
+    x[:, :5] = mode_result
+    w[:, :5] += 1
+
+    mode, score = weighted_mode(x, w, axis=1)
+
+    assert_array_equal(mode, mode_result)
+    assert_array_almost_equal(score.ravel(), w[:, :5].sum(1))
+
+
+def check_randomized_svd_low_rank(dtype):
+    # Check that extmath.randomized_svd is consistent with linalg.svd
+    n_samples = 100
+    n_features = 500
+    rank = 5
+    k = 10
+    decimal = 5 if dtype == np.float32 else 7
+    dtype = np.dtype(dtype)
+
+    # generate a matrix X of approximate effective rank `rank` and no noise
+    # component (very structured signal):
+    X = make_low_rank_matrix(
+        n_samples=n_samples,
+        n_features=n_features,
+        effective_rank=rank,
+        tail_strength=0.0,
+        random_state=0,
+    ).astype(dtype, copy=False)
+    assert X.shape == (n_samples, n_features)
+
+    # compute the singular values of X using the slow exact method
+    U, s, Vt = linalg.svd(X, full_matrices=False)
+
+    # Convert the singular values to the specific dtype
+    U = U.astype(dtype, copy=False)
+    s = s.astype(dtype, copy=False)
+    Vt = Vt.astype(dtype, copy=False)
+
+    for normalizer in ["auto", "LU", "QR"]:  # 'none' would not be stable
+        # compute the singular values of X using the fast approximate method
+        Ua, sa, Va = randomized_svd(
+            X, k, power_iteration_normalizer=normalizer, random_state=0
+        )
+
+        # If the input dtype is float, then the output dtype is float of the
+        # same bit size (f32 is not upcast to f64)
+        # But if the input dtype is int, the output dtype is float64
+        if dtype.kind == "f":
+            assert Ua.dtype == dtype
+            assert sa.dtype == dtype
+            assert Va.dtype == dtype
+        else:
+            assert Ua.dtype == np.float64
+            assert sa.dtype == np.float64
+            assert Va.dtype == np.float64
+
+        assert Ua.shape == (n_samples, k)
+        assert sa.shape == (k,)
+        assert Va.shape == (k, n_features)
+
+        # ensure that the singular values of both methods are equal up to the
+        # real rank of the matrix
+        assert_almost_equal(s[:k], sa, decimal=decimal)
+
+        # check the singular vectors too (while not checking the sign)
+        assert_almost_equal(
+            np.dot(U[:, :k], Vt[:k, :]), np.dot(Ua, Va), decimal=decimal
+        )
+
+        # check the sparse matrix representation
+        X = sparse.csr_matrix(X)
+
+        # compute the singular values of X using the fast approximate method
+        Ua, sa, Va = randomized_svd(
+            X, k, power_iteration_normalizer=normalizer, random_state=0
+        )
+        if dtype.kind == "f":
+            assert Ua.dtype == dtype
+            assert sa.dtype == dtype
+            assert Va.dtype == dtype
+        else:
+            assert Ua.dtype.kind == "f"
+            assert sa.dtype.kind == "f"
+            assert Va.dtype.kind == "f"
+
+        assert_almost_equal(s[:rank], sa[:rank], decimal=decimal)
+
+
+@pytest.mark.parametrize("dtype", (np.int32, np.int64, np.float32, np.float64))
+def test_randomized_svd_low_rank_all_dtypes(dtype):
+    check_randomized_svd_low_rank(dtype)
+
+
+@pytest.mark.parametrize("dtype", (np.int32, np.int64, np.float32, np.float64))
+def test_randomized_eigsh(dtype):
+    """Test that `_randomized_eigsh` returns the appropriate components"""
+
+    rng = np.random.RandomState(42)
+    X = np.diag(np.array([1.0, -2.0, 0.0, 3.0], dtype=dtype))
+    # random rotation that preserves the eigenvalues of X
+    rand_rot = np.linalg.qr(rng.normal(size=X.shape))[0]
+    X = rand_rot @ X @ rand_rot.T
+
+    # with 'module' selection method, the negative eigenvalue shows up
+    eigvals, eigvecs = _randomized_eigsh(X, n_components=2, selection="module")
+    # eigenvalues
+    assert eigvals.shape == (2,)
+    assert_array_almost_equal(eigvals, [3.0, -2.0])  # negative eigenvalue here
+    # eigenvectors
+    assert eigvecs.shape == (4, 2)
+
+    # with 'value' selection method, the negative eigenvalue does not show up
+    with pytest.raises(NotImplementedError):
+        _randomized_eigsh(X, n_components=2, selection="value")
+
+
+@pytest.mark.parametrize("k", (10, 50, 100, 199, 200))
+def test_randomized_eigsh_compared_to_others(k):
+    """Check that `_randomized_eigsh` is similar to other `eigsh`
+
+    Tests that for a random PSD matrix, `_randomized_eigsh` provides results
+    comparable to LAPACK (scipy.linalg.eigh) and ARPACK
+    (scipy.sparse.linalg.eigsh).
+
+    Note: some versions of ARPACK do not support k=n_features.
+    """
+
+    # make a random PSD matrix
+    n_features = 200
+    X = make_sparse_spd_matrix(n_features, random_state=0)
+
+    # compare two versions of randomized
+    # rough and fast
+    eigvals, eigvecs = _randomized_eigsh(
+        X, n_components=k, selection="module", n_iter=25, random_state=0
+    )
+    # more accurate but slow (TODO find realistic settings here)
+    eigvals_qr, eigvecs_qr = _randomized_eigsh(
+        X,
+        n_components=k,
+        n_iter=25,
+        n_oversamples=20,
+        random_state=0,
+        power_iteration_normalizer="QR",
+        selection="module",
+    )
+
+    # with LAPACK
+    eigvals_lapack, eigvecs_lapack = _eigh(
+        X, subset_by_index=(n_features - k, n_features - 1)
+    )
+    indices = eigvals_lapack.argsort()[::-1]
+    eigvals_lapack = eigvals_lapack[indices]
+    eigvecs_lapack = eigvecs_lapack[:, indices]
+
+    # -- eigenvalues comparison
+    assert eigvals_lapack.shape == (k,)
+    # comparison precision
+    assert_array_almost_equal(eigvals, eigvals_lapack, decimal=6)
+    assert_array_almost_equal(eigvals_qr, eigvals_lapack, decimal=6)
+
+    # -- eigenvectors comparison
+    assert eigvecs_lapack.shape == (n_features, k)
+    # flip eigenvectors' sign to enforce deterministic output
+    dummy_vecs = np.zeros_like(eigvecs).T
+    eigvecs, _ = svd_flip(eigvecs, dummy_vecs)
+    eigvecs_qr, _ = svd_flip(eigvecs_qr, dummy_vecs)
+    eigvecs_lapack, _ = svd_flip(eigvecs_lapack, dummy_vecs)
+    assert_array_almost_equal(eigvecs, eigvecs_lapack, decimal=4)
+    assert_array_almost_equal(eigvecs_qr, eigvecs_lapack, decimal=6)
+
+    # comparison ARPACK ~ LAPACK (some ARPACK implems do not support k=n)
+    if k < n_features:
+        v0 = _init_arpack_v0(n_features, random_state=0)
+        # "LA" largest algebraic <=> selection="value" in randomized_eigsh
+        eigvals_arpack, eigvecs_arpack = eigsh(
+            X, k, which="LA", tol=0, maxiter=None, v0=v0
+        )
+        indices = eigvals_arpack.argsort()[::-1]
+        # eigenvalues
+        eigvals_arpack = eigvals_arpack[indices]
+        assert_array_almost_equal(eigvals_lapack, eigvals_arpack, decimal=10)
+        # eigenvectors
+        eigvecs_arpack = eigvecs_arpack[:, indices]
+        eigvecs_arpack, _ = svd_flip(eigvecs_arpack, dummy_vecs)
+        assert_array_almost_equal(eigvecs_arpack, eigvecs_lapack, decimal=8)
+
+
+@pytest.mark.parametrize(
+    "n,rank",
+    [
+        (10, 7),
+        (100, 10),
+        (100, 80),
+        (500, 10),
+        (500, 250),
+        (500, 400),
+    ],
+)
+def test_randomized_eigsh_reconst_low_rank(n, rank):
+    """Check that randomized_eigsh is able to reconstruct a low rank psd matrix
+
+    Tests that the decomposition provided by `_randomized_eigsh` leads to
+    orthonormal eigenvectors, and that a low rank PSD matrix can be effectively
+    reconstructed with good accuracy using it.
+    """
+    assert rank < n
+
+    # create a low rank PSD
+    rng = np.random.RandomState(69)
+    X = rng.randn(n, rank)
+    A = X @ X.T
+
+    # approximate A with the "right" number of components
+    S, V = _randomized_eigsh(A, n_components=rank, random_state=rng)
+    # orthonormality checks
+    assert_array_almost_equal(np.linalg.norm(V, axis=0), np.ones(S.shape))
+    assert_array_almost_equal(V.T @ V, np.diag(np.ones(S.shape)))
+    # reconstruction
+    A_reconstruct = V @ np.diag(S) @ V.T
+
+    # test that the approximation is good
+    assert_array_almost_equal(A_reconstruct, A, decimal=6)
+
+
+@pytest.mark.parametrize("dtype", (np.float32, np.float64))
+def test_row_norms(dtype):
+    X = np.random.RandomState(42).randn(100, 100)
+    if dtype is np.float32:
+        precision = 4
+    else:
+        precision = 5
+
+    X = X.astype(dtype, copy=False)
+    sq_norm = (X**2).sum(axis=1)
+
+    assert_array_almost_equal(sq_norm, row_norms(X, squared=True), precision)
+    assert_array_almost_equal(np.sqrt(sq_norm), row_norms(X), precision)
+
+    for csr_index_dtype in [np.int32, np.int64]:
+        Xcsr = sparse.csr_matrix(X, dtype=dtype)
+        # csr_matrix will use int32 indices by default,
+        # up-casting those to int64 when necessary
+        if csr_index_dtype is np.int64:
+            Xcsr.indptr = Xcsr.indptr.astype(csr_index_dtype, copy=False)
+            Xcsr.indices = Xcsr.indices.astype(csr_index_dtype, copy=False)
+        assert Xcsr.indices.dtype == csr_index_dtype
+        assert Xcsr.indptr.dtype == csr_index_dtype
+        assert_array_almost_equal(sq_norm, row_norms(Xcsr, squared=True), precision)
+        assert_array_almost_equal(np.sqrt(sq_norm), row_norms(Xcsr), precision)
+
+
+def test_randomized_svd_low_rank_with_noise():
+    # Check that extmath.randomized_svd can handle noisy matrices
+    n_samples = 100
+    n_features = 500
+    rank = 5
+    k = 10
+
+    # generate a matrix X wity structure approximate rank `rank` and an
+    # important noisy component
+    X = make_low_rank_matrix(
+        n_samples=n_samples,
+        n_features=n_features,
+        effective_rank=rank,
+        tail_strength=0.1,
+        random_state=0,
+    )
+    assert X.shape == (n_samples, n_features)
+
+    # compute the singular values of X using the slow exact method
+    _, s, _ = linalg.svd(X, full_matrices=False)
+
+    for normalizer in ["auto", "none", "LU", "QR"]:
+        # compute the singular values of X using the fast approximate
+        # method without the iterated power method
+        _, sa, _ = randomized_svd(
+            X, k, n_iter=0, power_iteration_normalizer=normalizer, random_state=0
+        )
+
+        # the approximation does not tolerate the noise:
+        assert np.abs(s[:k] - sa).max() > 0.01
+
+        # compute the singular values of X using the fast approximate
+        # method with iterated power method
+        _, sap, _ = randomized_svd(
+            X, k, power_iteration_normalizer=normalizer, random_state=0
+        )
+
+        # the iterated power method is helping getting rid of the noise:
+        assert_almost_equal(s[:k], sap, decimal=3)
+
+
+def test_randomized_svd_infinite_rank():
+    # Check that extmath.randomized_svd can handle noisy matrices
+    n_samples = 100
+    n_features = 500
+    rank = 5
+    k = 10
+
+    # let us try again without 'low_rank component': just regularly but slowly
+    # decreasing singular values: the rank of the data matrix is infinite
+    X = make_low_rank_matrix(
+        n_samples=n_samples,
+        n_features=n_features,
+        effective_rank=rank,
+        tail_strength=1.0,
+        random_state=0,
+    )
+    assert X.shape == (n_samples, n_features)
+
+    # compute the singular values of X using the slow exact method
+    _, s, _ = linalg.svd(X, full_matrices=False)
+    for normalizer in ["auto", "none", "LU", "QR"]:
+        # compute the singular values of X using the fast approximate method
+        # without the iterated power method
+        _, sa, _ = randomized_svd(
+            X, k, n_iter=0, power_iteration_normalizer=normalizer, random_state=0
+        )
+
+        # the approximation does not tolerate the noise:
+        assert np.abs(s[:k] - sa).max() > 0.1
+
+        # compute the singular values of X using the fast approximate method
+        # with iterated power method
+        _, sap, _ = randomized_svd(
+            X, k, n_iter=5, power_iteration_normalizer=normalizer, random_state=0
+        )
+
+        # the iterated power method is still managing to get most of the
+        # structure at the requested rank
+        assert_almost_equal(s[:k], sap, decimal=3)
+
+
+def test_randomized_svd_transpose_consistency():
+    # Check that transposing the design matrix has limited impact
+    n_samples = 100
+    n_features = 500
+    rank = 4
+    k = 10
+
+    X = make_low_rank_matrix(
+        n_samples=n_samples,
+        n_features=n_features,
+        effective_rank=rank,
+        tail_strength=0.5,
+        random_state=0,
+    )
+    assert X.shape == (n_samples, n_features)
+
+    U1, s1, V1 = randomized_svd(X, k, n_iter=3, transpose=False, random_state=0)
+    U2, s2, V2 = randomized_svd(X, k, n_iter=3, transpose=True, random_state=0)
+    U3, s3, V3 = randomized_svd(X, k, n_iter=3, transpose="auto", random_state=0)
+    U4, s4, V4 = linalg.svd(X, full_matrices=False)
+
+    assert_almost_equal(s1, s4[:k], decimal=3)
+    assert_almost_equal(s2, s4[:k], decimal=3)
+    assert_almost_equal(s3, s4[:k], decimal=3)
+
+    assert_almost_equal(np.dot(U1, V1), np.dot(U4[:, :k], V4[:k, :]), decimal=2)
+    assert_almost_equal(np.dot(U2, V2), np.dot(U4[:, :k], V4[:k, :]), decimal=2)
+
+    # in this case 'auto' is equivalent to transpose
+    assert_almost_equal(s2, s3)
+
+
+def test_randomized_svd_power_iteration_normalizer():
+    # randomized_svd with power_iteration_normalized='none' diverges for
+    # large number of power iterations on this dataset
+    rng = np.random.RandomState(42)
+    X = make_low_rank_matrix(100, 500, effective_rank=50, random_state=rng)
+    X += 3 * rng.randint(0, 2, size=X.shape)
+    n_components = 50
+
+    # Check that it diverges with many (non-normalized) power iterations
+    U, s, Vt = randomized_svd(
+        X, n_components, n_iter=2, power_iteration_normalizer="none", random_state=0
+    )
+    A = X - U.dot(np.diag(s).dot(Vt))
+    error_2 = linalg.norm(A, ord="fro")
+    U, s, Vt = randomized_svd(
+        X, n_components, n_iter=20, power_iteration_normalizer="none", random_state=0
+    )
+    A = X - U.dot(np.diag(s).dot(Vt))
+    error_20 = linalg.norm(A, ord="fro")
+    assert np.abs(error_2 - error_20) > 100
+
+    for normalizer in ["LU", "QR", "auto"]:
+        U, s, Vt = randomized_svd(
+            X,
+            n_components,
+            n_iter=2,
+            power_iteration_normalizer=normalizer,
+            random_state=0,
+        )
+        A = X - U.dot(np.diag(s).dot(Vt))
+        error_2 = linalg.norm(A, ord="fro")
+
+        for i in [5, 10, 50]:
+            U, s, Vt = randomized_svd(
+                X,
+                n_components,
+                n_iter=i,
+                power_iteration_normalizer=normalizer,
+                random_state=0,
+            )
+            A = X - U.dot(np.diag(s).dot(Vt))
+            error = linalg.norm(A, ord="fro")
+            assert 15 > np.abs(error_2 - error)
+
+
+def test_randomized_svd_sparse_warnings():
+    # randomized_svd throws a warning for lil and dok matrix
+    rng = np.random.RandomState(42)
+    X = make_low_rank_matrix(50, 20, effective_rank=10, random_state=rng)
+    n_components = 5
+    for cls in (sparse.lil_matrix, sparse.dok_matrix):
+        X = cls(X)
+        warn_msg = (
+            "Calculating SVD of a {} is expensive. "
+            "csr_matrix is more efficient.".format(cls.__name__)
+        )
+        with pytest.warns(sparse.SparseEfficiencyWarning, match=warn_msg):
+            randomized_svd(X, n_components, n_iter=1, power_iteration_normalizer="none")
+
+
+def test_svd_flip():
+    # Check that svd_flip works in both situations, and reconstructs input.
+    rs = np.random.RandomState(1999)
+    n_samples = 20
+    n_features = 10
+    X = rs.randn(n_samples, n_features)
+
+    # Check matrix reconstruction
+    U, S, Vt = linalg.svd(X, full_matrices=False)
+    U1, V1 = svd_flip(U, Vt, u_based_decision=False)
+    assert_almost_equal(np.dot(U1 * S, V1), X, decimal=6)
+
+    # Check transposed matrix reconstruction
+    XT = X.T
+    U, S, Vt = linalg.svd(XT, full_matrices=False)
+    U2, V2 = svd_flip(U, Vt, u_based_decision=True)
+    assert_almost_equal(np.dot(U2 * S, V2), XT, decimal=6)
+
+    # Check that different flip methods are equivalent under reconstruction
+    U_flip1, V_flip1 = svd_flip(U, Vt, u_based_decision=True)
+    assert_almost_equal(np.dot(U_flip1 * S, V_flip1), XT, decimal=6)
+    U_flip2, V_flip2 = svd_flip(U, Vt, u_based_decision=False)
+    assert_almost_equal(np.dot(U_flip2 * S, V_flip2), XT, decimal=6)
+
+
+def test_randomized_svd_sign_flip():
+    a = np.array([[2.0, 0.0], [0.0, 1.0]])
+    u1, s1, v1 = randomized_svd(a, 2, flip_sign=True, random_state=41)
+    for seed in range(10):
+        u2, s2, v2 = randomized_svd(a, 2, flip_sign=True, random_state=seed)
+        assert_almost_equal(u1, u2)
+        assert_almost_equal(v1, v2)
+        assert_almost_equal(np.dot(u2 * s2, v2), a)
+        assert_almost_equal(np.dot(u2.T, u2), np.eye(2))
+        assert_almost_equal(np.dot(v2.T, v2), np.eye(2))
+
+
+def test_randomized_svd_sign_flip_with_transpose():
+    # Check if the randomized_svd sign flipping is always done based on u
+    # irrespective of transpose.
+    # See https://github.com/scikit-learn/scikit-learn/issues/5608
+    # for more details.
+    def max_loading_is_positive(u, v):
+        """
+        returns bool tuple indicating if the values maximising np.abs
+        are positive across all rows for u and across all columns for v.
+        """
+        u_based = (np.abs(u).max(axis=0) == u.max(axis=0)).all()
+        v_based = (np.abs(v).max(axis=1) == v.max(axis=1)).all()
+        return u_based, v_based
+
+    mat = np.arange(10 * 8).reshape(10, -1)
+
+    # Without transpose
+    u_flipped, _, v_flipped = randomized_svd(mat, 3, flip_sign=True, random_state=0)
+    u_based, v_based = max_loading_is_positive(u_flipped, v_flipped)
+    assert u_based
+    assert not v_based
+
+    # With transpose
+    u_flipped_with_transpose, _, v_flipped_with_transpose = randomized_svd(
+        mat, 3, flip_sign=True, transpose=True, random_state=0
+    )
+    u_based, v_based = max_loading_is_positive(
+        u_flipped_with_transpose, v_flipped_with_transpose
+    )
+    assert u_based
+    assert not v_based
+
+
+@pytest.mark.parametrize("n", [50, 100, 300])
+@pytest.mark.parametrize("m", [50, 100, 300])
+@pytest.mark.parametrize("k", [10, 20, 50])
+@pytest.mark.parametrize("seed", range(5))
+def test_randomized_svd_lapack_driver(n, m, k, seed):
+    # Check that different SVD drivers provide consistent results
+
+    # Matrix being compressed
+    rng = np.random.RandomState(seed)
+    X = rng.rand(n, m)
+
+    # Number of components
+    u1, s1, vt1 = randomized_svd(X, k, svd_lapack_driver="gesdd", random_state=0)
+    u2, s2, vt2 = randomized_svd(X, k, svd_lapack_driver="gesvd", random_state=0)
+
+    # Check shape and contents
+    assert u1.shape == u2.shape
+    assert_allclose(u1, u2, atol=0, rtol=1e-3)
+
+    assert s1.shape == s2.shape
+    assert_allclose(s1, s2, atol=0, rtol=1e-3)
+
+    assert vt1.shape == vt2.shape
+    assert_allclose(vt1, vt2, atol=0, rtol=1e-3)
+
+
+def test_cartesian():
+    # Check if cartesian product delivers the right results
+
+    axes = (np.array([1, 2, 3]), np.array([4, 5]), np.array([6, 7]))
+
+    true_out = np.array(
+        [
+            [1, 4, 6],
+            [1, 4, 7],
+            [1, 5, 6],
+            [1, 5, 7],
+            [2, 4, 6],
+            [2, 4, 7],
+            [2, 5, 6],
+            [2, 5, 7],
+            [3, 4, 6],
+            [3, 4, 7],
+            [3, 5, 6],
+            [3, 5, 7],
+        ]
+    )
+
+    out = cartesian(axes)
+    assert_array_equal(true_out, out)
+
+    # check single axis
+    x = np.arange(3)
+    assert_array_equal(x[:, np.newaxis], cartesian((x,)))
+
+
+@pytest.mark.parametrize(
+    "arrays, output_dtype",
+    [
+        (
+            [np.array([1, 2, 3], dtype=np.int32), np.array([4, 5], dtype=np.int64)],
+            np.dtype(np.int64),
+        ),
+        (
+            [np.array([1, 2, 3], dtype=np.int32), np.array([4, 5], dtype=np.float64)],
+            np.dtype(np.float64),
+        ),
+        (
+            [np.array([1, 2, 3], dtype=np.int32), np.array(["x", "y"], dtype=object)],
+            np.dtype(object),
+        ),
+    ],
+)
+def test_cartesian_mix_types(arrays, output_dtype):
+    """Check that the cartesian product works with mixed types."""
+    output = cartesian(arrays)
+
+    assert output.dtype == output_dtype
+
+
+def test_logistic_sigmoid():
+    # Check correctness and robustness of logistic sigmoid implementation
+    def naive_log_logistic(x):
+        return np.log(expit(x))
+
+    x = np.linspace(-2, 2, 50)
+    assert_array_almost_equal(log_logistic(x), naive_log_logistic(x))
+
+    extreme_x = np.array([-100.0, 100.0])
+    assert_array_almost_equal(log_logistic(extreme_x), [-100, 0])
+
+
+@pytest.fixture()
+def rng():
+    return np.random.RandomState(42)
+
+
+@pytest.mark.parametrize("dtype", [np.float32, np.float64])
+def test_incremental_weighted_mean_and_variance_simple(rng, dtype):
+    mult = 10
+    X = rng.rand(1000, 20).astype(dtype) * mult
+    sample_weight = rng.rand(X.shape[0]) * mult
+    mean, var, _ = _incremental_mean_and_var(X, 0, 0, 0, sample_weight=sample_weight)
+
+    expected_mean = np.average(X, weights=sample_weight, axis=0)
+    expected_var = (
+        np.average(X**2, weights=sample_weight, axis=0) - expected_mean**2
+    )
+    assert_almost_equal(mean, expected_mean)
+    assert_almost_equal(var, expected_var)
+
+
+@pytest.mark.parametrize("mean", [0, 1e7, -1e7])
+@pytest.mark.parametrize("var", [1, 1e-8, 1e5])
+@pytest.mark.parametrize(
+    "weight_loc, weight_scale", [(0, 1), (0, 1e-8), (1, 1e-8), (10, 1), (1e7, 1)]
+)
+def test_incremental_weighted_mean_and_variance(
+    mean, var, weight_loc, weight_scale, rng
+):
+
+    # Testing of correctness and numerical stability
+    def _assert(X, sample_weight, expected_mean, expected_var):
+        n = X.shape[0]
+        for chunk_size in [1, n // 10 + 1, n // 4 + 1, n // 2 + 1, n]:
+            last_mean, last_weight_sum, last_var = 0, 0, 0
+            for batch in gen_batches(n, chunk_size):
+                last_mean, last_var, last_weight_sum = _incremental_mean_and_var(
+                    X[batch],
+                    last_mean,
+                    last_var,
+                    last_weight_sum,
+                    sample_weight=sample_weight[batch],
+                )
+            assert_allclose(last_mean, expected_mean)
+            assert_allclose(last_var, expected_var, atol=1e-6)
+
+    size = (100, 20)
+    weight = rng.normal(loc=weight_loc, scale=weight_scale, size=size[0])
+
+    # Compare to weighted average: np.average
+    X = rng.normal(loc=mean, scale=var, size=size)
+    expected_mean = _safe_accumulator_op(np.average, X, weights=weight, axis=0)
+    expected_var = _safe_accumulator_op(
+        np.average, (X - expected_mean) ** 2, weights=weight, axis=0
+    )
+    _assert(X, weight, expected_mean, expected_var)
+
+    # Compare to unweighted mean: np.mean
+    X = rng.normal(loc=mean, scale=var, size=size)
+    ones_weight = np.ones(size[0])
+    expected_mean = _safe_accumulator_op(np.mean, X, axis=0)
+    expected_var = _safe_accumulator_op(np.var, X, axis=0)
+    _assert(X, ones_weight, expected_mean, expected_var)
+
+
+@pytest.mark.parametrize("dtype", [np.float32, np.float64])
+def test_incremental_weighted_mean_and_variance_ignore_nan(dtype):
+    old_means = np.array([535.0, 535.0, 535.0, 535.0])
+    old_variances = np.array([4225.0, 4225.0, 4225.0, 4225.0])
+    old_weight_sum = np.array([2, 2, 2, 2], dtype=np.int32)
+    sample_weights_X = np.ones(3)
+    sample_weights_X_nan = np.ones(4)
+
+    X = np.array(
+        [[170, 170, 170, 170], [430, 430, 430, 430], [300, 300, 300, 300]]
+    ).astype(dtype)
+
+    X_nan = np.array(
+        [
+            [170, np.nan, 170, 170],
+            [np.nan, 170, 430, 430],
+            [430, 430, np.nan, 300],
+            [300, 300, 300, np.nan],
+        ]
+    ).astype(dtype)
+
+    X_means, X_variances, X_count = _incremental_mean_and_var(
+        X, old_means, old_variances, old_weight_sum, sample_weight=sample_weights_X
+    )
+    X_nan_means, X_nan_variances, X_nan_count = _incremental_mean_and_var(
+        X_nan,
+        old_means,
+        old_variances,
+        old_weight_sum,
+        sample_weight=sample_weights_X_nan,
+    )
+
+    assert_allclose(X_nan_means, X_means)
+    assert_allclose(X_nan_variances, X_variances)
+    assert_allclose(X_nan_count, X_count)
+
+
+def test_incremental_variance_update_formulas():
+    # Test Youngs and Cramer incremental variance formulas.
+    # Doggie data from https://www.mathsisfun.com/data/standard-deviation.html
+    A = np.array(
+        [
+            [600, 470, 170, 430, 300],
+            [600, 470, 170, 430, 300],
+            [600, 470, 170, 430, 300],
+            [600, 470, 170, 430, 300],
+        ]
+    ).T
+    idx = 2
+    X1 = A[:idx, :]
+    X2 = A[idx:, :]
+
+    old_means = X1.mean(axis=0)
+    old_variances = X1.var(axis=0)
+    old_sample_count = np.full(X1.shape[1], X1.shape[0], dtype=np.int32)
+    final_means, final_variances, final_count = _incremental_mean_and_var(
+        X2, old_means, old_variances, old_sample_count
+    )
+    assert_almost_equal(final_means, A.mean(axis=0), 6)
+    assert_almost_equal(final_variances, A.var(axis=0), 6)
+    assert_almost_equal(final_count, A.shape[0])
+
+
+def test_incremental_mean_and_variance_ignore_nan():
+    old_means = np.array([535.0, 535.0, 535.0, 535.0])
+    old_variances = np.array([4225.0, 4225.0, 4225.0, 4225.0])
+    old_sample_count = np.array([2, 2, 2, 2], dtype=np.int32)
+
+    X = np.array([[170, 170, 170, 170], [430, 430, 430, 430], [300, 300, 300, 300]])
+
+    X_nan = np.array(
+        [
+            [170, np.nan, 170, 170],
+            [np.nan, 170, 430, 430],
+            [430, 430, np.nan, 300],
+            [300, 300, 300, np.nan],
+        ]
+    )
+
+    X_means, X_variances, X_count = _incremental_mean_and_var(
+        X, old_means, old_variances, old_sample_count
+    )
+    X_nan_means, X_nan_variances, X_nan_count = _incremental_mean_and_var(
+        X_nan, old_means, old_variances, old_sample_count
+    )
+
+    assert_allclose(X_nan_means, X_means)
+    assert_allclose(X_nan_variances, X_variances)
+    assert_allclose(X_nan_count, X_count)
+
+
+@skip_if_32bit
+def test_incremental_variance_numerical_stability():
+    # Test Youngs and Cramer incremental variance formulas.
+
+    def np_var(A):
+        return A.var(axis=0)
+
+    # Naive one pass variance computation - not numerically stable
+    # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
+    def one_pass_var(X):
+        n = X.shape[0]
+        exp_x2 = (X**2).sum(axis=0) / n
+        expx_2 = (X.sum(axis=0) / n) ** 2
+        return exp_x2 - expx_2
+
+    # Two-pass algorithm, stable.
+    # We use it as a benchmark. It is not an online algorithm
+    # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Two-pass_algorithm
+    def two_pass_var(X):
+        mean = X.mean(axis=0)
+        Y = X.copy()
+        return np.mean((Y - mean) ** 2, axis=0)
+
+    # Naive online implementation
+    # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm
+    # This works only for chunks for size 1
+    def naive_mean_variance_update(x, last_mean, last_variance, last_sample_count):
+        updated_sample_count = last_sample_count + 1
+        samples_ratio = last_sample_count / float(updated_sample_count)
+        updated_mean = x / updated_sample_count + last_mean * samples_ratio
+        updated_variance = (
+            last_variance * samples_ratio
+            + (x - last_mean) * (x - updated_mean) / updated_sample_count
+        )
+        return updated_mean, updated_variance, updated_sample_count
+
+    # We want to show a case when one_pass_var has error > 1e-3 while
+    # _batch_mean_variance_update has less.
+    tol = 200
+    n_features = 2
+    n_samples = 10000
+    x1 = np.array(1e8, dtype=np.float64)
+    x2 = np.log(1e-5, dtype=np.float64)
+    A0 = np.full((n_samples // 2, n_features), x1, dtype=np.float64)
+    A1 = np.full((n_samples // 2, n_features), x2, dtype=np.float64)
+    A = np.vstack((A0, A1))
+
+    # Naive one pass var: >tol (=1063)
+    assert np.abs(np_var(A) - one_pass_var(A)).max() > tol
+
+    # Starting point for online algorithms: after A0
+
+    # Naive implementation: >tol (436)
+    mean, var, n = A0[0, :], np.zeros(n_features), n_samples // 2
+    for i in range(A1.shape[0]):
+        mean, var, n = naive_mean_variance_update(A1[i, :], mean, var, n)
+    assert n == A.shape[0]
+    # the mean is also slightly unstable
+    assert np.abs(A.mean(axis=0) - mean).max() > 1e-6
+    assert np.abs(np_var(A) - var).max() > tol
+
+    # Robust implementation:  np.abs(np_var(A) - var).max()
+
+
+def test_incremental_variance_ddof():
+    # Test that degrees of freedom parameter for calculations are correct.
+    rng = np.random.RandomState(1999)
+    X = rng.randn(50, 10)
+    n_samples, n_features = X.shape
+    for batch_size in [11, 20, 37]:
+        steps = np.arange(0, X.shape[0], batch_size)
+        if steps[-1] != X.shape[0]:
+            steps = np.hstack([steps, n_samples])
+
+        for i, j in zip(steps[:-1], steps[1:]):
+            batch = X[i:j, :]
+            if i == 0:
+                incremental_means = batch.mean(axis=0)
+                incremental_variances = batch.var(axis=0)
+                # Assign this twice so that the test logic is consistent
+                incremental_count = batch.shape[0]
+                sample_count = np.full(batch.shape[1], batch.shape[0], dtype=np.int32)
+            else:
+                result = _incremental_mean_and_var(
+                    batch, incremental_means, incremental_variances, sample_count
+                )
+                (incremental_means, incremental_variances, incremental_count) = result
+                sample_count += batch.shape[0]
+
+            calculated_means = np.mean(X[:j], axis=0)
+            calculated_variances = np.var(X[:j], axis=0)
+            assert_almost_equal(incremental_means, calculated_means, 6)
+            assert_almost_equal(incremental_variances, calculated_variances, 6)
+            assert_array_equal(incremental_count, sample_count)
+
+
+def test_vector_sign_flip():
+    # Testing that sign flip is working & largest value has positive sign
+    data = np.random.RandomState(36).randn(5, 5)
+    max_abs_rows = np.argmax(np.abs(data), axis=1)
+    data_flipped = _deterministic_vector_sign_flip(data)
+    max_rows = np.argmax(data_flipped, axis=1)
+    assert_array_equal(max_abs_rows, max_rows)
+    signs = np.sign(data[range(data.shape[0]), max_abs_rows])
+    assert_array_equal(data, data_flipped * signs[:, np.newaxis])
+
+
+def test_softmax():
+    rng = np.random.RandomState(0)
+    X = rng.randn(3, 5)
+    exp_X = np.exp(X)
+    sum_exp_X = np.sum(exp_X, axis=1).reshape((-1, 1))
+    assert_array_almost_equal(softmax(X), exp_X / sum_exp_X)
+
+
+def test_stable_cumsum():
+    assert_array_equal(stable_cumsum([1, 2, 3]), np.cumsum([1, 2, 3]))
+    r = np.random.RandomState(0).rand(100000)
+    with pytest.warns(RuntimeWarning):
+        stable_cumsum(r, rtol=0, atol=0)
+
+    # test axis parameter
+    A = np.random.RandomState(36).randint(1000, size=(5, 5, 5))
+    assert_array_equal(stable_cumsum(A, axis=0), np.cumsum(A, axis=0))
+    assert_array_equal(stable_cumsum(A, axis=1), np.cumsum(A, axis=1))
+    assert_array_equal(stable_cumsum(A, axis=2), np.cumsum(A, axis=2))
+
+
+@pytest.mark.parametrize(
+    "A_array_constr", [np.array, sparse.csr_matrix], ids=["dense", "sparse"]
+)
+@pytest.mark.parametrize(
+    "B_array_constr", [np.array, sparse.csr_matrix], ids=["dense", "sparse"]
+)
+def test_safe_sparse_dot_2d(A_array_constr, B_array_constr):
+    rng = np.random.RandomState(0)
+
+    A = rng.random_sample((30, 10))
+    B = rng.random_sample((10, 20))
+    expected = np.dot(A, B)
+
+    A = A_array_constr(A)
+    B = B_array_constr(B)
+    actual = safe_sparse_dot(A, B, dense_output=True)
+
+    assert_allclose(actual, expected)
+
+
+def test_safe_sparse_dot_nd():
+    rng = np.random.RandomState(0)
+
+    # dense ND / sparse
+    A = rng.random_sample((2, 3, 4, 5, 6))
+    B = rng.random_sample((6, 7))
+    expected = np.dot(A, B)
+    B = sparse.csr_matrix(B)
+    actual = safe_sparse_dot(A, B)
+    assert_allclose(actual, expected)
+
+    # sparse / dense ND
+    A = rng.random_sample((2, 3))
+    B = rng.random_sample((4, 5, 3, 6))
+    expected = np.dot(A, B)
+    A = sparse.csr_matrix(A)
+    actual = safe_sparse_dot(A, B)
+    assert_allclose(actual, expected)
+
+
+@pytest.mark.parametrize(
+    "A_array_constr", [np.array, sparse.csr_matrix], ids=["dense", "sparse"]
+)
+def test_safe_sparse_dot_2d_1d(A_array_constr):
+    rng = np.random.RandomState(0)
+
+    B = rng.random_sample((10))
+
+    # 2D @ 1D
+    A = rng.random_sample((30, 10))
+    expected = np.dot(A, B)
+    A = A_array_constr(A)
+    actual = safe_sparse_dot(A, B)
+    assert_allclose(actual, expected)
+
+    # 1D @ 2D
+    A = rng.random_sample((10, 30))
+    expected = np.dot(B, A)
+    A = A_array_constr(A)
+    actual = safe_sparse_dot(B, A)
+    assert_allclose(actual, expected)
+
+
+@pytest.mark.parametrize("dense_output", [True, False])
+def test_safe_sparse_dot_dense_output(dense_output):
+    rng = np.random.RandomState(0)
+
+    A = sparse.random(30, 10, density=0.1, random_state=rng)
+    B = sparse.random(10, 20, density=0.1, random_state=rng)
+
+    expected = A.dot(B)
+    actual = safe_sparse_dot(A, B, dense_output=dense_output)
+
+    assert sparse.issparse(actual) == (not dense_output)
+
+    if dense_output:
+        expected = expected.toarray()
+    assert_allclose_dense_sparse(actual, expected)
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_fast_dict.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_fast_dict.py
new file mode 100644
index 0000000000000000000000000000000000000000..050df133a2d24f50816bc296a5c868bbaa30d4a3
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_fast_dict.py
@@ -0,0 +1,31 @@
+""" Test fast_dict.
+"""
+import numpy as np
+
+from sklearn.utils._fast_dict import IntFloatDict, argmin
+
+
+def test_int_float_dict():
+    rng = np.random.RandomState(0)
+    keys = np.unique(rng.randint(100, size=10).astype(np.intp))
+    values = rng.rand(len(keys))
+
+    d = IntFloatDict(keys, values)
+    for key, value in zip(keys, values):
+        assert d[key] == value
+    assert len(d) == len(keys)
+
+    d.append(120, 3.0)
+    assert d[120] == 3.0
+    assert len(d) == len(keys) + 1
+    for i in range(2000):
+        d.append(i + 1000, 4.0)
+    assert d[1100] == 4.0
+
+
+def test_int_float_dict_argmin():
+    # Test the argmin implementation on the IntFloatDict
+    keys = np.arange(100, dtype=np.intp)
+    values = np.arange(100, dtype=np.float64)
+    d = IntFloatDict(keys, values)
+    assert argmin(d) == (0, 0)
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_metaestimators.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_metaestimators.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a75ab387df6098452ff9719f0b75d093ab34ffe
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_metaestimators.py
@@ -0,0 +1,172 @@
+import numpy as np
+import pytest
+import warnings
+
+import pickle
+
+from sklearn.utils.metaestimators import if_delegate_has_method
+from sklearn.utils.metaestimators import available_if
+
+
+class Prefix:
+    def func(self):
+        pass
+
+
+class MockMetaEstimator:
+    """This is a mock meta estimator"""
+
+    a_prefix = Prefix()
+
+    @if_delegate_has_method(delegate="a_prefix")
+    def func(self):
+        """This is a mock delegated function"""
+        pass
+
+
+@pytest.mark.filterwarnings("ignore:if_delegate_has_method was deprecated")
+def test_delegated_docstring():
+    assert "This is a mock delegated function" in str(
+        MockMetaEstimator.__dict__["func"].__doc__
+    )
+    assert "This is a mock delegated function" in str(MockMetaEstimator.func.__doc__)
+    assert "This is a mock delegated function" in str(MockMetaEstimator().func.__doc__)
+
+
+class MetaEst:
+    """A mock meta estimator"""
+
+    def __init__(self, sub_est, better_sub_est=None):
+        self.sub_est = sub_est
+        self.better_sub_est = better_sub_est
+
+    @if_delegate_has_method(delegate="sub_est")
+    def predict(self):
+        pass
+
+
+class MetaEstTestTuple(MetaEst):
+    """A mock meta estimator to test passing a tuple of delegates"""
+
+    @if_delegate_has_method(delegate=("sub_est", "better_sub_est"))
+    def predict(self):
+        pass
+
+
+class MetaEstTestList(MetaEst):
+    """A mock meta estimator to test passing a list of delegates"""
+
+    @if_delegate_has_method(delegate=["sub_est", "better_sub_est"])
+    def predict(self):
+        pass
+
+
+class HasPredict:
+    """A mock sub-estimator with predict method"""
+
+    def predict(self):
+        pass
+
+
+class HasNoPredict:
+    """A mock sub-estimator with no predict method"""
+
+    pass
+
+
+class HasPredictAsNDArray:
+    """A mock sub-estimator where predict is a NumPy array"""
+
+    predict = np.ones((10, 2), dtype=np.int64)
+
+
+@pytest.mark.filterwarnings("ignore:if_delegate_has_method was deprecated")
+def test_if_delegate_has_method():
+    assert hasattr(MetaEst(HasPredict()), "predict")
+    assert not hasattr(MetaEst(HasNoPredict()), "predict")
+    assert not hasattr(MetaEstTestTuple(HasNoPredict(), HasNoPredict()), "predict")
+    assert hasattr(MetaEstTestTuple(HasPredict(), HasNoPredict()), "predict")
+    assert not hasattr(MetaEstTestTuple(HasNoPredict(), HasPredict()), "predict")
+    assert not hasattr(MetaEstTestList(HasNoPredict(), HasPredict()), "predict")
+    assert hasattr(MetaEstTestList(HasPredict(), HasPredict()), "predict")
+
+
+class AvailableParameterEstimator:
+    """This estimator's `available` parameter toggles the presence of a method"""
+
+    def __init__(self, available=True, return_value=1):
+        self.available = available
+        self.return_value = return_value
+
+    @available_if(lambda est: est.available)
+    def available_func(self):
+        """This is a mock available_if function"""
+        return self.return_value
+
+
+def test_available_if_docstring():
+    assert "This is a mock available_if function" in str(
+        AvailableParameterEstimator.__dict__["available_func"].__doc__
+    )
+    assert "This is a mock available_if function" in str(
+        AvailableParameterEstimator.available_func.__doc__
+    )
+    assert "This is a mock available_if function" in str(
+        AvailableParameterEstimator().available_func.__doc__
+    )
+
+
+def test_available_if():
+    assert hasattr(AvailableParameterEstimator(), "available_func")
+    assert not hasattr(AvailableParameterEstimator(available=False), "available_func")
+
+
+def test_available_if_unbound_method():
+    # This is a non regression test for:
+    # https://github.com/scikit-learn/scikit-learn/issues/20614
+    # to make sure that decorated functions can be used as an unbound method,
+    # for instance when monkeypatching.
+    est = AvailableParameterEstimator()
+    AvailableParameterEstimator.available_func(est)
+
+    est = AvailableParameterEstimator(available=False)
+    with pytest.raises(
+        AttributeError,
+        match="This 'AvailableParameterEstimator' has no attribute 'available_func'",
+    ):
+        AvailableParameterEstimator.available_func(est)
+
+
+@pytest.mark.filterwarnings("ignore:if_delegate_has_method was deprecated")
+def test_if_delegate_has_method_numpy_array():
+    """Check that we can check for an attribute that is a NumPy array.
+
+    This is a non-regression test for:
+    https://github.com/scikit-learn/scikit-learn/issues/21144
+    """
+    estimator = MetaEst(HasPredictAsNDArray())
+    assert hasattr(estimator, "predict")
+
+
+def test_if_delegate_has_method_deprecated():
+    """Check the deprecation warning of if_delegate_has_method"""
+    # don't warn when creating the decorator
+    with warnings.catch_warnings():
+        warnings.simplefilter("error", FutureWarning)
+        _ = if_delegate_has_method(delegate="predict")
+
+    # Only when calling it
+    with pytest.warns(FutureWarning, match="if_delegate_has_method was deprecated"):
+        hasattr(MetaEst(HasPredict()), "predict")
+
+
+def test_available_if_methods_can_be_pickled():
+    """Check that available_if methods can be pickled.
+
+    Non-regression test for #21344.
+    """
+    return_value = 10
+    est = AvailableParameterEstimator(available=True, return_value=return_value)
+    pickled_bytes = pickle.dumps(est.available_func)
+    unpickled_func = pickle.loads(pickled_bytes)
+    assert unpickled_func() == return_value
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_multiclass.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_multiclass.py
new file mode 100644
index 0000000000000000000000000000000000000000..731edbefc3925363501356684eeaf655c3158330
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_multiclass.py
@@ -0,0 +1,494 @@
+import numpy as np
+import scipy.sparse as sp
+from itertools import product
+import pytest
+
+from scipy.sparse import issparse
+from scipy.sparse import csc_matrix
+from scipy.sparse import csr_matrix
+from scipy.sparse import coo_matrix
+from scipy.sparse import dok_matrix
+from scipy.sparse import lil_matrix
+
+from sklearn.utils._testing import assert_array_equal
+from sklearn.utils._testing import assert_array_almost_equal
+from sklearn.utils._testing import assert_allclose
+from sklearn.utils.estimator_checks import _NotAnArray
+
+from sklearn.utils.multiclass import unique_labels
+from sklearn.utils.multiclass import is_multilabel
+from sklearn.utils.multiclass import type_of_target
+from sklearn.utils.multiclass import class_distribution
+from sklearn.utils.multiclass import check_classification_targets
+from sklearn.utils.multiclass import _ovr_decision_function
+
+from sklearn.utils.metaestimators import _safe_split
+from sklearn.model_selection import ShuffleSplit
+from sklearn.svm import SVC
+from sklearn import datasets
+
+sparse_multilable_explicit_zero = csc_matrix(np.array([[0, 1], [1, 0]]))
+sparse_multilable_explicit_zero[:, 0] = 0
+
+
+def _generate_sparse(
+    matrix,
+    matrix_types=(csr_matrix, csc_matrix, coo_matrix, dok_matrix, lil_matrix),
+    dtypes=(bool, int, np.int8, np.uint8, float, np.float32),
+):
+    return [
+        matrix_type(matrix, dtype=dtype)
+        for matrix_type in matrix_types
+        for dtype in dtypes
+    ]
+
+
+EXAMPLES = {
+    "multilabel-indicator": [
+        # valid when the data is formatted as sparse or dense, identified
+        # by CSR format when the testing takes place
+        csr_matrix(np.random.RandomState(42).randint(2, size=(10, 10))),
+        [[0, 1], [1, 0]],
+        [[0, 1]],
+        sparse_multilable_explicit_zero,
+        *_generate_sparse([[0, 1], [1, 0]]),
+        *_generate_sparse([[0, 0], [0, 0]]),
+        *_generate_sparse([[0, 1]]),
+        # Only valid when data is dense
+        [[-1, 1], [1, -1]],
+        np.array([[-1, 1], [1, -1]]),
+        np.array([[-3, 3], [3, -3]]),
+        _NotAnArray(np.array([[-3, 3], [3, -3]])),
+    ],
+    "multiclass": [
+        [1, 0, 2, 2, 1, 4, 2, 4, 4, 4],
+        np.array([1, 0, 2]),
+        np.array([1, 0, 2], dtype=np.int8),
+        np.array([1, 0, 2], dtype=np.uint8),
+        np.array([1, 0, 2], dtype=float),
+        np.array([1, 0, 2], dtype=np.float32),
+        np.array([[1], [0], [2]]),
+        _NotAnArray(np.array([1, 0, 2])),
+        [0, 1, 2],
+        ["a", "b", "c"],
+        np.array(["a", "b", "c"]),
+        np.array(["a", "b", "c"], dtype=object),
+        np.array(["a", "b", "c"], dtype=object),
+    ],
+    "multiclass-multioutput": [
+        [[1, 0, 2, 2], [1, 4, 2, 4]],
+        [["a", "b"], ["c", "d"]],
+        np.array([[1, 0, 2, 2], [1, 4, 2, 4]]),
+        np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.int8),
+        np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.uint8),
+        np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=float),
+        np.array([[1, 0, 2, 2], [1, 4, 2, 4]], dtype=np.float32),
+        *_generate_sparse(
+            [[1, 0, 2, 2], [1, 4, 2, 4]],
+            matrix_types=(csr_matrix, csc_matrix),
+            dtypes=(int, np.int8, np.uint8, float, np.float32),
+        ),
+        np.array([["a", "b"], ["c", "d"]]),
+        np.array([["a", "b"], ["c", "d"]]),
+        np.array([["a", "b"], ["c", "d"]], dtype=object),
+        np.array([[1, 0, 2]]),
+        _NotAnArray(np.array([[1, 0, 2]])),
+    ],
+    "binary": [
+        [0, 1],
+        [1, 1],
+        [],
+        [0],
+        np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1]),
+        np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=bool),
+        np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.int8),
+        np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.uint8),
+        np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=float),
+        np.array([0, 1, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.float32),
+        np.array([[0], [1]]),
+        _NotAnArray(np.array([[0], [1]])),
+        [1, -1],
+        [3, 5],
+        ["a"],
+        ["a", "b"],
+        ["abc", "def"],
+        np.array(["abc", "def"]),
+        ["a", "b"],
+        np.array(["abc", "def"], dtype=object),
+    ],
+    "continuous": [
+        [1e-5],
+        [0, 0.5],
+        np.array([[0], [0.5]]),
+        np.array([[0], [0.5]], dtype=np.float32),
+    ],
+    "continuous-multioutput": [
+        np.array([[0, 0.5], [0.5, 0]]),
+        np.array([[0, 0.5], [0.5, 0]], dtype=np.float32),
+        np.array([[0, 0.5]]),
+        *_generate_sparse(
+            [[0, 0.5], [0.5, 0]],
+            matrix_types=(csr_matrix, csc_matrix),
+            dtypes=(float, np.float32),
+        ),
+        *_generate_sparse(
+            [[0, 0.5]],
+            matrix_types=(csr_matrix, csc_matrix),
+            dtypes=(float, np.float32),
+        ),
+    ],
+    "unknown": [
+        [[]],
+        np.array([[]], dtype=object),
+        [()],
+        # sequence of sequences that weren't supported even before deprecation
+        np.array([np.array([]), np.array([1, 2, 3])], dtype=object),
+        [np.array([]), np.array([1, 2, 3])],
+        [{1, 2, 3}, {1, 2}],
+        [frozenset([1, 2, 3]), frozenset([1, 2])],
+        # and also confusable as sequences of sequences
+        [{0: "a", 1: "b"}, {0: "a"}],
+        # ndim 0
+        np.array(0),
+        # empty second dimension
+        np.array([[], []]),
+        # 3d
+        np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]),
+    ],
+}
+
+NON_ARRAY_LIKE_EXAMPLES = [
+    {1, 2, 3},
+    {0: "a", 1: "b"},
+    {0: [5], 1: [5]},
+    "abc",
+    frozenset([1, 2, 3]),
+    None,
+]
+
+MULTILABEL_SEQUENCES = [
+    [[1], [2], [0, 1]],
+    [(), (2), (0, 1)],
+    np.array([[], [1, 2]], dtype="object"),
+    _NotAnArray(np.array([[], [1, 2]], dtype="object")),
+]
+
+
+def test_unique_labels():
+    # Empty iterable
+    with pytest.raises(ValueError):
+        unique_labels()
+
+    # Multiclass problem
+    assert_array_equal(unique_labels(range(10)), np.arange(10))
+    assert_array_equal(unique_labels(np.arange(10)), np.arange(10))
+    assert_array_equal(unique_labels([4, 0, 2]), np.array([0, 2, 4]))
+
+    # Multilabel indicator
+    assert_array_equal(
+        unique_labels(np.array([[0, 0, 1], [1, 0, 1], [0, 0, 0]])), np.arange(3)
+    )
+
+    assert_array_equal(unique_labels(np.array([[0, 0, 1], [0, 0, 0]])), np.arange(3))
+
+    # Several arrays passed
+    assert_array_equal(unique_labels([4, 0, 2], range(5)), np.arange(5))
+    assert_array_equal(unique_labels((0, 1, 2), (0,), (2, 1)), np.arange(3))
+
+    # Border line case with binary indicator matrix
+    with pytest.raises(ValueError):
+        unique_labels([4, 0, 2], np.ones((5, 5)))
+    with pytest.raises(ValueError):
+        unique_labels(np.ones((5, 4)), np.ones((5, 5)))
+
+    assert_array_equal(unique_labels(np.ones((4, 5)), np.ones((5, 5))), np.arange(5))
+
+
+def test_unique_labels_non_specific():
+    # Test unique_labels with a variety of collected examples
+
+    # Smoke test for all supported format
+    for format in ["binary", "multiclass", "multilabel-indicator"]:
+        for y in EXAMPLES[format]:
+            unique_labels(y)
+
+    # We don't support those format at the moment
+    for example in NON_ARRAY_LIKE_EXAMPLES:
+        with pytest.raises(ValueError):
+            unique_labels(example)
+
+    for y_type in [
+        "unknown",
+        "continuous",
+        "continuous-multioutput",
+        "multiclass-multioutput",
+    ]:
+        for example in EXAMPLES[y_type]:
+            with pytest.raises(ValueError):
+                unique_labels(example)
+
+
+def test_unique_labels_mixed_types():
+    # Mix with binary or multiclass and multilabel
+    mix_clf_format = product(
+        EXAMPLES["multilabel-indicator"], EXAMPLES["multiclass"] + EXAMPLES["binary"]
+    )
+
+    for y_multilabel, y_multiclass in mix_clf_format:
+        with pytest.raises(ValueError):
+            unique_labels(y_multiclass, y_multilabel)
+        with pytest.raises(ValueError):
+            unique_labels(y_multilabel, y_multiclass)
+
+    with pytest.raises(ValueError):
+        unique_labels([[1, 2]], [["a", "d"]])
+
+    with pytest.raises(ValueError):
+        unique_labels(["1", 2])
+
+    with pytest.raises(ValueError):
+        unique_labels([["1", 2], [1, 3]])
+
+    with pytest.raises(ValueError):
+        unique_labels([["1", "2"], [2, 3]])
+
+
+def test_is_multilabel():
+    for group, group_examples in EXAMPLES.items():
+        if group in ["multilabel-indicator"]:
+            dense_exp = True
+        else:
+            dense_exp = False
+
+        for example in group_examples:
+            # Only mark explicitly defined sparse examples as valid sparse
+            # multilabel-indicators
+            if group == "multilabel-indicator" and issparse(example):
+                sparse_exp = True
+            else:
+                sparse_exp = False
+
+            if issparse(example) or (
+                hasattr(example, "__array__")
+                and np.asarray(example).ndim == 2
+                and np.asarray(example).dtype.kind in "biuf"
+                and np.asarray(example).shape[1] > 0
+            ):
+                examples_sparse = [
+                    sparse_matrix(example)
+                    for sparse_matrix in [
+                        coo_matrix,
+                        csc_matrix,
+                        csr_matrix,
+                        dok_matrix,
+                        lil_matrix,
+                    ]
+                ]
+                for exmpl_sparse in examples_sparse:
+                    assert sparse_exp == is_multilabel(
+                        exmpl_sparse
+                    ), "is_multilabel(%r) should be %s" % (exmpl_sparse, sparse_exp)
+
+            # Densify sparse examples before testing
+            if issparse(example):
+                example = example.toarray()
+
+            assert dense_exp == is_multilabel(
+                example
+            ), "is_multilabel(%r) should be %s" % (example, dense_exp)
+
+
+def test_check_classification_targets():
+    for y_type in EXAMPLES.keys():
+        if y_type in ["unknown", "continuous", "continuous-multioutput"]:
+            for example in EXAMPLES[y_type]:
+                msg = "Unknown label type: "
+                with pytest.raises(ValueError, match=msg):
+                    check_classification_targets(example)
+        else:
+            for example in EXAMPLES[y_type]:
+                check_classification_targets(example)
+
+
+# @ignore_warnings
+def test_type_of_target():
+    for group, group_examples in EXAMPLES.items():
+        for example in group_examples:
+            assert (
+                type_of_target(example) == group
+            ), "type_of_target(%r) should be %r, got %r" % (
+                example,
+                group,
+                type_of_target(example),
+            )
+
+    for example in NON_ARRAY_LIKE_EXAMPLES:
+        msg_regex = r"Expected array-like \(array or non-string sequence\).*"
+        with pytest.raises(ValueError, match=msg_regex):
+            type_of_target(example)
+
+    for example in MULTILABEL_SEQUENCES:
+        msg = (
+            "You appear to be using a legacy multi-label data "
+            "representation. Sequence of sequences are no longer supported;"
+            " use a binary array or sparse matrix instead."
+        )
+        with pytest.raises(ValueError, match=msg):
+            type_of_target(example)
+
+
+def test_type_of_target_pandas_sparse():
+    pd = pytest.importorskip("pandas")
+
+    y = pd.arrays.SparseArray([1, np.nan, np.nan, 1, np.nan])
+    msg = "y cannot be class 'SparseSeries' or 'SparseArray'"
+    with pytest.raises(ValueError, match=msg):
+        type_of_target(y)
+
+
+def test_type_of_target_pandas_nullable():
+    """Check that type_of_target works with pandas nullable dtypes."""
+    pd = pytest.importorskip("pandas")
+
+    for dtype in ["Int32", "Float32"]:
+        y_true = pd.Series([1, 0, 2, 3, 4], dtype=dtype)
+        assert type_of_target(y_true) == "multiclass"
+
+        y_true = pd.Series([1, 0, 1, 0], dtype=dtype)
+        assert type_of_target(y_true) == "binary"
+
+    y_true = pd.DataFrame([[1.4, 3.1], [3.1, 1.4]], dtype="Float32")
+    assert type_of_target(y_true) == "continuous-multioutput"
+
+    y_true = pd.DataFrame([[0, 1], [1, 1]], dtype="Int32")
+    assert type_of_target(y_true) == "multilabel-indicator"
+
+    y_true = pd.DataFrame([[1, 2], [3, 1]], dtype="Int32")
+    assert type_of_target(y_true) == "multiclass-multioutput"
+
+
+@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean"])
+def test_unique_labels_pandas_nullable(dtype):
+    """Checks that unique_labels work with pandas nullable dtypes.
+
+    Non-regression test for gh-25634.
+    """
+    pd = pytest.importorskip("pandas")
+
+    y_true = pd.Series([1, 0, 0, 1, 0, 1, 1, 0, 1], dtype=dtype)
+    y_predicted = pd.Series([0, 0, 1, 1, 0, 1, 1, 1, 1], dtype="int64")
+
+    labels = unique_labels(y_true, y_predicted)
+    assert_array_equal(labels, [0, 1])
+
+
+def test_class_distribution():
+    y = np.array(
+        [
+            [1, 0, 0, 1],
+            [2, 2, 0, 1],
+            [1, 3, 0, 1],
+            [4, 2, 0, 1],
+            [2, 0, 0, 1],
+            [1, 3, 0, 1],
+        ]
+    )
+    # Define the sparse matrix with a mix of implicit and explicit zeros
+    data = np.array([1, 2, 1, 4, 2, 1, 0, 2, 3, 2, 3, 1, 1, 1, 1, 1, 1])
+    indices = np.array([0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 5, 0, 1, 2, 3, 4, 5])
+    indptr = np.array([0, 6, 11, 11, 17])
+    y_sp = sp.csc_matrix((data, indices, indptr), shape=(6, 4))
+
+    classes, n_classes, class_prior = class_distribution(y)
+    classes_sp, n_classes_sp, class_prior_sp = class_distribution(y_sp)
+    classes_expected = [[1, 2, 4], [0, 2, 3], [0], [1]]
+    n_classes_expected = [3, 3, 1, 1]
+    class_prior_expected = [[3 / 6, 2 / 6, 1 / 6], [1 / 3, 1 / 3, 1 / 3], [1.0], [1.0]]
+
+    for k in range(y.shape[1]):
+        assert_array_almost_equal(classes[k], classes_expected[k])
+        assert_array_almost_equal(n_classes[k], n_classes_expected[k])
+        assert_array_almost_equal(class_prior[k], class_prior_expected[k])
+
+        assert_array_almost_equal(classes_sp[k], classes_expected[k])
+        assert_array_almost_equal(n_classes_sp[k], n_classes_expected[k])
+        assert_array_almost_equal(class_prior_sp[k], class_prior_expected[k])
+
+    # Test again with explicit sample weights
+    (classes, n_classes, class_prior) = class_distribution(
+        y, [1.0, 2.0, 1.0, 2.0, 1.0, 2.0]
+    )
+    (classes_sp, n_classes_sp, class_prior_sp) = class_distribution(
+        y, [1.0, 2.0, 1.0, 2.0, 1.0, 2.0]
+    )
+    class_prior_expected = [[4 / 9, 3 / 9, 2 / 9], [2 / 9, 4 / 9, 3 / 9], [1.0], [1.0]]
+
+    for k in range(y.shape[1]):
+        assert_array_almost_equal(classes[k], classes_expected[k])
+        assert_array_almost_equal(n_classes[k], n_classes_expected[k])
+        assert_array_almost_equal(class_prior[k], class_prior_expected[k])
+
+        assert_array_almost_equal(classes_sp[k], classes_expected[k])
+        assert_array_almost_equal(n_classes_sp[k], n_classes_expected[k])
+        assert_array_almost_equal(class_prior_sp[k], class_prior_expected[k])
+
+
+def test_safe_split_with_precomputed_kernel():
+    clf = SVC()
+    clfp = SVC(kernel="precomputed")
+
+    iris = datasets.load_iris()
+    X, y = iris.data, iris.target
+    K = np.dot(X, X.T)
+
+    cv = ShuffleSplit(test_size=0.25, random_state=0)
+    train, test = list(cv.split(X))[0]
+
+    X_train, y_train = _safe_split(clf, X, y, train)
+    K_train, y_train2 = _safe_split(clfp, K, y, train)
+    assert_array_almost_equal(K_train, np.dot(X_train, X_train.T))
+    assert_array_almost_equal(y_train, y_train2)
+
+    X_test, y_test = _safe_split(clf, X, y, test, train)
+    K_test, y_test2 = _safe_split(clfp, K, y, test, train)
+    assert_array_almost_equal(K_test, np.dot(X_test, X_train.T))
+    assert_array_almost_equal(y_test, y_test2)
+
+
+def test_ovr_decision_function():
+    # test properties for ovr decision function
+
+    predictions = np.array([[0, 1, 1], [0, 1, 0], [0, 1, 1], [0, 1, 1]])
+
+    confidences = np.array(
+        [[-1e16, 0, -1e16], [1.0, 2.0, -3.0], [-5.0, 2.0, 5.0], [-0.5, 0.2, 0.5]]
+    )
+
+    n_classes = 3
+
+    dec_values = _ovr_decision_function(predictions, confidences, n_classes)
+
+    # check that the decision values are within 0.5 range of the votes
+    votes = np.array([[1, 0, 2], [1, 1, 1], [1, 0, 2], [1, 0, 2]])
+
+    assert_allclose(votes, dec_values, atol=0.5)
+
+    # check that the prediction are what we expect
+    # highest vote or highest confidence if there is a tie.
+    # for the second sample we have a tie (should be won by 1)
+    expected_prediction = np.array([2, 1, 2, 2])
+    assert_array_equal(np.argmax(dec_values, axis=1), expected_prediction)
+
+    # third and fourth sample have the same vote but third sample
+    # has higher confidence, this should reflect on the decision values
+    assert dec_values[2, 2] > dec_values[3, 2]
+
+    # assert subset invariance.
+    dec_values_one = [
+        _ovr_decision_function(
+            np.array([predictions[i]]), np.array([confidences[i]]), n_classes
+        )[0]
+        for i in range(4)
+    ]
+
+    assert_allclose(dec_values, dec_values_one, atol=1e-6)
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_murmurhash.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_murmurhash.py
new file mode 100644
index 0000000000000000000000000000000000000000..4403c9a49275ccbff1cf84adc96075d97bf881f6
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_murmurhash.py
@@ -0,0 +1,74 @@
+# Author: Olivier Grisel 
+#
+# License: BSD 3 clause
+
+import numpy as np
+from sklearn.utils.murmurhash import murmurhash3_32
+from numpy.testing import assert_array_almost_equal
+from numpy.testing import assert_array_equal
+
+
+def test_mmhash3_int():
+    assert murmurhash3_32(3) == 847579505
+    assert murmurhash3_32(3, seed=0) == 847579505
+    assert murmurhash3_32(3, seed=42) == -1823081949
+
+    assert murmurhash3_32(3, positive=False) == 847579505
+    assert murmurhash3_32(3, seed=0, positive=False) == 847579505
+    assert murmurhash3_32(3, seed=42, positive=False) == -1823081949
+
+    assert murmurhash3_32(3, positive=True) == 847579505
+    assert murmurhash3_32(3, seed=0, positive=True) == 847579505
+    assert murmurhash3_32(3, seed=42, positive=True) == 2471885347
+
+
+def test_mmhash3_int_array():
+    rng = np.random.RandomState(42)
+    keys = rng.randint(-5342534, 345345, size=3 * 2 * 1).astype(np.int32)
+    keys = keys.reshape((3, 2, 1))
+
+    for seed in [0, 42]:
+        expected = np.array([murmurhash3_32(int(k), seed) for k in keys.flat])
+        expected = expected.reshape(keys.shape)
+        assert_array_equal(murmurhash3_32(keys, seed), expected)
+
+    for seed in [0, 42]:
+        expected = np.array([murmurhash3_32(k, seed, positive=True) for k in keys.flat])
+        expected = expected.reshape(keys.shape)
+        assert_array_equal(murmurhash3_32(keys, seed, positive=True), expected)
+
+
+def test_mmhash3_bytes():
+    assert murmurhash3_32(b"foo", 0) == -156908512
+    assert murmurhash3_32(b"foo", 42) == -1322301282
+
+    assert murmurhash3_32(b"foo", 0, positive=True) == 4138058784
+    assert murmurhash3_32(b"foo", 42, positive=True) == 2972666014
+
+
+def test_mmhash3_unicode():
+    assert murmurhash3_32("foo", 0) == -156908512
+    assert murmurhash3_32("foo", 42) == -1322301282
+
+    assert murmurhash3_32("foo", 0, positive=True) == 4138058784
+    assert murmurhash3_32("foo", 42, positive=True) == 2972666014
+
+
+def test_no_collision_on_byte_range():
+    previous_hashes = set()
+    for i in range(100):
+        h = murmurhash3_32(" " * i, 0)
+        assert h not in previous_hashes, "Found collision on growing empty string"
+
+
+def test_uniform_distribution():
+    n_bins, n_samples = 10, 100000
+    bins = np.zeros(n_bins, dtype=np.float64)
+
+    for i in range(n_samples):
+        bins[murmurhash3_32(i, positive=True) % n_bins] += 1
+
+    means = bins / n_samples
+    expected = np.full(n_bins, 1.0 / n_bins)
+
+    assert_array_almost_equal(means / expected, np.ones(n_bins), 2)
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_optimize.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..82719635366b05f381a4d3ab65890b4f4ddd2d8b
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_optimize.py
@@ -0,0 +1,32 @@
+import numpy as np
+
+from sklearn.utils.optimize import _newton_cg
+from scipy.optimize import fmin_ncg
+
+from sklearn.utils._testing import assert_array_almost_equal
+
+
+def test_newton_cg():
+    # Test that newton_cg gives same result as scipy's fmin_ncg
+
+    rng = np.random.RandomState(0)
+    A = rng.normal(size=(10, 10))
+    x0 = np.ones(10)
+
+    def func(x):
+        Ax = A.dot(x)
+        return 0.5 * (Ax).dot(Ax)
+
+    def grad(x):
+        return A.T.dot(A.dot(x))
+
+    def hess(x, p):
+        return p.dot(A.T.dot(A.dot(x.all())))
+
+    def grad_hess(x):
+        return grad(x), lambda x: A.T.dot(A.dot(x))
+
+    assert_array_almost_equal(
+        _newton_cg(grad_hess, func, grad, x0, tol=1e-10)[0],
+        fmin_ncg(f=func, x0=x0, fprime=grad, fhess_p=hess),
+    )
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_parallel.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_parallel.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f56c584300d18e4c4a97111ab225b824eb3052b
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_parallel.py
@@ -0,0 +1,101 @@
+import time
+
+import joblib
+import numpy as np
+import pytest
+from numpy.testing import assert_array_equal
+
+from sklearn import config_context, get_config
+from sklearn.compose import make_column_transformer
+from sklearn.datasets import load_iris
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.model_selection import GridSearchCV
+from sklearn.pipeline import make_pipeline
+from sklearn.preprocessing import StandardScaler
+
+from sklearn.utils.parallel import delayed, Parallel
+
+
+def get_working_memory():
+    return get_config()["working_memory"]
+
+
+@pytest.mark.parametrize("n_jobs", [1, 2])
+@pytest.mark.parametrize("backend", ["loky", "threading", "multiprocessing"])
+def test_configuration_passes_through_to_joblib(n_jobs, backend):
+    # Tests that the global global configuration is passed to joblib jobs
+
+    with config_context(working_memory=123):
+        results = Parallel(n_jobs=n_jobs, backend=backend)(
+            delayed(get_working_memory)() for _ in range(2)
+        )
+
+    assert_array_equal(results, [123] * 2)
+
+
+def test_parallel_delayed_warnings():
+    """Informative warnings should be raised when mixing sklearn and joblib API"""
+    # We should issue a warning when one wants to use sklearn.utils.fixes.Parallel
+    # with joblib.delayed. The config will not be propagated to the workers.
+    warn_msg = "`sklearn.utils.parallel.Parallel` needs to be used in conjunction"
+    with pytest.warns(UserWarning, match=warn_msg) as records:
+        Parallel()(joblib.delayed(time.sleep)(0) for _ in range(10))
+    assert len(records) == 10
+
+    # We should issue a warning if one wants to use sklearn.utils.fixes.delayed with
+    # joblib.Parallel
+    warn_msg = (
+        "`sklearn.utils.parallel.delayed` should be used with "
+        "`sklearn.utils.parallel.Parallel` to make it possible to propagate"
+    )
+    with pytest.warns(UserWarning, match=warn_msg) as records:
+        joblib.Parallel()(delayed(time.sleep)(0) for _ in range(10))
+    assert len(records) == 10
+
+
+@pytest.mark.parametrize("n_jobs", [1, 2])
+def test_dispatch_config_parallel(n_jobs):
+    """Check that we properly dispatch the configuration in parallel processing.
+
+    Non-regression test for:
+    https://github.com/scikit-learn/scikit-learn/issues/25239
+    """
+    pd = pytest.importorskip("pandas")
+    iris = load_iris(as_frame=True)
+
+    class TransformerRequiredDataFrame(StandardScaler):
+        def fit(self, X, y=None):
+            assert isinstance(X, pd.DataFrame), "X should be a DataFrame"
+            return super().fit(X, y)
+
+        def transform(self, X, y=None):
+            assert isinstance(X, pd.DataFrame), "X should be a DataFrame"
+            return super().transform(X, y)
+
+    dropper = make_column_transformer(
+        ("drop", [0]),
+        remainder="passthrough",
+        n_jobs=n_jobs,
+    )
+    param_grid = {"randomforestclassifier__max_depth": [1, 2, 3]}
+    search_cv = GridSearchCV(
+        make_pipeline(
+            dropper,
+            TransformerRequiredDataFrame(),
+            RandomForestClassifier(n_estimators=5, n_jobs=n_jobs),
+        ),
+        param_grid,
+        cv=5,
+        n_jobs=n_jobs,
+        error_score="raise",  # this search should not fail
+    )
+
+    # make sure that `fit` would fail in case we don't request dataframe
+    with pytest.raises(AssertionError, match="X should be a DataFrame"):
+        search_cv.fit(iris.data, iris.target)
+
+    with config_context(transform_output="pandas"):
+        # we expect each intermediate steps to output a DataFrame
+        search_cv.fit(iris.data, iris.target)
+
+    assert not np.isnan(search_cv.cv_results_["mean_test_score"]).any()
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_random.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_random.py
new file mode 100644
index 0000000000000000000000000000000000000000..320ebe8b1ae658bc5a30504113036cc4470fe2cd
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_random.py
@@ -0,0 +1,193 @@
+import numpy as np
+import pytest
+import scipy.sparse as sp
+from scipy.special import comb
+from numpy.testing import assert_array_almost_equal
+
+from sklearn.utils.random import _random_choice_csc, sample_without_replacement
+from sklearn.utils._random import _our_rand_r_py
+
+
+###############################################################################
+# test custom sampling without replacement algorithm
+###############################################################################
+def test_invalid_sample_without_replacement_algorithm():
+    with pytest.raises(ValueError):
+        sample_without_replacement(5, 4, "unknown")
+
+
+def test_sample_without_replacement_algorithms():
+    methods = ("auto", "tracking_selection", "reservoir_sampling", "pool")
+
+    for m in methods:
+
+        def sample_without_replacement_method(
+            n_population, n_samples, random_state=None
+        ):
+            return sample_without_replacement(
+                n_population, n_samples, method=m, random_state=random_state
+            )
+
+        check_edge_case_of_sample_int(sample_without_replacement_method)
+        check_sample_int(sample_without_replacement_method)
+        check_sample_int_distribution(sample_without_replacement_method)
+
+
+def check_edge_case_of_sample_int(sample_without_replacement):
+
+    # n_population < n_sample
+    with pytest.raises(ValueError):
+        sample_without_replacement(0, 1)
+    with pytest.raises(ValueError):
+        sample_without_replacement(1, 2)
+
+    # n_population == n_samples
+    assert sample_without_replacement(0, 0).shape == (0,)
+
+    assert sample_without_replacement(1, 1).shape == (1,)
+
+    # n_population >= n_samples
+    assert sample_without_replacement(5, 0).shape == (0,)
+    assert sample_without_replacement(5, 1).shape == (1,)
+
+    # n_population < 0 or n_samples < 0
+    with pytest.raises(ValueError):
+        sample_without_replacement(-1, 5)
+    with pytest.raises(ValueError):
+        sample_without_replacement(5, -1)
+
+
+def check_sample_int(sample_without_replacement):
+    # This test is heavily inspired from test_random.py of python-core.
+    #
+    # For the entire allowable range of 0 <= k <= N, validate that
+    # the sample is of the correct length and contains only unique items
+    n_population = 100
+
+    for n_samples in range(n_population + 1):
+        s = sample_without_replacement(n_population, n_samples)
+        assert len(s) == n_samples
+        unique = np.unique(s)
+        assert np.size(unique) == n_samples
+        assert np.all(unique < n_population)
+
+    # test edge case n_population == n_samples == 0
+    assert np.size(sample_without_replacement(0, 0)) == 0
+
+
+def check_sample_int_distribution(sample_without_replacement):
+    # This test is heavily inspired from test_random.py of python-core.
+    #
+    # For the entire allowable range of 0 <= k <= N, validate that
+    # sample generates all possible permutations
+    n_population = 10
+
+    # a large number of trials prevents false negatives without slowing normal
+    # case
+    n_trials = 10000
+
+    for n_samples in range(n_population):
+        # Counting the number of combinations is not as good as counting the
+        # the number of permutations. However, it works with sampling algorithm
+        # that does not provide a random permutation of the subset of integer.
+        n_expected = comb(n_population, n_samples, exact=True)
+
+        output = {}
+        for i in range(n_trials):
+            output[
+                frozenset(sample_without_replacement(n_population, n_samples))
+            ] = None
+
+            if len(output) == n_expected:
+                break
+        else:
+            raise AssertionError(
+                "number of combinations != number of expected (%s != %s)"
+                % (len(output), n_expected)
+            )
+
+
+def test_random_choice_csc(n_samples=10000, random_state=24):
+    # Explicit class probabilities
+    classes = [np.array([0, 1]), np.array([0, 1, 2])]
+    class_probabilities = [np.array([0.5, 0.5]), np.array([0.6, 0.1, 0.3])]
+
+    got = _random_choice_csc(n_samples, classes, class_probabilities, random_state)
+    assert sp.issparse(got)
+
+    for k in range(len(classes)):
+        p = np.bincount(got.getcol(k).toarray().ravel()) / float(n_samples)
+        assert_array_almost_equal(class_probabilities[k], p, decimal=1)
+
+    # Implicit class probabilities
+    classes = [[0, 1], [1, 2]]  # test for array-like support
+    class_probabilities = [np.array([0.5, 0.5]), np.array([0, 1 / 2, 1 / 2])]
+
+    got = _random_choice_csc(
+        n_samples=n_samples, classes=classes, random_state=random_state
+    )
+    assert sp.issparse(got)
+
+    for k in range(len(classes)):
+        p = np.bincount(got.getcol(k).toarray().ravel()) / float(n_samples)
+        assert_array_almost_equal(class_probabilities[k], p, decimal=1)
+
+    # Edge case probabilities 1.0 and 0.0
+    classes = [np.array([0, 1]), np.array([0, 1, 2])]
+    class_probabilities = [np.array([0.0, 1.0]), np.array([0.0, 1.0, 0.0])]
+
+    got = _random_choice_csc(n_samples, classes, class_probabilities, random_state)
+    assert sp.issparse(got)
+
+    for k in range(len(classes)):
+        p = (
+            np.bincount(
+                got.getcol(k).toarray().ravel(), minlength=len(class_probabilities[k])
+            )
+            / n_samples
+        )
+        assert_array_almost_equal(class_probabilities[k], p, decimal=1)
+
+    # One class target data
+    classes = [[1], [0]]  # test for array-like support
+    class_probabilities = [np.array([0.0, 1.0]), np.array([1.0])]
+
+    got = _random_choice_csc(
+        n_samples=n_samples, classes=classes, random_state=random_state
+    )
+    assert sp.issparse(got)
+
+    for k in range(len(classes)):
+        p = np.bincount(got.getcol(k).toarray().ravel()) / n_samples
+        assert_array_almost_equal(class_probabilities[k], p, decimal=1)
+
+
+def test_random_choice_csc_errors():
+    # the length of an array in classes and class_probabilities is mismatched
+    classes = [np.array([0, 1]), np.array([0, 1, 2, 3])]
+    class_probabilities = [np.array([0.5, 0.5]), np.array([0.6, 0.1, 0.3])]
+    with pytest.raises(ValueError):
+        _random_choice_csc(4, classes, class_probabilities, 1)
+
+    # the class dtype is not supported
+    classes = [np.array(["a", "1"]), np.array(["z", "1", "2"])]
+    class_probabilities = [np.array([0.5, 0.5]), np.array([0.6, 0.1, 0.3])]
+    with pytest.raises(ValueError):
+        _random_choice_csc(4, classes, class_probabilities, 1)
+
+    # the class dtype is not supported
+    classes = [np.array([4.2, 0.1]), np.array([0.1, 0.2, 9.4])]
+    class_probabilities = [np.array([0.5, 0.5]), np.array([0.6, 0.1, 0.3])]
+    with pytest.raises(ValueError):
+        _random_choice_csc(4, classes, class_probabilities, 1)
+
+    # Given probabilities don't sum to 1
+    classes = [np.array([0, 1]), np.array([0, 1, 2])]
+    class_probabilities = [np.array([0.5, 0.6]), np.array([0.6, 0.1, 0.3])]
+    with pytest.raises(ValueError):
+        _random_choice_csc(4, classes, class_probabilities, 1)
+
+
+def test_our_rand_r():
+    assert 131541053 == _our_rand_r_py(1273642419)
+    assert 270369 == _our_rand_r_py(0)
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_readonly_wrapper.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_readonly_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..38163cc2461ce878eb638401b74bea21507f701f
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_readonly_wrapper.py
@@ -0,0 +1,41 @@
+import numpy as np
+
+import pytest
+
+from sklearn.utils._readonly_array_wrapper import ReadonlyArrayWrapper, _test_sum
+from sklearn.utils._testing import create_memmap_backed_data
+
+
+def _readonly_array_copy(x):
+    """Return a copy of x with flag writeable set to False."""
+    y = x.copy()
+    y.flags["WRITEABLE"] = False
+    return y
+
+
+def _create_memmap_backed_data(data):
+    return create_memmap_backed_data(
+        data, mmap_mode="r", return_folder=False, aligned=True
+    )
+
+
+@pytest.mark.parametrize("readonly", [_readonly_array_copy, _create_memmap_backed_data])
+@pytest.mark.parametrize("dtype", [np.float32, np.float64, np.int32, np.int64])
+def test_readonly_array_wrapper(readonly, dtype):
+    """Test that ReadonlyWrapper allows working with fused-typed."""
+    x = np.arange(10).astype(dtype)
+    sum_origin = _test_sum(x)
+
+    # ReadonlyArrayWrapper works with writable buffers
+    sum_writable = _test_sum(ReadonlyArrayWrapper(x))
+    assert sum_writable == pytest.approx(sum_origin, rel=1e-11)
+
+    # Now, check on readonly buffers
+    x_readonly = readonly(x)
+
+    with pytest.raises(ValueError, match="buffer source array is read-only"):
+        _test_sum(x_readonly)
+
+    x_readonly = ReadonlyArrayWrapper(x_readonly)
+    sum_readonly = _test_sum(x_readonly)
+    assert sum_readonly == pytest.approx(sum_origin, rel=1e-11)
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_seq_dataset.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_seq_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c876fe62d74b8f964d6647cbed4f40c5e173cf0
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_seq_dataset.py
@@ -0,0 +1,170 @@
+# Author: Tom Dupre la Tour
+#         Joan Massich 
+#
+# License: BSD 3 clause
+
+import numpy as np
+import pytest
+import scipy.sparse as sp
+from numpy.testing import assert_array_equal
+from sklearn.utils._seq_dataset import (
+    ArrayDataset32,
+    ArrayDataset64,
+    CSRDataset32,
+    CSRDataset64,
+)
+
+from sklearn.datasets import load_iris
+from sklearn.utils._testing import assert_allclose
+
+iris = load_iris()
+X64 = iris.data.astype(np.float64)
+y64 = iris.target.astype(np.float64)
+X_csr64 = sp.csr_matrix(X64)
+sample_weight64 = np.arange(y64.size, dtype=np.float64)
+
+X32 = iris.data.astype(np.float32)
+y32 = iris.target.astype(np.float32)
+X_csr32 = sp.csr_matrix(X32)
+sample_weight32 = np.arange(y32.size, dtype=np.float32)
+
+
+def assert_csr_equal_values(current, expected):
+    current.eliminate_zeros()
+    expected.eliminate_zeros()
+    expected = expected.astype(current.dtype)
+    assert current.shape[0] == expected.shape[0]
+    assert current.shape[1] == expected.shape[1]
+    assert_array_equal(current.data, expected.data)
+    assert_array_equal(current.indices, expected.indices)
+    assert_array_equal(current.indptr, expected.indptr)
+
+
+def make_dense_dataset_32():
+    return ArrayDataset32(X32, y32, sample_weight32, seed=42)
+
+
+def make_dense_dataset_64():
+    return ArrayDataset64(X64, y64, sample_weight64, seed=42)
+
+
+def make_sparse_dataset_32():
+    return CSRDataset32(
+        X_csr32.data, X_csr32.indptr, X_csr32.indices, y32, sample_weight32, seed=42
+    )
+
+
+def make_sparse_dataset_64():
+    return CSRDataset64(
+        X_csr64.data, X_csr64.indptr, X_csr64.indices, y64, sample_weight64, seed=42
+    )
+
+
+@pytest.mark.parametrize(
+    "dataset_constructor",
+    [
+        make_dense_dataset_32,
+        make_dense_dataset_64,
+        make_sparse_dataset_32,
+        make_sparse_dataset_64,
+    ],
+)
+def test_seq_dataset_basic_iteration(dataset_constructor):
+    NUMBER_OF_RUNS = 5
+    dataset = dataset_constructor()
+    for _ in range(NUMBER_OF_RUNS):
+        # next sample
+        xi_, yi, swi, idx = dataset._next_py()
+        xi = sp.csr_matrix((xi_), shape=(1, X64.shape[1]))
+
+        assert_csr_equal_values(xi, X_csr64[idx])
+        assert yi == y64[idx]
+        assert swi == sample_weight64[idx]
+
+        # random sample
+        xi_, yi, swi, idx = dataset._random_py()
+        xi = sp.csr_matrix((xi_), shape=(1, X64.shape[1]))
+
+        assert_csr_equal_values(xi, X_csr64[idx])
+        assert yi == y64[idx]
+        assert swi == sample_weight64[idx]
+
+
+@pytest.mark.parametrize(
+    "make_dense_dataset,make_sparse_dataset",
+    [
+        (make_dense_dataset_32, make_sparse_dataset_32),
+        (make_dense_dataset_64, make_sparse_dataset_64),
+    ],
+)
+def test_seq_dataset_shuffle(make_dense_dataset, make_sparse_dataset):
+    dense_dataset, sparse_dataset = make_dense_dataset(), make_sparse_dataset()
+    # not shuffled
+    for i in range(5):
+        _, _, _, idx1 = dense_dataset._next_py()
+        _, _, _, idx2 = sparse_dataset._next_py()
+        assert idx1 == i
+        assert idx2 == i
+
+    for i in [132, 50, 9, 18, 58]:
+        _, _, _, idx1 = dense_dataset._random_py()
+        _, _, _, idx2 = sparse_dataset._random_py()
+        assert idx1 == i
+        assert idx2 == i
+
+    seed = 77
+    dense_dataset._shuffle_py(seed)
+    sparse_dataset._shuffle_py(seed)
+
+    idx_next = [63, 91, 148, 87, 29]
+    idx_shuffle = [137, 125, 56, 121, 127]
+    for i, j in zip(idx_next, idx_shuffle):
+        _, _, _, idx1 = dense_dataset._next_py()
+        _, _, _, idx2 = sparse_dataset._next_py()
+        assert idx1 == i
+        assert idx2 == i
+
+        _, _, _, idx1 = dense_dataset._random_py()
+        _, _, _, idx2 = sparse_dataset._random_py()
+        assert idx1 == j
+        assert idx2 == j
+
+
+@pytest.mark.parametrize(
+    "make_dataset_32,make_dataset_64",
+    [
+        (make_dense_dataset_32, make_dense_dataset_64),
+        (make_sparse_dataset_32, make_sparse_dataset_64),
+    ],
+)
+def test_fused_types_consistency(make_dataset_32, make_dataset_64):
+    dataset_32, dataset_64 = make_dataset_32(), make_dataset_64()
+    NUMBER_OF_RUNS = 5
+    for _ in range(NUMBER_OF_RUNS):
+        # next sample
+        (xi_data32, _, _), yi32, _, _ = dataset_32._next_py()
+        (xi_data64, _, _), yi64, _, _ = dataset_64._next_py()
+
+        assert xi_data32.dtype == np.float32
+        assert xi_data64.dtype == np.float64
+
+        assert_allclose(xi_data64, xi_data32, rtol=1e-5)
+        assert_allclose(yi64, yi32, rtol=1e-5)
+
+
+def test_buffer_dtype_mismatch_error():
+    with pytest.raises(ValueError, match="Buffer dtype mismatch"):
+        ArrayDataset64(X32, y32, sample_weight32, seed=42),
+
+    with pytest.raises(ValueError, match="Buffer dtype mismatch"):
+        ArrayDataset32(X64, y64, sample_weight64, seed=42),
+
+    with pytest.raises(ValueError, match="Buffer dtype mismatch"):
+        CSRDataset64(
+            X_csr32.data, X_csr32.indptr, X_csr32.indices, y32, sample_weight32, seed=42
+        ),
+
+    with pytest.raises(ValueError, match="Buffer dtype mismatch"):
+        CSRDataset32(
+            X_csr64.data, X_csr64.indptr, X_csr64.indices, y64, sample_weight64, seed=42
+        ),
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_set_output.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_set_output.py
new file mode 100644
index 0000000000000000000000000000000000000000..52213d771ee44ee60344db8acaf1e59055d6d1c9
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_set_output.py
@@ -0,0 +1,294 @@
+import pytest
+
+import numpy as np
+from scipy.sparse import csr_matrix
+from numpy.testing import assert_array_equal
+
+from sklearn._config import config_context, get_config
+from sklearn.utils._set_output import _wrap_in_pandas_container
+from sklearn.utils._set_output import _safe_set_output
+from sklearn.utils._set_output import _SetOutputMixin
+from sklearn.utils._set_output import _get_output_config
+
+
+def test__wrap_in_pandas_container_dense():
+    """Check _wrap_in_pandas_container for dense data."""
+    pd = pytest.importorskip("pandas")
+    X = np.asarray([[1, 0, 3], [0, 0, 1]])
+    columns = np.asarray(["f0", "f1", "f2"], dtype=object)
+    index = np.asarray([0, 1])
+
+    dense_named = _wrap_in_pandas_container(X, columns=lambda: columns, index=index)
+    assert isinstance(dense_named, pd.DataFrame)
+    assert_array_equal(dense_named.columns, columns)
+    assert_array_equal(dense_named.index, index)
+
+
+def test__wrap_in_pandas_container_dense_update_columns_and_index():
+    """Check that _wrap_in_pandas_container overrides columns and index."""
+    pd = pytest.importorskip("pandas")
+    X_df = pd.DataFrame([[1, 0, 3], [0, 0, 1]], columns=["a", "b", "c"])
+    new_columns = np.asarray(["f0", "f1", "f2"], dtype=object)
+    new_index = [10, 12]
+
+    new_df = _wrap_in_pandas_container(X_df, columns=new_columns, index=new_index)
+    assert_array_equal(new_df.columns, new_columns)
+
+    # Index does not change when the input is a DataFrame
+    assert_array_equal(new_df.index, X_df.index)
+
+
+def test__wrap_in_pandas_container_error_validation():
+    """Check errors in _wrap_in_pandas_container."""
+    X = np.asarray([[1, 0, 3], [0, 0, 1]])
+    X_csr = csr_matrix(X)
+    match = "Pandas output does not support sparse data"
+    with pytest.raises(ValueError, match=match):
+        _wrap_in_pandas_container(X_csr, columns=["a", "b", "c"])
+
+
+class EstimatorWithoutSetOutputAndWithoutTransform:
+    pass
+
+
+class EstimatorNoSetOutputWithTransform:
+    def transform(self, X, y=None):
+        return X  # pragma: no cover
+
+
+class EstimatorWithSetOutput(_SetOutputMixin):
+    def fit(self, X, y=None):
+        self.n_features_in_ = X.shape[1]
+        return self
+
+    def transform(self, X, y=None):
+        return X
+
+    def get_feature_names_out(self, input_features=None):
+        return np.asarray([f"X{i}" for i in range(self.n_features_in_)], dtype=object)
+
+
+def test__safe_set_output():
+    """Check _safe_set_output works as expected."""
+
+    # Estimator without transform will not raise when setting set_output for transform.
+    est = EstimatorWithoutSetOutputAndWithoutTransform()
+    _safe_set_output(est, transform="pandas")
+
+    # Estimator with transform but without set_output will raise
+    est = EstimatorNoSetOutputWithTransform()
+    with pytest.raises(ValueError, match="Unable to configure output"):
+        _safe_set_output(est, transform="pandas")
+
+    est = EstimatorWithSetOutput().fit(np.asarray([[1, 2, 3]]))
+    _safe_set_output(est, transform="pandas")
+    config = _get_output_config("transform", est)
+    assert config["dense"] == "pandas"
+
+    _safe_set_output(est, transform="default")
+    config = _get_output_config("transform", est)
+    assert config["dense"] == "default"
+
+    # transform is None is a no-op, so the config remains "default"
+    _safe_set_output(est, transform=None)
+    config = _get_output_config("transform", est)
+    assert config["dense"] == "default"
+
+
+class EstimatorNoSetOutputWithTransformNoFeatureNamesOut(_SetOutputMixin):
+    def transform(self, X, y=None):
+        return X  # pragma: no cover
+
+
+def test_set_output_mixin():
+    """Estimator without get_feature_names_out does not define `set_output`."""
+    est = EstimatorNoSetOutputWithTransformNoFeatureNamesOut()
+    assert not hasattr(est, "set_output")
+
+
+def test__safe_set_output_error():
+    """Check transform with invalid config."""
+    X = np.asarray([[1, 0, 3], [0, 0, 1]])
+
+    est = EstimatorWithSetOutput()
+    _safe_set_output(est, transform="bad")
+
+    msg = "output config must be 'default'"
+    with pytest.raises(ValueError, match=msg):
+        est.transform(X)
+
+
+def test_set_output_method():
+    """Check that the output is pandas."""
+    pd = pytest.importorskip("pandas")
+
+    X = np.asarray([[1, 0, 3], [0, 0, 1]])
+    est = EstimatorWithSetOutput().fit(X)
+
+    # transform=None is a no-op
+    est2 = est.set_output(transform=None)
+    assert est2 is est
+    X_trans_np = est2.transform(X)
+    assert isinstance(X_trans_np, np.ndarray)
+
+    est.set_output(transform="pandas")
+
+    X_trans_pd = est.transform(X)
+    assert isinstance(X_trans_pd, pd.DataFrame)
+
+
+def test_set_output_method_error():
+    """Check transform fails with invalid transform."""
+
+    X = np.asarray([[1, 0, 3], [0, 0, 1]])
+    est = EstimatorWithSetOutput().fit(X)
+    est.set_output(transform="bad")
+
+    msg = "output config must be 'default'"
+    with pytest.raises(ValueError, match=msg):
+        est.transform(X)
+
+
+def test__get_output_config():
+    """Check _get_output_config works as expected."""
+
+    # Without a configuration set, the global config is used
+    global_config = get_config()["transform_output"]
+    config = _get_output_config("transform")
+    assert config["dense"] == global_config
+
+    with config_context(transform_output="pandas"):
+        # with estimator=None, the global config is used
+        config = _get_output_config("transform")
+        assert config["dense"] == "pandas"
+
+        est = EstimatorNoSetOutputWithTransform()
+        config = _get_output_config("transform", est)
+        assert config["dense"] == "pandas"
+
+        est = EstimatorWithSetOutput()
+        # If estimator has not config, use global config
+        config = _get_output_config("transform", est)
+        assert config["dense"] == "pandas"
+
+        # If estimator has a config, use local config
+        est.set_output(transform="default")
+        config = _get_output_config("transform", est)
+        assert config["dense"] == "default"
+
+    est.set_output(transform="pandas")
+    config = _get_output_config("transform", est)
+    assert config["dense"] == "pandas"
+
+
+class EstimatorWithSetOutputNoAutoWrap(_SetOutputMixin, auto_wrap_output_keys=None):
+    def transform(self, X, y=None):
+        return X
+
+
+def test_get_output_auto_wrap_false():
+    """Check that auto_wrap_output_keys=None does not wrap."""
+    est = EstimatorWithSetOutputNoAutoWrap()
+    assert not hasattr(est, "set_output")
+
+    X = np.asarray([[1, 0, 3], [0, 0, 1]])
+    assert X is est.transform(X)
+
+
+def test_auto_wrap_output_keys_errors_with_incorrect_input():
+    msg = "auto_wrap_output_keys must be None or a tuple of keys."
+    with pytest.raises(ValueError, match=msg):
+
+        class BadEstimator(_SetOutputMixin, auto_wrap_output_keys="bad_parameter"):
+            pass
+
+
+class AnotherMixin:
+    def __init_subclass__(cls, custom_parameter, **kwargs):
+        super().__init_subclass__(**kwargs)
+        cls.custom_parameter = custom_parameter
+
+
+def test_set_output_mixin_custom_mixin():
+    """Check that multiple init_subclasses passes parameters up."""
+
+    class BothMixinEstimator(_SetOutputMixin, AnotherMixin, custom_parameter=123):
+        def transform(self, X, y=None):
+            return X
+
+        def get_feature_names_out(self, input_features=None):
+            return input_features
+
+    est = BothMixinEstimator()
+    assert est.custom_parameter == 123
+    assert hasattr(est, "set_output")
+
+
+def test__wrap_in_pandas_container_column_errors():
+    """If a callable `columns` errors, it has the same semantics as columns=None."""
+    pd = pytest.importorskip("pandas")
+
+    def get_columns():
+        raise ValueError("No feature names defined")
+
+    X_df = pd.DataFrame({"feat1": [1, 2, 3], "feat2": [3, 4, 5]})
+
+    X_wrapped = _wrap_in_pandas_container(X_df, columns=get_columns)
+    assert_array_equal(X_wrapped.columns, X_df.columns)
+
+    X_np = np.asarray([[1, 3], [2, 4], [3, 5]])
+    X_wrapped = _wrap_in_pandas_container(X_np, columns=get_columns)
+    assert_array_equal(X_wrapped.columns, range(X_np.shape[1]))
+
+
+def test_set_output_mro():
+    """Check that multi-inheritance resolves to the correct class method.
+
+    Non-regression test gh-25293.
+    """
+
+    class Base(_SetOutputMixin):
+        def transform(self, X):
+            return "Base"  # noqa
+
+    class A(Base):
+        pass
+
+    class B(Base):
+        def transform(self, X):
+            return "B"
+
+    class C(A, B):
+        pass
+
+    assert C().transform(None) == "B"
+
+
+class EstimatorWithSetOutputIndex(_SetOutputMixin):
+    def fit(self, X, y=None):
+        self.n_features_in_ = X.shape[1]
+        return self
+
+    def transform(self, X, y=None):
+        import pandas as pd
+
+        # transform by giving output a new index.
+        return pd.DataFrame(X.to_numpy(), index=[f"s{i}" for i in range(X.shape[0])])
+
+    def get_feature_names_out(self, input_features=None):
+        return np.asarray([f"X{i}" for i in range(self.n_features_in_)], dtype=object)
+
+
+def test_set_output_pandas_keep_index():
+    """Check that set_output does not override index.
+
+    Non-regression test for gh-25730.
+    """
+    pd = pytest.importorskip("pandas")
+
+    X = pd.DataFrame([[1, 2, 3], [4, 5, 6]], index=[0, 1])
+    est = EstimatorWithSetOutputIndex().set_output(transform="pandas")
+    est.fit(X)
+
+    X_trans = est.transform(X)
+    assert_array_equal(X_trans.index, ["s0", "s1"])
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_shortest_path.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_shortest_path.py
new file mode 100644
index 0000000000000000000000000000000000000000..7994f1f48863a54fe9438e4aec6cb79a3c2d2c26
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_shortest_path.py
@@ -0,0 +1,64 @@
+from collections import defaultdict
+
+import numpy as np
+from numpy.testing import assert_array_almost_equal
+from sklearn.utils.graph import single_source_shortest_path_length
+
+
+def floyd_warshall_slow(graph, directed=False):
+    N = graph.shape[0]
+
+    # set nonzero entries to infinity
+    graph[np.where(graph == 0)] = np.inf
+
+    # set diagonal to zero
+    graph.flat[:: N + 1] = 0
+
+    if not directed:
+        graph = np.minimum(graph, graph.T)
+
+    for k in range(N):
+        for i in range(N):
+            for j in range(N):
+                graph[i, j] = min(graph[i, j], graph[i, k] + graph[k, j])
+
+    graph[np.where(np.isinf(graph))] = 0
+
+    return graph
+
+
+def generate_graph(N=20):
+    # sparse grid of distances
+    rng = np.random.RandomState(0)
+    dist_matrix = rng.random_sample((N, N))
+
+    # make symmetric: distances are not direction-dependent
+    dist_matrix = dist_matrix + dist_matrix.T
+
+    # make graph sparse
+    i = (rng.randint(N, size=N * N // 2), rng.randint(N, size=N * N // 2))
+    dist_matrix[i] = 0
+
+    # set diagonal to zero
+    dist_matrix.flat[:: N + 1] = 0
+
+    return dist_matrix
+
+
+def test_shortest_path():
+    dist_matrix = generate_graph(20)
+    # We compare path length and not costs (-> set distances to 0 or 1)
+    dist_matrix[dist_matrix != 0] = 1
+
+    for directed in (True, False):
+        if not directed:
+            dist_matrix = np.minimum(dist_matrix, dist_matrix.T)
+
+        graph_py = floyd_warshall_slow(dist_matrix.copy(), directed)
+        for i in range(dist_matrix.shape[0]):
+            # Non-reachable nodes have distance 0 in graph_py
+            dist_dict = defaultdict(int)
+            dist_dict.update(single_source_shortest_path_length(dist_matrix, i))
+
+            for j in range(graph_py[i].shape[0]):
+                assert_array_almost_equal(dist_dict[j], graph_py[i, j])
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_tags.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_tags.py
new file mode 100644
index 0000000000000000000000000000000000000000..f96a4947164c307eecd8004e468000618b685248
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_tags.py
@@ -0,0 +1,47 @@
+import pytest
+
+from sklearn.base import BaseEstimator
+from sklearn.utils._tags import (
+    _DEFAULT_TAGS,
+    _safe_tags,
+)
+
+
+class NoTagsEstimator:
+    pass
+
+
+class MoreTagsEstimator:
+    def _more_tags(self):
+        return {"allow_nan": True}
+
+
+@pytest.mark.parametrize(
+    "estimator, err_msg",
+    [
+        (BaseEstimator(), "The key xxx is not defined in _get_tags"),
+        (NoTagsEstimator(), "The key xxx is not defined in _DEFAULT_TAGS"),
+    ],
+)
+def test_safe_tags_error(estimator, err_msg):
+    # Check that safe_tags raises error in ambiguous case.
+    with pytest.raises(ValueError, match=err_msg):
+        _safe_tags(estimator, key="xxx")
+
+
+@pytest.mark.parametrize(
+    "estimator, key, expected_results",
+    [
+        (NoTagsEstimator(), None, _DEFAULT_TAGS),
+        (NoTagsEstimator(), "allow_nan", _DEFAULT_TAGS["allow_nan"]),
+        (MoreTagsEstimator(), None, {**_DEFAULT_TAGS, **{"allow_nan": True}}),
+        (MoreTagsEstimator(), "allow_nan", True),
+        (BaseEstimator(), None, _DEFAULT_TAGS),
+        (BaseEstimator(), "allow_nan", _DEFAULT_TAGS["allow_nan"]),
+        (BaseEstimator(), "allow_nan", _DEFAULT_TAGS["allow_nan"]),
+    ],
+)
+def test_safe_tags_no_get_tags(estimator, key, expected_results):
+    # check the behaviour of _safe_tags when an estimator does not implement
+    # _get_tags
+    assert _safe_tags(estimator, key=key) == expected_results
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_testing.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..93c62de0ffa3b4f25c10261848a793e02a0f41ac
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_testing.py
@@ -0,0 +1,842 @@
+import warnings
+import unittest
+import os
+import atexit
+
+import numpy as np
+
+from scipy import sparse
+
+import pytest
+
+from sklearn.utils.deprecation import deprecated
+from sklearn.utils.metaestimators import available_if, if_delegate_has_method
+from sklearn.utils._readonly_array_wrapper import _test_sum
+from sklearn.utils._testing import (
+    assert_raises,
+    assert_no_warnings,
+    set_random_state,
+    assert_raise_message,
+    ignore_warnings,
+    check_docstring_parameters,
+    assert_allclose_dense_sparse,
+    assert_raises_regex,
+    TempMemmap,
+    create_memmap_backed_data,
+    _delete_folder,
+    _convert_container,
+    raises,
+    assert_allclose,
+)
+
+from sklearn.tree import DecisionTreeClassifier
+from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
+
+
+def test_set_random_state():
+    lda = LinearDiscriminantAnalysis()
+    tree = DecisionTreeClassifier()
+    # Linear Discriminant Analysis doesn't have random state: smoke test
+    set_random_state(lda, 3)
+    set_random_state(tree, 3)
+    assert tree.random_state == 3
+
+
+def test_assert_allclose_dense_sparse():
+    x = np.arange(9).reshape(3, 3)
+    msg = "Not equal to tolerance "
+    y = sparse.csc_matrix(x)
+    for X in [x, y]:
+        # basic compare
+        with pytest.raises(AssertionError, match=msg):
+            assert_allclose_dense_sparse(X, X * 2)
+        assert_allclose_dense_sparse(X, X)
+
+    with pytest.raises(ValueError, match="Can only compare two sparse"):
+        assert_allclose_dense_sparse(x, y)
+
+    A = sparse.diags(np.ones(5), offsets=0).tocsr()
+    B = sparse.csr_matrix(np.ones((1, 5)))
+    with pytest.raises(AssertionError, match="Arrays are not equal"):
+        assert_allclose_dense_sparse(B, A)
+
+
+def test_assert_raises_msg():
+    with assert_raises_regex(AssertionError, "Hello world"):
+        with assert_raises(ValueError, msg="Hello world"):
+            pass
+
+
+def test_assert_raise_message():
+    def _raise_ValueError(message):
+        raise ValueError(message)
+
+    def _no_raise():
+        pass
+
+    assert_raise_message(ValueError, "test", _raise_ValueError, "test")
+
+    assert_raises(
+        AssertionError,
+        assert_raise_message,
+        ValueError,
+        "something else",
+        _raise_ValueError,
+        "test",
+    )
+
+    assert_raises(
+        ValueError,
+        assert_raise_message,
+        TypeError,
+        "something else",
+        _raise_ValueError,
+        "test",
+    )
+
+    assert_raises(AssertionError, assert_raise_message, ValueError, "test", _no_raise)
+
+    # multiple exceptions in a tuple
+    assert_raises(
+        AssertionError,
+        assert_raise_message,
+        (ValueError, AttributeError),
+        "test",
+        _no_raise,
+    )
+
+
+def test_ignore_warning():
+    # This check that ignore_warning decorator and context manager are working
+    # as expected
+    def _warning_function():
+        warnings.warn("deprecation warning", DeprecationWarning)
+
+    def _multiple_warning_function():
+        warnings.warn("deprecation warning", DeprecationWarning)
+        warnings.warn("deprecation warning")
+
+    # Check the function directly
+    assert_no_warnings(ignore_warnings(_warning_function))
+    assert_no_warnings(ignore_warnings(_warning_function, category=DeprecationWarning))
+    with pytest.warns(DeprecationWarning):
+        ignore_warnings(_warning_function, category=UserWarning)()
+    with pytest.warns(UserWarning):
+        ignore_warnings(_multiple_warning_function, category=FutureWarning)()
+    with pytest.warns(DeprecationWarning):
+        ignore_warnings(_multiple_warning_function, category=UserWarning)()
+    assert_no_warnings(
+        ignore_warnings(_warning_function, category=(DeprecationWarning, UserWarning))
+    )
+
+    # Check the decorator
+    @ignore_warnings
+    def decorator_no_warning():
+        _warning_function()
+        _multiple_warning_function()
+
+    @ignore_warnings(category=(DeprecationWarning, UserWarning))
+    def decorator_no_warning_multiple():
+        _multiple_warning_function()
+
+    @ignore_warnings(category=DeprecationWarning)
+    def decorator_no_deprecation_warning():
+        _warning_function()
+
+    @ignore_warnings(category=UserWarning)
+    def decorator_no_user_warning():
+        _warning_function()
+
+    @ignore_warnings(category=DeprecationWarning)
+    def decorator_no_deprecation_multiple_warning():
+        _multiple_warning_function()
+
+    @ignore_warnings(category=UserWarning)
+    def decorator_no_user_multiple_warning():
+        _multiple_warning_function()
+
+    assert_no_warnings(decorator_no_warning)
+    assert_no_warnings(decorator_no_warning_multiple)
+    assert_no_warnings(decorator_no_deprecation_warning)
+    with pytest.warns(DeprecationWarning):
+        decorator_no_user_warning()
+    with pytest.warns(UserWarning):
+        decorator_no_deprecation_multiple_warning()
+    with pytest.warns(DeprecationWarning):
+        decorator_no_user_multiple_warning()
+
+    # Check the context manager
+    def context_manager_no_warning():
+        with ignore_warnings():
+            _warning_function()
+
+    def context_manager_no_warning_multiple():
+        with ignore_warnings(category=(DeprecationWarning, UserWarning)):
+            _multiple_warning_function()
+
+    def context_manager_no_deprecation_warning():
+        with ignore_warnings(category=DeprecationWarning):
+            _warning_function()
+
+    def context_manager_no_user_warning():
+        with ignore_warnings(category=UserWarning):
+            _warning_function()
+
+    def context_manager_no_deprecation_multiple_warning():
+        with ignore_warnings(category=DeprecationWarning):
+            _multiple_warning_function()
+
+    def context_manager_no_user_multiple_warning():
+        with ignore_warnings(category=UserWarning):
+            _multiple_warning_function()
+
+    assert_no_warnings(context_manager_no_warning)
+    assert_no_warnings(context_manager_no_warning_multiple)
+    assert_no_warnings(context_manager_no_deprecation_warning)
+    with pytest.warns(DeprecationWarning):
+        context_manager_no_user_warning()
+    with pytest.warns(UserWarning):
+        context_manager_no_deprecation_multiple_warning()
+    with pytest.warns(DeprecationWarning):
+        context_manager_no_user_multiple_warning()
+
+    # Check that passing warning class as first positional argument
+    warning_class = UserWarning
+    match = "'obj' should be a callable.+you should use 'category=UserWarning'"
+
+    with pytest.raises(ValueError, match=match):
+        silence_warnings_func = ignore_warnings(warning_class)(_warning_function)
+        silence_warnings_func()
+
+    with pytest.raises(ValueError, match=match):
+
+        @ignore_warnings(warning_class)
+        def test():
+            pass
+
+
+class TestWarns(unittest.TestCase):
+    def test_warn(self):
+        def f():
+            warnings.warn("yo")
+            return 3
+
+        with pytest.raises(AssertionError):
+            assert_no_warnings(f)
+        assert assert_no_warnings(lambda x: x, 1) == 1
+
+
+# Tests for docstrings:
+
+
+def f_ok(a, b):
+    """Function f
+
+    Parameters
+    ----------
+    a : int
+        Parameter a
+    b : float
+        Parameter b
+
+    Returns
+    -------
+    c : list
+        Parameter c
+    """
+    c = a + b
+    return c
+
+
+def f_bad_sections(a, b):
+    """Function f
+
+    Parameters
+    ----------
+    a : int
+        Parameter a
+    b : float
+        Parameter b
+
+    Results
+    -------
+    c : list
+        Parameter c
+    """
+    c = a + b
+    return c
+
+
+def f_bad_order(b, a):
+    """Function f
+
+    Parameters
+    ----------
+    a : int
+        Parameter a
+    b : float
+        Parameter b
+
+    Returns
+    -------
+    c : list
+        Parameter c
+    """
+    c = a + b
+    return c
+
+
+def f_too_many_param_docstring(a, b):
+    """Function f
+
+    Parameters
+    ----------
+    a : int
+        Parameter a
+    b : int
+        Parameter b
+    c : int
+        Parameter c
+
+    Returns
+    -------
+    d : list
+        Parameter c
+    """
+    d = a + b
+    return d
+
+
+def f_missing(a, b):
+    """Function f
+
+    Parameters
+    ----------
+    a : int
+        Parameter a
+
+    Returns
+    -------
+    c : list
+        Parameter c
+    """
+    c = a + b
+    return c
+
+
+def f_check_param_definition(a, b, c, d, e):
+    """Function f
+
+    Parameters
+    ----------
+    a: int
+        Parameter a
+    b:
+        Parameter b
+    c :
+        This is parsed correctly in numpydoc 1.2
+    d:int
+        Parameter d
+    e
+        No typespec is allowed without colon
+    """
+    return a + b + c + d
+
+
+class Klass:
+    def f_missing(self, X, y):
+        pass
+
+    def f_bad_sections(self, X, y):
+        """Function f
+
+        Parameter
+        ---------
+        a : int
+            Parameter a
+        b : float
+            Parameter b
+
+        Results
+        -------
+        c : list
+            Parameter c
+        """
+        pass
+
+
+class MockEst:
+    def __init__(self):
+        """MockEstimator"""
+
+    def fit(self, X, y):
+        return X
+
+    def predict(self, X):
+        return X
+
+    def predict_proba(self, X):
+        return X
+
+    def score(self, X):
+        return 1.0
+
+
+class MockMetaEstimator:
+    def __init__(self, delegate):
+        """MetaEstimator to check if doctest on delegated methods work.
+
+        Parameters
+        ---------
+        delegate : estimator
+            Delegated estimator.
+        """
+        self.delegate = delegate
+
+    @available_if(lambda self: hasattr(self.delegate, "predict"))
+    def predict(self, X):
+        """This is available only if delegate has predict.
+
+        Parameters
+        ----------
+        y : ndarray
+            Parameter y
+        """
+        return self.delegate.predict(X)
+
+    @available_if(lambda self: hasattr(self.delegate, "score"))
+    @deprecated("Testing a deprecated delegated method")
+    def score(self, X):
+        """This is available only if delegate has score.
+
+        Parameters
+        ---------
+        y : ndarray
+            Parameter y
+        """
+
+    @available_if(lambda self: hasattr(self.delegate, "predict_proba"))
+    def predict_proba(self, X):
+        """This is available only if delegate has predict_proba.
+
+        Parameters
+        ---------
+        X : ndarray
+            Parameter X
+        """
+        return X
+
+    @deprecated("Testing deprecated function with wrong params")
+    def fit(self, X, y):
+        """Incorrect docstring but should not be tested"""
+
+
+class MockMetaEstimatorDeprecatedDelegation:
+    def __init__(self, delegate):
+        """MetaEstimator to check if doctest on delegated methods work.
+
+        Parameters
+        ---------
+        delegate : estimator
+            Delegated estimator.
+        """
+        self.delegate = delegate
+
+    @if_delegate_has_method(delegate="delegate")
+    def predict(self, X):
+        """This is available only if delegate has predict.
+
+        Parameters
+        ----------
+        y : ndarray
+            Parameter y
+        """
+        return self.delegate.predict(X)
+
+    @if_delegate_has_method(delegate="delegate")
+    @deprecated("Testing a deprecated delegated method")
+    def score(self, X):
+        """This is available only if delegate has score.
+
+        Parameters
+        ---------
+        y : ndarray
+            Parameter y
+        """
+
+    @if_delegate_has_method(delegate="delegate")
+    def predict_proba(self, X):
+        """This is available only if delegate has predict_proba.
+
+        Parameters
+        ---------
+        X : ndarray
+            Parameter X
+        """
+        return X
+
+    @deprecated("Testing deprecated function with wrong params")
+    def fit(self, X, y):
+        """Incorrect docstring but should not be tested"""
+
+
+@pytest.mark.filterwarnings("ignore:if_delegate_has_method was deprecated")
+@pytest.mark.parametrize(
+    "mock_meta",
+    [
+        MockMetaEstimator(delegate=MockEst()),
+        MockMetaEstimatorDeprecatedDelegation(delegate=MockEst()),
+    ],
+)
+def test_check_docstring_parameters(mock_meta):
+    pytest.importorskip(
+        "numpydoc",
+        reason="numpydoc is required to test the docstrings",
+        minversion="1.2.0",
+    )
+
+    incorrect = check_docstring_parameters(f_ok)
+    assert incorrect == []
+    incorrect = check_docstring_parameters(f_ok, ignore=["b"])
+    assert incorrect == []
+    incorrect = check_docstring_parameters(f_missing, ignore=["b"])
+    assert incorrect == []
+    with pytest.raises(RuntimeError, match="Unknown section Results"):
+        check_docstring_parameters(f_bad_sections)
+    with pytest.raises(RuntimeError, match="Unknown section Parameter"):
+        check_docstring_parameters(Klass.f_bad_sections)
+
+    incorrect = check_docstring_parameters(f_check_param_definition)
+    mock_meta_name = mock_meta.__class__.__name__
+    assert incorrect == [
+        "sklearn.utils.tests.test_testing.f_check_param_definition There "
+        "was no space between the param name and colon ('a: int')",
+        "sklearn.utils.tests.test_testing.f_check_param_definition There "
+        "was no space between the param name and colon ('b:')",
+        "sklearn.utils.tests.test_testing.f_check_param_definition There "
+        "was no space between the param name and colon ('d:int')",
+    ]
+
+    messages = [
+        [
+            "In function: sklearn.utils.tests.test_testing.f_bad_order",
+            "There's a parameter name mismatch in function docstring w.r.t."
+            " function signature, at index 0 diff: 'b' != 'a'",
+            "Full diff:",
+            "- ['b', 'a']",
+            "+ ['a', 'b']",
+        ],
+        [
+            "In function: "
+            + "sklearn.utils.tests.test_testing.f_too_many_param_docstring",
+            "Parameters in function docstring have more items w.r.t. function"
+            " signature, first extra item: c",
+            "Full diff:",
+            "- ['a', 'b']",
+            "+ ['a', 'b', 'c']",
+            "?          +++++",
+        ],
+        [
+            "In function: sklearn.utils.tests.test_testing.f_missing",
+            "Parameters in function docstring have less items w.r.t. function"
+            " signature, first missing item: b",
+            "Full diff:",
+            "- ['a', 'b']",
+            "+ ['a']",
+        ],
+        [
+            "In function: sklearn.utils.tests.test_testing.Klass.f_missing",
+            "Parameters in function docstring have less items w.r.t. function"
+            " signature, first missing item: X",
+            "Full diff:",
+            "- ['X', 'y']",
+            "+ []",
+        ],
+        [
+            "In function: "
+            + f"sklearn.utils.tests.test_testing.{mock_meta_name}.predict",
+            "There's a parameter name mismatch in function docstring w.r.t."
+            " function signature, at index 0 diff: 'X' != 'y'",
+            "Full diff:",
+            "- ['X']",
+            "?   ^",
+            "+ ['y']",
+            "?   ^",
+        ],
+        [
+            "In function: "
+            + f"sklearn.utils.tests.test_testing.{mock_meta_name}."
+            + "predict_proba",
+            "potentially wrong underline length... ",
+            "Parameters ",
+            "--------- in ",
+        ],
+        [
+            "In function: "
+            + f"sklearn.utils.tests.test_testing.{mock_meta_name}.score",
+            "potentially wrong underline length... ",
+            "Parameters ",
+            "--------- in ",
+        ],
+        [
+            "In function: " + f"sklearn.utils.tests.test_testing.{mock_meta_name}.fit",
+            "Parameters in function docstring have less items w.r.t. function"
+            " signature, first missing item: X",
+            "Full diff:",
+            "- ['X', 'y']",
+            "+ []",
+        ],
+    ]
+
+    for msg, f in zip(
+        messages,
+        [
+            f_bad_order,
+            f_too_many_param_docstring,
+            f_missing,
+            Klass.f_missing,
+            mock_meta.predict,
+            mock_meta.predict_proba,
+            mock_meta.score,
+            mock_meta.fit,
+        ],
+    ):
+        incorrect = check_docstring_parameters(f)
+        assert msg == incorrect, '\n"%s"\n not in \n"%s"' % (msg, incorrect)
+
+
+class RegistrationCounter:
+    def __init__(self):
+        self.nb_calls = 0
+
+    def __call__(self, to_register_func):
+        self.nb_calls += 1
+        assert to_register_func.func is _delete_folder
+
+
+def check_memmap(input_array, mmap_data, mmap_mode="r"):
+    assert isinstance(mmap_data, np.memmap)
+    writeable = mmap_mode != "r"
+    assert mmap_data.flags.writeable is writeable
+    np.testing.assert_array_equal(input_array, mmap_data)
+
+
+def test_tempmemmap(monkeypatch):
+    registration_counter = RegistrationCounter()
+    monkeypatch.setattr(atexit, "register", registration_counter)
+
+    input_array = np.ones(3)
+    with TempMemmap(input_array) as data:
+        check_memmap(input_array, data)
+        temp_folder = os.path.dirname(data.filename)
+    if os.name != "nt":
+        assert not os.path.exists(temp_folder)
+    assert registration_counter.nb_calls == 1
+
+    mmap_mode = "r+"
+    with TempMemmap(input_array, mmap_mode=mmap_mode) as data:
+        check_memmap(input_array, data, mmap_mode=mmap_mode)
+        temp_folder = os.path.dirname(data.filename)
+    if os.name != "nt":
+        assert not os.path.exists(temp_folder)
+    assert registration_counter.nb_calls == 2
+
+
+@pytest.mark.parametrize("aligned", [False, True])
+def test_create_memmap_backed_data(monkeypatch, aligned):
+    registration_counter = RegistrationCounter()
+    monkeypatch.setattr(atexit, "register", registration_counter)
+
+    input_array = np.ones(3)
+    data = create_memmap_backed_data(input_array, aligned=aligned)
+    check_memmap(input_array, data)
+    assert registration_counter.nb_calls == 1
+
+    data, folder = create_memmap_backed_data(
+        input_array, return_folder=True, aligned=aligned
+    )
+    check_memmap(input_array, data)
+    assert folder == os.path.dirname(data.filename)
+    assert registration_counter.nb_calls == 2
+
+    mmap_mode = "r+"
+    data = create_memmap_backed_data(input_array, mmap_mode=mmap_mode, aligned=aligned)
+    check_memmap(input_array, data, mmap_mode)
+    assert registration_counter.nb_calls == 3
+
+    input_list = [input_array, input_array + 1, input_array + 2]
+    mmap_data_list = create_memmap_backed_data(input_list, aligned=aligned)
+    for input_array, data in zip(input_list, mmap_data_list):
+        check_memmap(input_array, data)
+    assert registration_counter.nb_calls == 4
+
+    with pytest.raises(
+        ValueError,
+        match=(
+            "When creating aligned memmap-backed arrays, input must be a single array"
+            " or a sequence of arrays"
+        ),
+    ):
+        create_memmap_backed_data([input_array, "not-an-array"], aligned=True)
+
+
+@pytest.mark.parametrize("dtype", [np.float32, np.float64, np.int32, np.int64])
+def test_memmap_on_contiguous_data(dtype):
+    """Test memory mapped array on contiguous memoryview."""
+    x = np.arange(10).astype(dtype)
+    assert x.flags["C_CONTIGUOUS"]
+    assert x.flags["ALIGNED"]
+
+    # _test_sum consumes contiguous arrays
+    # def _test_sum(NUM_TYPES[::1] x):
+    sum_origin = _test_sum(x)
+
+    # now on memory mapped data
+    # aligned=True so avoid https://github.com/joblib/joblib/issues/563
+    # without alignment, this can produce segmentation faults, see
+    # https://github.com/scikit-learn/scikit-learn/pull/21654
+    x_mmap = create_memmap_backed_data(x, mmap_mode="r+", aligned=True)
+    sum_mmap = _test_sum(x_mmap)
+    assert sum_mmap == pytest.approx(sum_origin, rel=1e-11)
+
+
+@pytest.mark.parametrize(
+    "constructor_name, container_type",
+    [
+        ("list", list),
+        ("tuple", tuple),
+        ("array", np.ndarray),
+        ("sparse", sparse.csr_matrix),
+        ("sparse_csr", sparse.csr_matrix),
+        ("sparse_csc", sparse.csc_matrix),
+        ("dataframe", lambda: pytest.importorskip("pandas").DataFrame),
+        ("series", lambda: pytest.importorskip("pandas").Series),
+        ("index", lambda: pytest.importorskip("pandas").Index),
+        ("slice", slice),
+    ],
+)
+@pytest.mark.parametrize(
+    "dtype, superdtype",
+    [
+        (np.int32, np.integer),
+        (np.int64, np.integer),
+        (np.float32, np.floating),
+        (np.float64, np.floating),
+    ],
+)
+def test_convert_container(
+    constructor_name,
+    container_type,
+    dtype,
+    superdtype,
+):
+    """Check that we convert the container to the right type of array with the
+    right data type."""
+    if constructor_name in ("dataframe", "series", "index"):
+        # delay the import of pandas within the function to only skip this test
+        # instead of the whole file
+        container_type = container_type()
+    container = [0, 1]
+    container_converted = _convert_container(
+        container,
+        constructor_name,
+        dtype=dtype,
+    )
+    assert isinstance(container_converted, container_type)
+
+    if constructor_name in ("list", "tuple", "index"):
+        # list and tuple will use Python class dtype: int, float
+        # pandas index will always use high precision: np.int64 and np.float64
+        assert np.issubdtype(type(container_converted[0]), superdtype)
+    elif hasattr(container_converted, "dtype"):
+        assert container_converted.dtype == dtype
+    elif hasattr(container_converted, "dtypes"):
+        assert container_converted.dtypes[0] == dtype
+
+
+def test_raises():
+    # Tests for the raises context manager
+
+    # Proper type, no match
+    with raises(TypeError):
+        raise TypeError()
+
+    # Proper type, proper match
+    with raises(TypeError, match="how are you") as cm:
+        raise TypeError("hello how are you")
+    assert cm.raised_and_matched
+
+    # Proper type, proper match with multiple patterns
+    with raises(TypeError, match=["not this one", "how are you"]) as cm:
+        raise TypeError("hello how are you")
+    assert cm.raised_and_matched
+
+    # bad type, no match
+    with pytest.raises(ValueError, match="this will be raised"):
+        with raises(TypeError) as cm:
+            raise ValueError("this will be raised")
+    assert not cm.raised_and_matched
+
+    # Bad type, no match, with a err_msg
+    with pytest.raises(AssertionError, match="the failure message"):
+        with raises(TypeError, err_msg="the failure message") as cm:
+            raise ValueError()
+    assert not cm.raised_and_matched
+
+    # bad type, with match (is ignored anyway)
+    with pytest.raises(ValueError, match="this will be raised"):
+        with raises(TypeError, match="this is ignored") as cm:
+            raise ValueError("this will be raised")
+    assert not cm.raised_and_matched
+
+    # proper type but bad match
+    with pytest.raises(
+        AssertionError, match="should contain one of the following patterns"
+    ):
+        with raises(TypeError, match="hello") as cm:
+            raise TypeError("Bad message")
+    assert not cm.raised_and_matched
+
+    # proper type but bad match, with err_msg
+    with pytest.raises(AssertionError, match="the failure message"):
+        with raises(TypeError, match="hello", err_msg="the failure message") as cm:
+            raise TypeError("Bad message")
+    assert not cm.raised_and_matched
+
+    # no raise with default may_pass=False
+    with pytest.raises(AssertionError, match="Did not raise"):
+        with raises(TypeError) as cm:
+            pass
+    assert not cm.raised_and_matched
+
+    # no raise with may_pass=True
+    with raises(TypeError, match="hello", may_pass=True) as cm:
+        pass  # still OK
+    assert not cm.raised_and_matched
+
+    # Multiple exception types:
+    with raises((TypeError, ValueError)):
+        raise TypeError()
+    with raises((TypeError, ValueError)):
+        raise ValueError()
+    with pytest.raises(AssertionError):
+        with raises((TypeError, ValueError)):
+            pass
+
+
+def test_float32_aware_assert_allclose():
+    # The relative tolerance for float32 inputs is 1e-4
+    assert_allclose(np.array([1.0 + 2e-5], dtype=np.float32), 1.0)
+    with pytest.raises(AssertionError):
+        assert_allclose(np.array([1.0 + 2e-4], dtype=np.float32), 1.0)
+
+    # The relative tolerance for other inputs is left to 1e-7 as in
+    # the original numpy version.
+    assert_allclose(np.array([1.0 + 2e-8], dtype=np.float64), 1.0)
+    with pytest.raises(AssertionError):
+        assert_allclose(np.array([1.0 + 2e-7], dtype=np.float64), 1.0)
+
+    # atol is left to 0.0 by default, even for float32
+    with pytest.raises(AssertionError):
+        assert_allclose(np.array([1e-5], dtype=np.float32), 0.0)
+    assert_allclose(np.array([1e-5], dtype=np.float32), 0.0, atol=2e-5)
diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_validation.py b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c9379facf366ae18327bba607dae3a70124b2d0
--- /dev/null
+++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/tests/test_validation.py
@@ -0,0 +1,1778 @@
+"""Tests for input validation functions"""
+
+import numbers
+import warnings
+import re
+
+from tempfile import NamedTemporaryFile
+from itertools import product
+from operator import itemgetter
+
+import pytest
+from pytest import importorskip
+import numpy as np
+import scipy.sparse as sp
+
+from sklearn._config import config_context
+from sklearn.utils._testing import assert_no_warnings
+from sklearn.utils._testing import ignore_warnings
+from sklearn.utils._testing import SkipTest
+from sklearn.utils._testing import assert_array_equal
+from sklearn.utils._testing import assert_allclose_dense_sparse
+from sklearn.utils._testing import assert_allclose
+from sklearn.utils._testing import _convert_container
+from sklearn.utils import as_float_array, check_array, check_symmetric
+from sklearn.utils import check_X_y
+from sklearn.utils import deprecated
+from sklearn.utils._mocking import MockDataFrame
+from sklearn.utils.fixes import parse_version
+from sklearn.utils.estimator_checks import _NotAnArray
+from sklearn.random_projection import _sparse_random_matrix
+from sklearn.linear_model import ARDRegression
+from sklearn.neighbors import KNeighborsClassifier
+from sklearn.ensemble import RandomForestRegressor
+from sklearn.svm import SVR
+from sklearn.datasets import make_blobs
+from sklearn.utils import _safe_indexing
+from sklearn.utils.validation import (
+    has_fit_parameter,
+    check_is_fitted,
+    check_consistent_length,
+    assert_all_finite,
+    check_memory,
+    check_non_negative,
+    _num_samples,
+    check_scalar,
+    _check_psd_eigenvalues,
+    _check_y,
+    _deprecate_positional_args,
+    _check_sample_weight,
+    _allclose_dense_sparse,
+    _num_features,
+    FLOAT_DTYPES,
+    _get_feature_names,
+    _check_feature_names_in,
+    _check_fit_params,
+)
+from sklearn.base import BaseEstimator
+import sklearn
+
+from sklearn.exceptions import NotFittedError, PositiveSpectrumWarning
+
+from sklearn.utils._testing import TempMemmap
+
+
+def test_as_float_array():
+    # Test function for as_float_array
+    X = np.ones((3, 10), dtype=np.int32)
+    X = X + np.arange(10, dtype=np.int32)
+    X2 = as_float_array(X, copy=False)
+    assert X2.dtype == np.float32
+    # Another test
+    X = X.astype(np.int64)
+    X2 = as_float_array(X, copy=True)
+    # Checking that the array wasn't overwritten
+    assert as_float_array(X, copy=False) is not X
+    assert X2.dtype == np.float64
+    # Test int dtypes <= 32bit
+    tested_dtypes = [bool, np.int8, np.int16, np.int32, np.uint8, np.uint16, np.uint32]
+    for dtype in tested_dtypes:
+        X = X.astype(dtype)
+        X2 = as_float_array(X)
+        assert X2.dtype == np.float32
+
+    # Test object dtype
+    X = X.astype(object)
+    X2 = as_float_array(X, copy=True)
+    assert X2.dtype == np.float64
+
+    # Here, X is of the right type, it shouldn't be modified
+    X = np.ones((3, 2), dtype=np.float32)
+    assert as_float_array(X, copy=False) is X
+    # Test that if X is fortran ordered it stays
+    X = np.asfortranarray(X)
+    assert np.isfortran(as_float_array(X, copy=True))
+
+    # Test the copy parameter with some matrices
+    matrices = [
+        sp.csc_matrix(np.arange(5)).toarray(),
+        _sparse_random_matrix(10, 10, density=0.10).toarray(),
+    ]
+    for M in matrices:
+        N = as_float_array(M, copy=True)
+        N[0, 0] = np.nan
+        assert not np.isnan(M).any()
+
+
+@pytest.mark.parametrize("X", [(np.random.random((10, 2))), (sp.rand(10, 2).tocsr())])
+def test_as_float_array_nan(X):
+    X[5, 0] = np.nan
+    X[6, 1] = np.nan
+    X_converted = as_float_array(X, force_all_finite="allow-nan")
+    assert_allclose_dense_sparse(X_converted, X)
+
+
+def test_np_matrix():
+    # Confirm that input validation code does not return np.matrix
+    X = np.arange(12).reshape(3, 4)
+
+    assert not isinstance(as_float_array(X), np.matrix)
+    assert not isinstance(as_float_array(sp.csc_matrix(X)), np.matrix)
+
+
+def test_memmap():
+    # Confirm that input validation code doesn't copy memory mapped arrays
+
+    asflt = lambda x: as_float_array(x, copy=False)
+
+    with NamedTemporaryFile(prefix="sklearn-test") as tmp:
+        M = np.memmap(tmp, shape=(10, 10), dtype=np.float32)
+        M[:] = 0
+
+        for f in (check_array, np.asarray, asflt):
+            X = f(M)
+            X[:] = 1
+            assert_array_equal(X.ravel(), M.ravel())
+            X[:] = 0
+
+
+def test_ordering():
+    # Check that ordering is enforced correctly by validation utilities.
+    # We need to check each validation utility, because a 'copy' without
+    # 'order=K' will kill the ordering.
+    X = np.ones((10, 5))
+    for A in X, X.T:
+        for copy in (True, False):
+            B = check_array(A, order="C", copy=copy)
+            assert B.flags["C_CONTIGUOUS"]
+            B = check_array(A, order="F", copy=copy)
+            assert B.flags["F_CONTIGUOUS"]
+            if copy:
+                assert A is not B
+
+    X = sp.csr_matrix(X)
+    X.data = X.data[::-1]
+    assert not X.data.flags["C_CONTIGUOUS"]
+
+
+@pytest.mark.parametrize(
+    "value, force_all_finite", [(np.inf, False), (np.nan, "allow-nan"), (np.nan, False)]
+)
+@pytest.mark.parametrize("retype", [np.asarray, sp.csr_matrix])
+def test_check_array_force_all_finite_valid(value, force_all_finite, retype):
+    X = retype(np.arange(4).reshape(2, 2).astype(float))
+    X[0, 0] = value
+    X_checked = check_array(X, force_all_finite=force_all_finite, accept_sparse=True)
+    assert_allclose_dense_sparse(X, X_checked)
+
+
+@pytest.mark.parametrize(
+    "value, input_name, force_all_finite, match_msg",
+    [
+        (np.inf, "", True, "Input contains infinity"),
+        (np.inf, "X", True, "Input X contains infinity"),
+        (np.inf, "sample_weight", True, "Input sample_weight contains infinity"),
+        (np.inf, "X", "allow-nan", "Input X contains infinity"),
+        (np.nan, "", True, "Input contains NaN"),
+        (np.nan, "X", True, "Input X contains NaN"),
+        (np.nan, "y", True, "Input y contains NaN"),
+        (
+            np.nan,
+            "",
+            "allow-inf",
+            'force_all_finite should be a bool or "allow-nan"',
+        ),
+        (np.nan, "", 1, "Input contains NaN"),
+    ],
+)
+@pytest.mark.parametrize("retype", [np.asarray, sp.csr_matrix])
+def test_check_array_force_all_finiteinvalid(
+    value, input_name, force_all_finite, match_msg, retype
+):
+    X = retype(np.arange(4).reshape(2, 2).astype(np.float64))
+    X[0, 0] = value
+    with pytest.raises(ValueError, match=match_msg):
+        check_array(
+            X,
+            input_name=input_name,
+            force_all_finite=force_all_finite,
+            accept_sparse=True,
+        )
+
+
+@pytest.mark.parametrize("input_name", ["X", "y", "sample_weight"])
+@pytest.mark.parametrize("retype", [np.asarray, sp.csr_matrix])
+def test_check_array_links_to_imputer_doc_only_for_X(input_name, retype):
+    data = retype(np.arange(4).reshape(2, 2).astype(np.float64))
+    data[0, 0] = np.nan
+    estimator = SVR()
+    extended_msg = (
+        f"\n{estimator.__class__.__name__} does not accept missing values"
+        " encoded as NaN natively. For supervised learning, you might want"
+        " to consider sklearn.ensemble.HistGradientBoostingClassifier and Regressor"
+        " which accept missing values encoded as NaNs natively."
+        " Alternatively, it is possible to preprocess the"
+        " data, for instance by using an imputer transformer in a pipeline"
+        " or drop samples with missing values. See"
+        " https://scikit-learn.org/stable/modules/impute.html"
+        " You can find a list of all estimators that handle NaN values"
+        " at the following page:"
+        " https://scikit-learn.org/stable/modules/impute.html"
+        "#estimators-that-handle-nan-values"
+    )
+
+    with pytest.raises(ValueError, match=f"Input {input_name} contains NaN") as ctx:
+        check_array(
+            data,
+            estimator=estimator,
+            input_name=input_name,
+            accept_sparse=True,
+        )
+
+    if input_name == "X":
+        assert extended_msg in ctx.value.args[0]
+    else:
+        assert extended_msg not in ctx.value.args[0]
+
+    if input_name == "X":
+        # Veriy that _validate_data is automatically called with the right argument
+        # to generate the same exception:
+        with pytest.raises(ValueError, match=f"Input {input_name} contains NaN") as ctx:
+            SVR().fit(data, np.ones(data.shape[0]))
+        assert extended_msg in ctx.value.args[0]
+
+
+def test_check_array_force_all_finite_object():
+    X = np.array([["a", "b", np.nan]], dtype=object).T
+
+    X_checked = check_array(X, dtype=None, force_all_finite="allow-nan")
+    assert X is X_checked
+
+    X_checked = check_array(X, dtype=None, force_all_finite=False)
+    assert X is X_checked
+
+    with pytest.raises(ValueError, match="Input contains NaN"):
+        check_array(X, dtype=None, force_all_finite=True)
+
+
+@pytest.mark.parametrize(
+    "X, err_msg",
+    [
+        (
+            np.array([[1, np.nan]]),
+            "Input contains NaN.",
+        ),
+        (
+            np.array([[1, np.nan]]),
+            "Input contains NaN.",
+        ),
+        (
+            np.array([[1, np.inf]]),
+            "Input contains infinity or a value too large for.*int",
+        ),
+        (np.array([[1, np.nan]], dtype=object), "cannot convert float NaN to integer"),
+    ],
+)
+@pytest.mark.parametrize("force_all_finite", [True, False])
+def test_check_array_force_all_finite_object_unsafe_casting(
+    X, err_msg, force_all_finite
+):
+    # casting a float array containing NaN or inf to int dtype should
+    # raise an error irrespective of the force_all_finite parameter.
+    with pytest.raises(ValueError, match=err_msg):
+        check_array(X, dtype=int, force_all_finite=force_all_finite)
+
+
+@ignore_warnings
+def test_check_array():
+    # accept_sparse == False
+    # raise error on sparse inputs
+    X = [[1, 2], [3, 4]]
+    X_csr = sp.csr_matrix(X)
+    with pytest.raises(TypeError):
+        check_array(X_csr)
+
+    # ensure_2d=False
+    X_array = check_array([0, 1, 2], ensure_2d=False)
+    assert X_array.ndim == 1
+    # ensure_2d=True with 1d array
+    with pytest.raises(ValueError, match="Expected 2D array, got 1D array instead"):
+        check_array([0, 1, 2], ensure_2d=True)
+
+    # ensure_2d=True with scalar array
+    with pytest.raises(ValueError, match="Expected 2D array, got scalar array instead"):
+        check_array(10, ensure_2d=True)
+
+    # don't allow ndim > 3
+    X_ndim = np.arange(8).reshape(2, 2, 2)
+    with pytest.raises(ValueError):
+        check_array(X_ndim)
+    check_array(X_ndim, allow_nd=True)  # doesn't raise
+
+    # dtype and order enforcement.
+    X_C = np.arange(4).reshape(2, 2).copy("C")
+    X_F = X_C.copy("F")
+    X_int = X_C.astype(int)
+    X_float = X_C.astype(float)
+    Xs = [X_C, X_F, X_int, X_float]
+    dtypes = [np.int32, int, float, np.float32, None, bool, object]
+    orders = ["C", "F", None]
+    copys = [True, False]
+
+    for X, dtype, order, copy in product(Xs, dtypes, orders, copys):
+        X_checked = check_array(X, dtype=dtype, order=order, copy=copy)
+        if dtype is not None:
+            assert X_checked.dtype == dtype
+        else:
+            assert X_checked.dtype == X.dtype
+        if order == "C":
+            assert X_checked.flags["C_CONTIGUOUS"]
+            assert not X_checked.flags["F_CONTIGUOUS"]
+        elif order == "F":
+            assert X_checked.flags["F_CONTIGUOUS"]
+            assert not X_checked.flags["C_CONTIGUOUS"]
+        if copy:
+            assert X is not X_checked
+        else:
+            # doesn't copy if it was already good
+            if (
+                X.dtype == X_checked.dtype
+                and X_checked.flags["C_CONTIGUOUS"] == X.flags["C_CONTIGUOUS"]
+                and X_checked.flags["F_CONTIGUOUS"] == X.flags["F_CONTIGUOUS"]
+            ):
+                assert X is X_checked
+
+    # allowed sparse != None
+    X_csc = sp.csc_matrix(X_C)
+    X_coo = X_csc.tocoo()
+    X_dok = X_csc.todok()
+    X_int = X_csc.astype(int)
+    X_float = X_csc.astype(float)
+
+    Xs = [X_csc, X_coo, X_dok, X_int, X_float]
+    accept_sparses = [["csr", "coo"], ["coo", "dok"]]
+    # scipy sparse matrices do not support the object dtype so
+    # this dtype is skipped in this loop
+    non_object_dtypes = [dt for dt in dtypes if dt is not object]
+    for X, dtype, accept_sparse, copy in product(
+        Xs, non_object_dtypes, accept_sparses, copys
+    ):
+        X_checked = check_array(X, dtype=dtype, accept_sparse=accept_sparse, copy=copy)
+        if dtype is not None:
+            assert X_checked.dtype == dtype
+        else:
+            assert X_checked.dtype == X.dtype
+        if X.format in accept_sparse:
+            # no change if allowed
+            assert X.format == X_checked.format
+        else:
+            # got converted
+            assert X_checked.format == accept_sparse[0]
+        if copy:
+            assert X is not X_checked
+        else:
+            # doesn't copy if it was already good
+            if X.dtype == X_checked.dtype and X.format == X_checked.format:
+                assert X is X_checked
+
+    # other input formats
+    # convert lists to arrays
+    X_dense = check_array([[1, 2], [3, 4]])
+    assert isinstance(X_dense, np.ndarray)
+    # raise on too deep lists
+    with pytest.raises(ValueError):
+        check_array(X_ndim.tolist())
+    check_array(X_ndim.tolist(), allow_nd=True)  # doesn't raise
+
+    # convert weird stuff to arrays
+    X_no_array = _NotAnArray(X_dense)
+    result = check_array(X_no_array)
+    assert isinstance(result, np.ndarray)
+
+
+@pytest.mark.parametrize(
+    "X",
+    [
+        [["1", "2"], ["3", "4"]],
+        np.array([["1", "2"], ["3", "4"]], dtype="U"),
+        np.array([["1", "2"], ["3", "4"]], dtype="S"),
+        [[b"1", b"2"], [b"3", b"4"]],
+        np.array([[b"1", b"2"], [b"3", b"4"]], dtype="V1"),
+    ],
+)
+def test_check_array_numeric_error(X):
+    """Test that check_array errors when it receives an array of bytes/string
+    while a numeric dtype is required."""
+    expected_msg = r"dtype='numeric' is not compatible with arrays of bytes/strings"
+    with pytest.raises(ValueError, match=expected_msg):
+        check_array(X, dtype="numeric")
+
+
+@pytest.mark.parametrize(
+    "pd_dtype", ["Int8", "Int16", "UInt8", "UInt16", "Float32", "Float64"]
+)
+@pytest.mark.parametrize(
+    "dtype, expected_dtype",
+    [
+        ([np.float32, np.float64], np.float32),
+        (np.float64, np.float64),
+        ("numeric", np.float64),
+    ],
+)
+def test_check_array_pandas_na_support(pd_dtype, dtype, expected_dtype):
+    # Test pandas numerical extension arrays with pd.NA
+    pd = pytest.importorskip("pandas")
+
+    if pd_dtype in {"Float32", "Float64"}:
+        # Extension dtypes with Floats was added in 1.2
+        pd = pytest.importorskip("pandas", minversion="1.2")
+
+    X_np = np.array(
+        [[1, 2, 3, np.nan, np.nan], [np.nan, np.nan, 8, 4, 6], [1, 2, 3, 4, 5]]
+    ).T
+
+    # Creates dataframe with numerical extension arrays with pd.NA
+    X = pd.DataFrame(X_np, dtype=pd_dtype, columns=["a", "b", "c"])
+    # column c has no nans
+    X["c"] = X["c"].astype("float")
+    X_checked = check_array(X, force_all_finite="allow-nan", dtype=dtype)
+    assert_allclose(X_checked, X_np)
+    assert X_checked.dtype == expected_dtype
+
+    X_checked = check_array(X, force_all_finite=False, dtype=dtype)
+    assert_allclose(X_checked, X_np)
+    assert X_checked.dtype == expected_dtype
+
+    msg = "Input contains NaN"
+    with pytest.raises(ValueError, match=msg):
+        check_array(X, force_all_finite=True)
+
+
+def test_check_array_panadas_na_support_series():
+    """Check check_array is correct with pd.NA in a series."""
+    pd = pytest.importorskip("pandas")
+
+    X_int64 = pd.Series([1, 2, pd.NA], dtype="Int64")
+
+    msg = "Input contains NaN"
+    with pytest.raises(ValueError, match=msg):
+        check_array(X_int64, force_all_finite=True, ensure_2d=False)
+
+    X_out = check_array(X_int64, force_all_finite=False, ensure_2d=False)
+    assert_allclose(X_out, [1, 2, np.nan])
+    assert X_out.dtype == np.float64
+
+    X_out = check_array(
+        X_int64, force_all_finite=False, ensure_2d=False, dtype=np.float32
+    )
+    assert_allclose(X_out, [1, 2, np.nan])
+    assert X_out.dtype == np.float32
+
+
+def test_check_array_pandas_dtype_casting():
+    # test that data-frames with homogeneous dtype are not upcast
+    pd = pytest.importorskip("pandas")
+    X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32)
+    X_df = pd.DataFrame(X)
+    assert check_array(X_df).dtype == np.float32
+    assert check_array(X_df, dtype=FLOAT_DTYPES).dtype == np.float32
+
+    X_df = X_df.astype({0: np.float16})
+    assert_array_equal(X_df.dtypes, (np.float16, np.float32, np.float32))
+    assert check_array(X_df).dtype == np.float32
+    assert check_array(X_df, dtype=FLOAT_DTYPES).dtype == np.float32
+
+    X_df = X_df.astype({0: np.int16})
+    # float16, int16, float32 casts to float32
+    assert check_array(X_df).dtype == np.float32
+    assert check_array(X_df, dtype=FLOAT_DTYPES).dtype == np.float32
+
+    X_df = X_df.astype({2: np.float16})
+    # float16, int16, float16 casts to float32
+    assert check_array(X_df).dtype == np.float32
+    assert check_array(X_df, dtype=FLOAT_DTYPES).dtype == np.float32
+
+    X_df = X_df.astype(np.int16)
+    assert check_array(X_df).dtype == np.int16
+    # we're not using upcasting rules for determining
+    # the target type yet, so we cast to the default of float64
+    assert check_array(X_df, dtype=FLOAT_DTYPES).dtype == np.float64
+
+    # check that we handle pandas dtypes in a semi-reasonable way
+    # this is actually tricky because we can't really know that this
+    # should be integer ahead of converting it.
+    cat_df = pd.DataFrame({"cat_col": pd.Categorical([1, 2, 3])})
+    assert check_array(cat_df).dtype == np.int64
+    assert check_array(cat_df, dtype=FLOAT_DTYPES).dtype == np.float64
+
+
+def test_check_array_on_mock_dataframe():
+    arr = np.array([[0.2, 0.7], [0.6, 0.5], [0.4, 0.1], [0.7, 0.2]])
+    mock_df = MockDataFrame(arr)
+    checked_arr = check_array(mock_df)
+    assert checked_arr.dtype == arr.dtype
+    checked_arr = check_array(mock_df, dtype=np.float32)
+    assert checked_arr.dtype == np.dtype(np.float32)
+
+
+def test_check_array_dtype_stability():
+    # test that lists with ints don't get converted to floats
+    X = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+    assert check_array(X).dtype.kind == "i"
+    assert check_array(X, ensure_2d=False).dtype.kind == "i"
+
+
+def test_check_array_dtype_warning():
+    X_int_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+    X_float32 = np.asarray(X_int_list, dtype=np.float32)
+    X_int64 = np.asarray(X_int_list, dtype=np.int64)
+    X_csr_float32 = sp.csr_matrix(X_float32)
+    X_csc_float32 = sp.csc_matrix(X_float32)
+    X_csc_int32 = sp.csc_matrix(X_int64, dtype=np.int32)
+    integer_data = [X_int64, X_csc_int32]
+    float32_data = [X_float32, X_csr_float32, X_csc_float32]
+    for X in integer_data:
+        X_checked = assert_no_warnings(
+            check_array, X, dtype=np.float64, accept_sparse=True
+        )
+        assert X_checked.dtype == np.float64
+
+    for X in float32_data:
+        X_checked = assert_no_warnings(
+            check_array, X, dtype=[np.float64, np.float32], accept_sparse=True
+        )
+        assert X_checked.dtype == np.float32
+        assert X_checked is X
+
+        X_checked = assert_no_warnings(
+            check_array,
+            X,
+            dtype=[np.float64, np.float32],
+            accept_sparse=["csr", "dok"],
+            copy=True,
+        )
+        assert X_checked.dtype == np.float32
+        assert X_checked is not X
+
+    X_checked = assert_no_warnings(
+        check_array,
+        X_csc_float32,
+        dtype=[np.float64, np.float32],
+        accept_sparse=["csr", "dok"],
+        copy=False,
+    )
+    assert X_checked.dtype == np.float32
+    assert X_checked is not X_csc_float32
+    assert X_checked.format == "csr"
+
+
+def test_check_array_accept_sparse_type_exception():
+    X = [[1, 2], [3, 4]]
+    X_csr = sp.csr_matrix(X)
+    invalid_type = SVR()
+
+    msg = (
+        "A sparse matrix was passed, but dense data is required. "
+        r"Use X.toarray\(\) to convert to a dense numpy array."
+    )
+    with pytest.raises(TypeError, match=msg):
+        check_array(X_csr, accept_sparse=False)
+
+    msg = (
+        "Parameter 'accept_sparse' should be a string, "
+        "boolean or list of strings. You provided 'accept_sparse=.*'."
+    )
+    with pytest.raises(ValueError, match=msg):
+        check_array(X_csr, accept_sparse=invalid_type)
+
+    msg = (
+        "When providing 'accept_sparse' as a tuple or list, "
+        "it must contain at least one string value."
+    )
+    with pytest.raises(ValueError, match=msg):
+        check_array(X_csr, accept_sparse=[])
+    with pytest.raises(ValueError, match=msg):
+        check_array(X_csr, accept_sparse=())
+    with pytest.raises(TypeError, match="SVR"):
+        check_array(X_csr, accept_sparse=[invalid_type])
+
+
+def test_check_array_accept_sparse_no_exception():
+    X = [[1, 2], [3, 4]]
+    X_csr = sp.csr_matrix(X)
+
+    check_array(X_csr, accept_sparse=True)
+    check_array(X_csr, accept_sparse="csr")
+    check_array(X_csr, accept_sparse=["csr"])
+    check_array(X_csr, accept_sparse=("csr",))
+
+
+@pytest.fixture(params=["csr", "csc", "coo", "bsr"])
+def X_64bit(request):
+    X = sp.rand(20, 10, format=request.param)
+    for attr in ["indices", "indptr", "row", "col"]:
+        if hasattr(X, attr):
+            setattr(X, attr, getattr(X, attr).astype("int64"))
+    yield X
+
+
+def test_check_array_accept_large_sparse_no_exception(X_64bit):
+    # When large sparse are allowed
+    check_array(X_64bit, accept_large_sparse=True, accept_sparse=True)
+
+
+def test_check_array_accept_large_sparse_raise_exception(X_64bit):
+    # When large sparse are not allowed
+    msg = (
+        "Only sparse matrices with 32-bit integer indices "
+        "are accepted. Got int64 indices."
+    )
+    with pytest.raises(ValueError, match=msg):
+        check_array(X_64bit, accept_sparse=True, accept_large_sparse=False)
+
+
+def test_check_array_min_samples_and_features_messages():
+    # empty list is considered 2D by default:
+    msg = r"0 feature\(s\) \(shape=\(1, 0\)\) while a minimum of 1 is" " required."
+    with pytest.raises(ValueError, match=msg):
+        check_array([[]])
+
+    # If considered a 1D collection when ensure_2d=False, then the minimum
+    # number of samples will break:
+    msg = r"0 sample\(s\) \(shape=\(0,\)\) while a minimum of 1 is required."
+    with pytest.raises(ValueError, match=msg):
+        check_array([], ensure_2d=False)
+
+    # Invalid edge case when checking the default minimum sample of a scalar
+    msg = r"Singleton array array\(42\) cannot be considered a valid" " collection."
+    with pytest.raises(TypeError, match=msg):
+        check_array(42, ensure_2d=False)
+
+    # Simulate a model that would need at least 2 samples to be well defined
+    X = np.ones((1, 10))
+    y = np.ones(1)
+    msg = r"1 sample\(s\) \(shape=\(1, 10\)\) while a minimum of 2 is" " required."
+    with pytest.raises(ValueError, match=msg):
+        check_X_y(X, y, ensure_min_samples=2)
+
+    # The same message is raised if the data has 2 dimensions even if this is
+    # not mandatory
+    with pytest.raises(ValueError, match=msg):
+        check_X_y(X, y, ensure_min_samples=2, ensure_2d=False)
+
+    # Simulate a model that would require at least 3 features (e.g. SelectKBest
+    # with k=3)
+    X = np.ones((10, 2))
+    y = np.ones(2)
+    msg = r"2 feature\(s\) \(shape=\(10, 2\)\) while a minimum of 3 is" " required."
+    with pytest.raises(ValueError, match=msg):
+        check_X_y(X, y, ensure_min_features=3)
+
+    # Only the feature check is enabled whenever the number of dimensions is 2
+    # even if allow_nd is enabled:
+    with pytest.raises(ValueError, match=msg):
+        check_X_y(X, y, ensure_min_features=3, allow_nd=True)
+
+    # Simulate a case where a pipeline stage as trimmed all the features of a
+    # 2D dataset.
+    X = np.empty(0).reshape(10, 0)
+    y = np.ones(10)
+    msg = r"0 feature\(s\) \(shape=\(10, 0\)\) while a minimum of 1 is" " required."
+    with pytest.raises(ValueError, match=msg):
+        check_X_y(X, y)
+
+    # nd-data is not checked for any minimum number of features by default:
+    X = np.ones((10, 0, 28, 28))
+    y = np.ones(10)
+    X_checked, y_checked = check_X_y(X, y, allow_nd=True)
+    assert_array_equal(X, X_checked)
+    assert_array_equal(y, y_checked)
+
+
+def test_check_array_complex_data_error():
+    X = np.array([[1 + 2j, 3 + 4j, 5 + 7j], [2 + 3j, 4 + 5j, 6 + 7j]])
+    with pytest.raises(ValueError, match="Complex data not supported"):
+        check_array(X)
+
+    # list of lists
+    X = [[1 + 2j, 3 + 4j, 5 + 7j], [2 + 3j, 4 + 5j, 6 + 7j]]
+    with pytest.raises(ValueError, match="Complex data not supported"):
+        check_array(X)
+
+    # tuple of tuples
+    X = ((1 + 2j, 3 + 4j, 5 + 7j), (2 + 3j, 4 + 5j, 6 + 7j))
+    with pytest.raises(ValueError, match="Complex data not supported"):
+        check_array(X)
+
+    # list of np arrays
+    X = [np.array([1 + 2j, 3 + 4j, 5 + 7j]), np.array([2 + 3j, 4 + 5j, 6 + 7j])]
+    with pytest.raises(ValueError, match="Complex data not supported"):
+        check_array(X)
+
+    # tuple of np arrays
+    X = (np.array([1 + 2j, 3 + 4j, 5 + 7j]), np.array([2 + 3j, 4 + 5j, 6 + 7j]))
+    with pytest.raises(ValueError, match="Complex data not supported"):
+        check_array(X)
+
+    # dataframe
+    X = MockDataFrame(np.array([[1 + 2j, 3 + 4j, 5 + 7j], [2 + 3j, 4 + 5j, 6 + 7j]]))
+    with pytest.raises(ValueError, match="Complex data not supported"):
+        check_array(X)
+
+    # sparse matrix
+    X = sp.coo_matrix([[0, 1 + 2j], [0, 0]])
+    with pytest.raises(ValueError, match="Complex data not supported"):
+        check_array(X)
+
+    # target variable does not always go through check_array but should
+    # never accept complex data either.
+    y = np.array([1 + 2j, 3 + 4j, 5 + 7j, 2 + 3j, 4 + 5j, 6 + 7j])
+    with pytest.raises(ValueError, match="Complex data not supported"):
+        _check_y(y)
+
+
+def test_has_fit_parameter():
+    assert not has_fit_parameter(KNeighborsClassifier, "sample_weight")
+    assert has_fit_parameter(RandomForestRegressor, "sample_weight")
+    assert has_fit_parameter(SVR, "sample_weight")
+    assert has_fit_parameter(SVR(), "sample_weight")
+
+    class TestClassWithDeprecatedFitMethod:
+        @deprecated("Deprecated for the purpose of testing has_fit_parameter")
+        def fit(self, X, y, sample_weight=None):
+            pass
+
+    assert has_fit_parameter(
+        TestClassWithDeprecatedFitMethod, "sample_weight"
+    ), "has_fit_parameter fails for class with deprecated fit method."
+
+
+def test_check_symmetric():
+    arr_sym = np.array([[0, 1], [1, 2]])
+    arr_bad = np.ones(2)
+    arr_asym = np.array([[0, 2], [0, 2]])
+
+    test_arrays = {
+        "dense": arr_asym,
+        "dok": sp.dok_matrix(arr_asym),
+        "csr": sp.csr_matrix(arr_asym),
+        "csc": sp.csc_matrix(arr_asym),
+        "coo": sp.coo_matrix(arr_asym),
+        "lil": sp.lil_matrix(arr_asym),
+        "bsr": sp.bsr_matrix(arr_asym),
+    }
+
+    # check error for bad inputs
+    with pytest.raises(ValueError):
+        check_symmetric(arr_bad)
+
+    # check that asymmetric arrays are properly symmetrized
+    for arr_format, arr in test_arrays.items():
+        # Check for warnings and errors
+        with pytest.warns(UserWarning):
+            check_symmetric(arr)
+        with pytest.raises(ValueError):
+            check_symmetric(arr, raise_exception=True)
+
+        output = check_symmetric(arr, raise_warning=False)
+        if sp.issparse(output):
+            assert output.format == arr_format
+            assert_array_equal(output.toarray(), arr_sym)
+        else:
+            assert_array_equal(output, arr_sym)
+
+
+def test_check_is_fitted_with_is_fitted():
+    class Estimator(BaseEstimator):
+        def fit(self, **kwargs):
+            self._is_fitted = True
+            return self
+
+        def __sklearn_is_fitted__(self):
+            return hasattr(self, "_is_fitted") and self._is_fitted
+
+    with pytest.raises(NotFittedError):
+        check_is_fitted(Estimator())
+    check_is_fitted(Estimator().fit())
+
+
+def test_check_is_fitted():
+    # Check is TypeError raised when non estimator instance passed
+    with pytest.raises(TypeError):
+        check_is_fitted(ARDRegression)
+    with pytest.raises(TypeError):
+        check_is_fitted("SVR")
+
+    ard = ARDRegression()
+    svr = SVR()
+
+    try:
+        with pytest.raises(NotFittedError):
+            check_is_fitted(ard)
+        with pytest.raises(NotFittedError):
+            check_is_fitted(svr)
+    except ValueError:
+        assert False, "check_is_fitted failed with ValueError"
+
+    # NotFittedError is a subclass of both ValueError and AttributeError
+    msg = "Random message %(name)s, %(name)s"
+    match = "Random message ARDRegression, ARDRegression"
+    with pytest.raises(ValueError, match=match):
+        check_is_fitted(ard, msg=msg)
+
+    msg = "Another message %(name)s, %(name)s"
+    match = "Another message SVR, SVR"
+    with pytest.raises(AttributeError, match=match):
+        check_is_fitted(svr, msg=msg)
+
+    ard.fit(*make_blobs())
+    svr.fit(*make_blobs())
+
+    assert check_is_fitted(ard) is None
+    assert check_is_fitted(svr) is None
+
+
+def test_check_is_fitted_attributes():
+    class MyEstimator:
+        def fit(self, X, y):
+            return self
+
+    msg = "not fitted"
+    est = MyEstimator()
+
+    with pytest.raises(NotFittedError, match=msg):
+        check_is_fitted(est, attributes=["a_", "b_"])
+    with pytest.raises(NotFittedError, match=msg):
+        check_is_fitted(est, attributes=["a_", "b_"], all_or_any=all)
+    with pytest.raises(NotFittedError, match=msg):
+        check_is_fitted(est, attributes=["a_", "b_"], all_or_any=any)
+
+    est.a_ = "a"
+    with pytest.raises(NotFittedError, match=msg):
+        check_is_fitted(est, attributes=["a_", "b_"])
+    with pytest.raises(NotFittedError, match=msg):
+        check_is_fitted(est, attributes=["a_", "b_"], all_or_any=all)
+    check_is_fitted(est, attributes=["a_", "b_"], all_or_any=any)
+
+    est.b_ = "b"
+    check_is_fitted(est, attributes=["a_", "b_"])
+    check_is_fitted(est, attributes=["a_", "b_"], all_or_any=all)
+    check_is_fitted(est, attributes=["a_", "b_"], all_or_any=any)
+
+
+@pytest.mark.parametrize(
+    "wrap", [itemgetter(0), list, tuple], ids=["single", "list", "tuple"]
+)
+def test_check_is_fitted_with_attributes(wrap):
+    ard = ARDRegression()
+    with pytest.raises(NotFittedError, match="is not fitted yet"):
+        check_is_fitted(ard, wrap(["coef_"]))
+
+    ard.fit(*make_blobs())
+
+    # Does not raise
+    check_is_fitted(ard, wrap(["coef_"]))
+
+    # Raises when using attribute that is not defined
+    with pytest.raises(NotFittedError, match="is not fitted yet"):
+        check_is_fitted(ard, wrap(["coef_bad_"]))
+
+
+def test_check_consistent_length():
+    check_consistent_length([1], [2], [3], [4], [5])
+    check_consistent_length([[1, 2], [[1, 2]]], [1, 2], ["a", "b"])
+    check_consistent_length([1], (2,), np.array([3]), sp.csr_matrix((1, 2)))
+    with pytest.raises(ValueError, match="inconsistent numbers of samples"):
+        check_consistent_length([1, 2], [1])
+    with pytest.raises(TypeError, match=r"got <\w+ 'int'>"):
+        check_consistent_length([1, 2], 1)
+    with pytest.raises(TypeError, match=r"got <\w+ 'object'>"):
+        check_consistent_length([1, 2], object())
+
+    with pytest.raises(TypeError):
+        check_consistent_length([1, 2], np.array(1))
+
+    # Despite ensembles having __len__ they must raise TypeError
+    with pytest.raises(TypeError, match="Expected sequence or array-like"):
+        check_consistent_length([1, 2], RandomForestRegressor())
+    # XXX: We should have a test with a string, but what is correct behaviour?
+
+
+def test_check_dataframe_fit_attribute():
+    # check pandas dataframe with 'fit' column does not raise error
+    # https://github.com/scikit-learn/scikit-learn/issues/8415
+    try:
+        import pandas as pd
+
+        X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+        X_df = pd.DataFrame(X, columns=["a", "b", "fit"])
+        check_consistent_length(X_df)
+    except ImportError:
+        raise SkipTest("Pandas not found")
+
+
+def test_suppress_validation():
+    X = np.array([0, np.inf])
+    with pytest.raises(ValueError):
+        assert_all_finite(X)
+    sklearn.set_config(assume_finite=True)
+    assert_all_finite(X)
+    sklearn.set_config(assume_finite=False)
+    with pytest.raises(ValueError):
+        assert_all_finite(X)
+
+
+def test_check_array_series():
+    # regression test that check_array works on pandas Series
+    pd = importorskip("pandas")
+    res = check_array(pd.Series([1, 2, 3]), ensure_2d=False)
+    assert_array_equal(res, np.array([1, 2, 3]))
+
+    # with categorical dtype (not a numpy dtype) (GH12699)
+    s = pd.Series(["a", "b", "c"]).astype("category")
+    res = check_array(s, dtype=None, ensure_2d=False)
+    assert_array_equal(res, np.array(["a", "b", "c"], dtype=object))
+
+
+@pytest.mark.parametrize(
+    "dtype", ((np.float64, np.float32), np.float64, None, "numeric")
+)
+@pytest.mark.parametrize("bool_dtype", ("bool", "boolean"))
+def test_check_dataframe_mixed_float_dtypes(dtype, bool_dtype):
+    # pandas dataframe will coerce a boolean into a object, this is a mismatch
+    # with np.result_type which will return a float
+    # check_array needs to explicitly check for bool dtype in a dataframe for
+    # this situation
+    # https://github.com/scikit-learn/scikit-learn/issues/15787
+
+    if bool_dtype == "boolean":
+        # boolean extension arrays was introduced in 1.0
+        pd = importorskip("pandas", minversion="1.0")
+    else:
+        pd = importorskip("pandas")
+
+    df = pd.DataFrame(
+        {
+            "int": [1, 2, 3],
+            "float": [0, 0.1, 2.1],
+            "bool": pd.Series([True, False, True], dtype=bool_dtype),
+        },
+        columns=["int", "float", "bool"],
+    )
+
+    array = check_array(df, dtype=dtype)
+    assert array.dtype == np.float64
+    expected_array = np.array(
+        [[1.0, 0.0, 1.0], [2.0, 0.1, 0.0], [3.0, 2.1, 1.0]], dtype=float
+    )
+    assert_allclose_dense_sparse(array, expected_array)
+
+
+def test_check_dataframe_with_only_bool():
+    """Check that dataframe with bool return a boolean arrays."""
+    pd = importorskip("pandas")
+    df = pd.DataFrame({"bool": [True, False, True]})
+
+    array = check_array(df, dtype=None)
+    assert array.dtype == np.bool_
+    assert_array_equal(array, [[True], [False], [True]])
+
+    # common dtype is int for bool + int
+    df = pd.DataFrame(
+        {"bool": [True, False, True], "int": [1, 2, 3]},
+        columns=["bool", "int"],
+    )
+    array = check_array(df, dtype="numeric")
+    assert array.dtype == np.int64
+    assert_array_equal(array, [[1, 1], [0, 2], [1, 3]])
+
+
+def test_check_dataframe_with_only_boolean():
+    """Check that dataframe with boolean return a float array with dtype=None"""
+    pd = importorskip("pandas", minversion="1.0")
+    df = pd.DataFrame({"bool": pd.Series([True, False, True], dtype="boolean")})
+
+    array = check_array(df, dtype=None)
+    assert array.dtype == np.float64
+    assert_array_equal(array, [[True], [False], [True]])
+
+
+class DummyMemory:
+    def cache(self, func):
+        return func
+
+
+class WrongDummyMemory:
+    pass
+
+
+def test_check_memory():
+    memory = check_memory("cache_directory")
+    assert memory.location == "cache_directory"
+
+    memory = check_memory(None)
+    assert memory.location is None
+
+    dummy = DummyMemory()
+    memory = check_memory(dummy)
+    assert memory is dummy
+
+    msg = (
+        "'memory' should be None, a string or have the same interface as"
+        " joblib.Memory. Got memory='1' instead."
+    )
+    with pytest.raises(ValueError, match=msg):
+        check_memory(1)
+    dummy = WrongDummyMemory()
+    msg = (
+        "'memory' should be None, a string or have the same interface as"
+        " joblib.Memory. Got memory='{}' instead.".format(dummy)
+    )
+    with pytest.raises(ValueError, match=msg):
+        check_memory(dummy)
+
+
+@pytest.mark.parametrize("copy", [True, False])
+def test_check_array_memmap(copy):
+    X = np.ones((4, 4))
+    with TempMemmap(X, mmap_mode="r") as X_memmap:
+        X_checked = check_array(X_memmap, copy=copy)
+        assert np.may_share_memory(X_memmap, X_checked) == (not copy)
+        assert X_checked.flags["WRITEABLE"] == copy
+
+
+@pytest.mark.parametrize(
+    "retype",
+    [
+        np.asarray,
+        sp.csr_matrix,
+        sp.csc_matrix,
+        sp.coo_matrix,
+        sp.lil_matrix,
+        sp.bsr_matrix,
+        sp.dok_matrix,
+        sp.dia_matrix,
+    ],
+)
+def test_check_non_negative(retype):
+    A = np.array([[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
+    X = retype(A)
+    check_non_negative(X, "")
+    X = retype([[0, 0], [0, 0]])
+    check_non_negative(X, "")
+
+    A[0, 0] = -1
+    X = retype(A)
+    with pytest.raises(ValueError, match="Negative "):
+        check_non_negative(X, "")
+
+
+def test_check_X_y_informative_error():
+    X = np.ones((2, 2))
+    y = None
+    msg = "estimator requires y to be passed, but the target y is None"
+    with pytest.raises(ValueError, match=msg):
+        check_X_y(X, y)
+
+    msg = "RandomForestRegressor requires y to be passed, but the target y is None"
+    with pytest.raises(ValueError, match=msg):
+        check_X_y(X, y, estimator=RandomForestRegressor())
+
+
+def test_retrieve_samples_from_non_standard_shape():
+    class TestNonNumericShape:
+        def __init__(self):
+            self.shape = ("not numeric",)
+
+        def __len__(self):
+            return len([1, 2, 3])
+
+    X = TestNonNumericShape()
+    assert _num_samples(X) == len(X)
+
+    # check that it gives a good error if there's no __len__
+    class TestNoLenWeirdShape:
+        def __init__(self):
+            self.shape = ("not numeric",)
+
+    with pytest.raises(TypeError, match="Expected sequence or array-like"):
+        _num_samples(TestNoLenWeirdShape())
+
+
+@pytest.mark.parametrize("x", [2, 3, 2.5, 5])
+def test_check_scalar_valid(x):
+    """Test that check_scalar returns no error/warning if valid inputs are
+    provided"""
+    with warnings.catch_warnings():
+        warnings.simplefilter("error")
+        scalar = check_scalar(
+            x,
+            "test_name",
+            target_type=numbers.Real,
+            min_val=2,
+            max_val=5,
+            include_boundaries="both",
+        )
+    assert scalar == x
+
+
+@pytest.mark.parametrize(
+    "x, target_name, target_type, min_val, max_val, include_boundaries, err_msg",
+    [
+        (
+            1,
+            "test_name1",
+            float,
+            2,
+            4,
+            "neither",
+            TypeError("test_name1 must be an instance of float, not int."),
+        ),
+        (
+            None,
+            "test_name1",
+            numbers.Real,
+            2,
+            4,
+            "neither",
+            TypeError("test_name1 must be an instance of float, not NoneType."),
+        ),
+        (
+            None,
+            "test_name1",
+            numbers.Integral,
+            2,
+            4,
+            "neither",
+            TypeError("test_name1 must be an instance of int, not NoneType."),
+        ),
+        (
+            1,
+            "test_name1",
+            (float, bool),
+            2,
+            4,
+            "neither",
+            TypeError("test_name1 must be an instance of {float, bool}, not int."),
+        ),
+        (
+            1,
+            "test_name2",
+            int,
+            2,
+            4,
+            "neither",
+            ValueError("test_name2 == 1, must be > 2."),
+        ),
+        (
+            5,
+            "test_name3",
+            int,
+            2,
+            4,
+            "neither",
+            ValueError("test_name3 == 5, must be < 4."),
+        ),
+        (
+            2,
+            "test_name4",
+            int,
+            2,
+            4,
+            "right",
+            ValueError("test_name4 == 2, must be > 2."),
+        ),
+        (
+            4,
+            "test_name5",
+            int,
+            2,
+            4,
+            "left",
+            ValueError("test_name5 == 4, must be < 4."),
+        ),
+        (
+            4,
+            "test_name6",
+            int,
+            2,
+            4,
+            "bad parameter value",
+            ValueError(
+                "Unknown value for `include_boundaries`: 'bad parameter value'. "
+                "Possible values are: ('left', 'right', 'both', 'neither')."
+            ),
+        ),
+        (
+            4,
+            "test_name7",
+            int,
+            None,
+            4,
+            "left",
+            ValueError(
+                "`include_boundaries`='left' without specifying explicitly `min_val` "
+                "is inconsistent."
+            ),
+        ),
+        (
+            4,
+            "test_name8",
+            int,
+            2,
+            None,
+            "right",
+            ValueError(
+                "`include_boundaries`='right' without specifying explicitly `max_val` "
+                "is inconsistent."
+            ),
+        ),
+    ],
+)
+def test_check_scalar_invalid(
+    x, target_name, target_type, min_val, max_val, include_boundaries, err_msg
+):
+    """Test that check_scalar returns the right error if a wrong input is
+    given"""
+    with pytest.raises(Exception) as raised_error:
+        check_scalar(
+            x,
+            target_name,
+            target_type=target_type,
+            min_val=min_val,
+            max_val=max_val,
+            include_boundaries=include_boundaries,
+        )
+    assert str(raised_error.value) == str(err_msg)
+    assert type(raised_error.value) == type(err_msg)
+
+
+_psd_cases_valid = {
+    "nominal": ((1, 2), np.array([1, 2]), None, ""),
+    "nominal_np_array": (np.array([1, 2]), np.array([1, 2]), None, ""),
+    "insignificant_imag": (
+        (5, 5e-5j),
+        np.array([5, 0]),
+        PositiveSpectrumWarning,
+        "There are imaginary parts in eigenvalues \\(1e\\-05 of the maximum real part",
+    ),
+    "insignificant neg": ((5, -5e-5), np.array([5, 0]), PositiveSpectrumWarning, ""),
+    "insignificant neg float32": (
+        np.array([1, -1e-6], dtype=np.float32),
+        np.array([1, 0], dtype=np.float32),
+        PositiveSpectrumWarning,
+        "There are negative eigenvalues \\(1e\\-06 of the maximum positive",
+    ),
+    "insignificant neg float64": (
+        np.array([1, -1e-10], dtype=np.float64),
+        np.array([1, 0], dtype=np.float64),
+        PositiveSpectrumWarning,
+        "There are negative eigenvalues \\(1e\\-10 of the maximum positive",
+    ),
+    "insignificant pos": (
+        (5, 4e-12),
+        np.array([5, 0]),
+        PositiveSpectrumWarning,
+        "the largest eigenvalue is more than 1e\\+12 times the smallest",
+    ),
+}
+
+
+@pytest.mark.parametrize(
+    "lambdas, expected_lambdas, w_type, w_msg",
+    list(_psd_cases_valid.values()),
+    ids=list(_psd_cases_valid.keys()),
+)
+@pytest.mark.parametrize("enable_warnings", [True, False])
+def test_check_psd_eigenvalues_valid(
+    lambdas, expected_lambdas, w_type, w_msg, enable_warnings
+):
+    # Test that ``_check_psd_eigenvalues`` returns the right output for valid
+    # input, possibly raising the right warning
+
+    if not enable_warnings:
+        w_type = None
+
+    if w_type is None:
+        with warnings.catch_warnings():
+            warnings.simplefilter("error", PositiveSpectrumWarning)
+            lambdas_fixed = _check_psd_eigenvalues(
+                lambdas, enable_warnings=enable_warnings
+            )
+    else:
+        with pytest.warns(w_type, match=w_msg):
+            lambdas_fixed = _check_psd_eigenvalues(
+                lambdas, enable_warnings=enable_warnings
+            )
+
+    assert_allclose(expected_lambdas, lambdas_fixed)
+
+
+_psd_cases_invalid = {
+    "significant_imag": (
+        (5, 5j),
+        ValueError,
+        "There are significant imaginary parts in eigenv",
+    ),
+    "all negative": (
+        (-5, -1),
+        ValueError,
+        "All eigenvalues are negative \\(maximum is -1",
+    ),
+    "significant neg": (
+        (5, -1),
+        ValueError,
+        "There are significant negative eigenvalues",
+    ),
+    "significant neg float32": (
+        np.array([3e-4, -2e-6], dtype=np.float32),
+        ValueError,
+        "There are significant negative eigenvalues",
+    ),
+    "significant neg float64": (
+        np.array([1e-5, -2e-10], dtype=np.float64),
+        ValueError,
+        "There are significant negative eigenvalues",
+    ),
+}
+
+
+@pytest.mark.parametrize(
+    "lambdas, err_type, err_msg",
+    list(_psd_cases_invalid.values()),
+    ids=list(_psd_cases_invalid.keys()),
+)
+def test_check_psd_eigenvalues_invalid(lambdas, err_type, err_msg):
+    # Test that ``_check_psd_eigenvalues`` raises the right error for invalid
+    # input
+
+    with pytest.raises(err_type, match=err_msg):
+        _check_psd_eigenvalues(lambdas)
+
+
+def test_check_sample_weight():
+    # check array order
+    sample_weight = np.ones(10)[::2]
+    assert not sample_weight.flags["C_CONTIGUOUS"]
+    sample_weight = _check_sample_weight(sample_weight, X=np.ones((5, 1)))
+    assert sample_weight.flags["C_CONTIGUOUS"]
+
+    # check None input
+    sample_weight = _check_sample_weight(None, X=np.ones((5, 2)))
+    assert_allclose(sample_weight, np.ones(5))
+
+    # check numbers input
+    sample_weight = _check_sample_weight(2.0, X=np.ones((5, 2)))
+    assert_allclose(sample_weight, 2 * np.ones(5))
+
+    # check wrong number of dimensions
+    with pytest.raises(ValueError, match="Sample weights must be 1D array or scalar"):
+        _check_sample_weight(np.ones((2, 4)), X=np.ones((2, 2)))
+
+    # check incorrect n_samples
+    msg = r"sample_weight.shape == \(4,\), expected \(2,\)!"
+    with pytest.raises(ValueError, match=msg):
+        _check_sample_weight(np.ones(4), X=np.ones((2, 2)))
+
+    # float32 dtype is preserved
+    X = np.ones((5, 2))
+    sample_weight = np.ones(5, dtype=np.float32)
+    sample_weight = _check_sample_weight(sample_weight, X)
+    assert sample_weight.dtype == np.float32
+
+    # int dtype will be converted to float64 instead
+    X = np.ones((5, 2), dtype=int)
+    sample_weight = _check_sample_weight(None, X, dtype=X.dtype)
+    assert sample_weight.dtype == np.float64
+
+    # check negative weight when only_non_negative=True
+    X = np.ones((5, 2))
+    sample_weight = np.ones(_num_samples(X))
+    sample_weight[-1] = -10
+    err_msg = "Negative values in data passed to `sample_weight`"
+    with pytest.raises(ValueError, match=err_msg):
+        _check_sample_weight(sample_weight, X, only_non_negative=True)
+
+
+@pytest.mark.parametrize("toarray", [np.array, sp.csr_matrix, sp.csc_matrix])
+def test_allclose_dense_sparse_equals(toarray):
+    base = np.arange(9).reshape(3, 3)
+    x, y = toarray(base), toarray(base)
+    assert _allclose_dense_sparse(x, y)
+
+
+@pytest.mark.parametrize("toarray", [np.array, sp.csr_matrix, sp.csc_matrix])
+def test_allclose_dense_sparse_not_equals(toarray):
+    base = np.arange(9).reshape(3, 3)
+    x, y = toarray(base), toarray(base + 1)
+    assert not _allclose_dense_sparse(x, y)
+
+
+@pytest.mark.parametrize("toarray", [sp.csr_matrix, sp.csc_matrix])
+def test_allclose_dense_sparse_raise(toarray):
+    x = np.arange(9).reshape(3, 3)
+    y = toarray(x + 1)
+
+    msg = "Can only compare two sparse matrices, not a sparse matrix and an array"
+    with pytest.raises(ValueError, match=msg):
+        _allclose_dense_sparse(x, y)
+
+
+def test_deprecate_positional_args_warns_for_function():
+    @_deprecate_positional_args
+    def f1(a, b, *, c=1, d=1):
+        pass
+
+    with pytest.warns(FutureWarning, match=r"Pass c=3 as keyword args"):
+        f1(1, 2, 3)
+
+    with pytest.warns(FutureWarning, match=r"Pass c=3, d=4 as keyword args"):
+        f1(1, 2, 3, 4)
+
+    @_deprecate_positional_args
+    def f2(a=1, *, b=1, c=1, d=1):
+        pass
+
+    with pytest.warns(FutureWarning, match=r"Pass b=2 as keyword args"):
+        f2(1, 2)
+
+    # The * is place before a keyword only argument without a default value
+    @_deprecate_positional_args
+    def f3(a, *, b, c=1, d=1):
+        pass
+
+    with pytest.warns(FutureWarning, match=r"Pass b=2 as keyword args"):
+        f3(1, 2)
+
+
+def test_deprecate_positional_args_warns_for_function_version():
+    @_deprecate_positional_args(version="1.1")
+    def f1(a, *, b):
+        pass
+
+    with pytest.warns(
+        FutureWarning, match=r"From version 1.1 passing these as positional"
+    ):
+        f1(1, 2)
+
+
+def test_deprecate_positional_args_warns_for_class():
+    class A1:
+        @_deprecate_positional_args
+        def __init__(self, a, b, *, c=1, d=1):
+            pass
+
+    with pytest.warns(FutureWarning, match=r"Pass c=3 as keyword args"):
+        A1(1, 2, 3)
+
+    with pytest.warns(FutureWarning, match=r"Pass c=3, d=4 as keyword args"):
+        A1(1, 2, 3, 4)
+
+    class A2:
+        @_deprecate_positional_args
+        def __init__(self, a=1, b=1, *, c=1, d=1):
+            pass
+
+    with pytest.warns(FutureWarning, match=r"Pass c=3 as keyword args"):
+        A2(1, 2, 3)
+
+    with pytest.warns(FutureWarning, match=r"Pass c=3, d=4 as keyword args"):
+        A2(1, 2, 3, 4)
+
+
+@pytest.mark.parametrize("indices", [None, [1, 3]])
+def test_check_fit_params(indices):
+    X = np.random.randn(4, 2)
+    fit_params = {
+        "list": [1, 2, 3, 4],
+        "array": np.array([1, 2, 3, 4]),
+        "sparse-col": sp.csc_matrix([1, 2, 3, 4]).T,
+        "sparse-row": sp.csc_matrix([1, 2, 3, 4]),
+        "scalar-int": 1,
+        "scalar-str": "xxx",
+        "None": None,
+    }
+    result = _check_fit_params(X, fit_params, indices)
+    indices_ = indices if indices is not None else list(range(X.shape[0]))
+
+    for key in ["sparse-row", "scalar-int", "scalar-str", "None"]:
+        assert result[key] is fit_params[key]
+
+    assert result["list"] == _safe_indexing(fit_params["list"], indices_)
+    assert_array_equal(result["array"], _safe_indexing(fit_params["array"], indices_))
+    assert_allclose_dense_sparse(
+        result["sparse-col"], _safe_indexing(fit_params["sparse-col"], indices_)
+    )
+
+
+@pytest.mark.parametrize("sp_format", [True, "csr", "csc", "coo", "bsr"])
+def test_check_sparse_pandas_sp_format(sp_format):
+    # check_array converts pandas dataframe with only sparse arrays into
+    # sparse matrix
+    pd = pytest.importorskip("pandas")
+    sp_mat = _sparse_random_matrix(10, 3)
+
+    sdf = pd.DataFrame.sparse.from_spmatrix(sp_mat)
+    result = check_array(sdf, accept_sparse=sp_format)
+
+    if sp_format is True:
+        # by default pandas converts to coo when accept_sparse is True
+        sp_format = "coo"
+
+    assert sp.issparse(result)
+    assert result.format == sp_format
+    assert_allclose_dense_sparse(sp_mat, result)
+
+
+@pytest.mark.parametrize(
+    "ntype1, ntype2",
+    [
+        ("longdouble", "float16"),
+        ("float16", "float32"),
+        ("float32", "double"),
+        ("int16", "int32"),
+        ("int32", "long"),
+        ("byte", "uint16"),
+        ("ushort", "uint32"),
+        ("uint32", "uint64"),
+        ("uint8", "int8"),
+    ],
+)
+def test_check_pandas_sparse_invalid(ntype1, ntype2):
+    """check that we raise an error with dataframe having
+    sparse extension arrays with unsupported mixed dtype
+    and pandas version below 1.1. pandas versions 1.1 and
+    above fixed this issue so no error will be raised."""
+    pd = pytest.importorskip("pandas")
+    df = pd.DataFrame(
+        {
+            "col1": pd.arrays.SparseArray([0, 1, 0], dtype=ntype1, fill_value=0),
+            "col2": pd.arrays.SparseArray([1, 0, 1], dtype=ntype2, fill_value=0),
+        }
+    )
+
+    if parse_version(pd.__version__) < parse_version("1.1"):
+        err_msg = "Pandas DataFrame with mixed sparse extension arrays"
+        with pytest.raises(ValueError, match=err_msg):
+            check_array(df, accept_sparse=["csr", "csc"])
+    else:
+        # pandas fixed this issue at 1.1 so from here on,
+        # no error will be raised.
+        check_array(df, accept_sparse=["csr", "csc"])
+
+
+@pytest.mark.parametrize(
+    "ntype1, ntype2, expected_subtype",
+    [
+        ("longfloat", "longdouble", np.floating),
+        ("float16", "half", np.floating),
+        ("single", "float32", np.floating),
+        ("double", "float64", np.floating),
+        ("int8", "byte", np.integer),
+        ("short", "int16", np.integer),
+        ("intc", "int32", np.integer),
+        ("intp", "long", np.integer),
+        ("int", "long", np.integer),
+        ("int64", "longlong", np.integer),
+        ("int_", "intp", np.integer),
+        ("ubyte", "uint8", np.unsignedinteger),
+        ("uint16", "ushort", np.unsignedinteger),
+        ("uintc", "uint32", np.unsignedinteger),
+        ("uint", "uint64", np.unsignedinteger),
+        ("uintp", "ulonglong", np.unsignedinteger),
+    ],
+)
+def test_check_pandas_sparse_valid(ntype1, ntype2, expected_subtype):
+    # check that we support the conversion of sparse dataframe with mixed
+    # type which can be converted safely.
+    pd = pytest.importorskip("pandas")
+    df = pd.DataFrame(
+        {
+            "col1": pd.arrays.SparseArray([0, 1, 0], dtype=ntype1, fill_value=0),
+            "col2": pd.arrays.SparseArray([1, 0, 1], dtype=ntype2, fill_value=0),
+        }
+    )
+    arr = check_array(df, accept_sparse=["csr", "csc"])
+    assert np.issubdtype(arr.dtype, expected_subtype)
+
+
+@pytest.mark.parametrize(
+    "constructor_name",
+    ["list", "tuple", "array", "dataframe", "sparse_csr", "sparse_csc"],
+)
+def test_num_features(constructor_name):
+    """Check _num_features for array-likes."""
+    X = [[1, 2, 3], [4, 5, 6]]
+    X = _convert_container(X, constructor_name)
+    assert _num_features(X) == 3
+
+
+@pytest.mark.parametrize(
+    "X",
+    [
+        [1, 2, 3],
+        ["a", "b", "c"],
+        [False, True, False],
+        [1.0, 3.4, 4.0],
+        [{"a": 1}, {"b": 2}, {"c": 3}],
+    ],
+    ids=["int", "str", "bool", "float", "dict"],
+)
+@pytest.mark.parametrize("constructor_name", ["list", "tuple", "array", "series"])
+def test_num_features_errors_1d_containers(X, constructor_name):
+    X = _convert_container(X, constructor_name)
+    if constructor_name == "array":
+        expected_type_name = "numpy.ndarray"
+    elif constructor_name == "series":
+        expected_type_name = "pandas.core.series.Series"
+    else:
+        expected_type_name = constructor_name
+    message = (
+        f"Unable to find the number of features from X of type {expected_type_name}"
+    )
+    if hasattr(X, "shape"):
+        message += " with shape (3,)"
+    elif isinstance(X[0], str):
+        message += " where the samples are of type str"
+    elif isinstance(X[0], dict):
+        message += " where the samples are of type dict"
+    with pytest.raises(TypeError, match=re.escape(message)):
+        _num_features(X)
+
+
+@pytest.mark.parametrize("X", [1, "b", False, 3.0], ids=["int", "str", "bool", "float"])
+def test_num_features_errors_scalars(X):
+    msg = f"Unable to find the number of features from X of type {type(X).__qualname__}"
+    with pytest.raises(TypeError, match=msg):
+        _num_features(X)
+
+
+@pytest.mark.parametrize(
+    "names",
+    [list(range(2)), range(2), None, [["a", "b"], ["c", "d"]]],
+    ids=["list-int", "range", "default", "MultiIndex"],
+)
+def test_get_feature_names_pandas_with_ints_no_warning(names):
+    """Get feature names with pandas dataframes without warning.
+
+    Column names with consistent dtypes will not warn, such as int or MultiIndex.
+    """
+    pd = pytest.importorskip("pandas")
+    X = pd.DataFrame([[1, 2], [4, 5], [5, 6]], columns=names)
+
+    with warnings.catch_warnings():
+        warnings.simplefilter("error", FutureWarning)
+        names = _get_feature_names(X)
+    assert names is None
+
+
+def test_get_feature_names_pandas():
+    """Get feature names with pandas dataframes."""
+    pd = pytest.importorskip("pandas")
+    columns = [f"col_{i}" for i in range(3)]
+    X = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=columns)
+    feature_names = _get_feature_names(X)
+
+    assert_array_equal(feature_names, columns)
+
+
+def test_get_feature_names_numpy():
+    """Get feature names return None for numpy arrays."""
+    X = np.array([[1, 2, 3], [4, 5, 6]])
+    names = _get_feature_names(X)
+    assert names is None
+
+
+@pytest.mark.parametrize(
+    "names, dtypes",
+    [
+        (["a", 1], "['int', 'str']"),
+        (["pizza", ["a", "b"]], "['list', 'str']"),
+    ],
+    ids=["int-str", "list-str"],
+)
+def test_get_feature_names_invalid_dtypes(names, dtypes):
+    """Get feature names errors when the feature names have mixed dtypes"""
+    pd = pytest.importorskip("pandas")
+    X = pd.DataFrame([[1, 2], [4, 5], [5, 6]], columns=names)
+
+    msg = re.escape(
+        "Feature names are only supported if all input features have string names, "
+        f"but your input has {dtypes} as feature name / column name types. "
+        "If you want feature names to be stored and validated, you must convert "
+        "them all to strings, by using X.columns = X.columns.astype(str) for "
+        "example. Otherwise you can remove feature / column names from your input "
+        "data, or convert them all to a non-string data type."
+    )
+    with pytest.raises(TypeError, match=msg):
+        names = _get_feature_names(X)
+
+
+class PassthroughTransformer(BaseEstimator):
+    def fit(self, X, y=None):
+        self._validate_data(X, reset=True)
+        return self
+
+    def transform(self, X):
+        return X
+
+    def get_feature_names_out(self, input_features=None):
+        return _check_feature_names_in(self, input_features)
+
+
+def test_check_feature_names_in():
+    """Check behavior of check_feature_names_in for arrays."""
+    X = np.array([[0.0, 1.0, 2.0]])
+    est = PassthroughTransformer().fit(X)
+
+    names = est.get_feature_names_out()
+    assert_array_equal(names, ["x0", "x1", "x2"])
+
+    incorrect_len_names = ["x10", "x1"]
+    with pytest.raises(ValueError, match="input_features should have length equal to"):
+        est.get_feature_names_out(incorrect_len_names)
+
+    # remove n_feature_in_
+    del est.n_features_in_
+    with pytest.raises(ValueError, match="Unable to generate feature names"):
+        est.get_feature_names_out()
+
+
+def test_check_feature_names_in_pandas():
+    """Check behavior of check_feature_names_in for pandas dataframes."""
+    pd = pytest.importorskip("pandas")
+    names = ["a", "b", "c"]
+    df = pd.DataFrame([[0.0, 1.0, 2.0]], columns=names)
+    est = PassthroughTransformer().fit(df)
+
+    names = est.get_feature_names_out()
+    assert_array_equal(names, ["a", "b", "c"])
+
+    with pytest.raises(ValueError, match="input_features is not equal to"):
+        est.get_feature_names_out(["x1", "x2", "x3"])
+
+
+def test_boolean_series_remains_boolean():
+    """Regression test for gh-25145"""
+    pd = importorskip("pandas")
+    res = check_array(pd.Series([True, False]), ensure_2d=False)
+    expected = np.array([True, False])
+
+    assert res.dtype == expected.dtype
+    assert_array_equal(res, expected)
+
+
+@pytest.mark.parametrize("array_namespace", ["numpy.array_api", "cupy.array_api"])
+def test_check_array_array_api_has_non_finite(array_namespace):
+    """Checks that Array API arrays checks non-finite correctly."""
+    xp = pytest.importorskip(array_namespace)
+
+    X_nan = xp.asarray([[xp.nan, 1, 0], [0, xp.nan, 3]], dtype=xp.float32)
+    with config_context(array_api_dispatch=True):
+        with pytest.raises(ValueError, match="Input contains NaN."):
+            check_array(X_nan)
+
+    X_inf = xp.asarray([[xp.inf, 1, 0], [0, xp.inf, 3]], dtype=xp.float32)
+    with config_context(array_api_dispatch=True):
+        with pytest.raises(ValueError, match="infinity or a value too large"):
+            check_array(X_inf)
diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cholesky_solve_helper_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cholesky_solve_helper_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..89609b25562942767e5288ec3bd5d007ca05eebf
--- /dev/null
+++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cholesky_solve_helper_native.h
@@ -0,0 +1,23 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor & _cholesky_solve_helper_out(const at::Tensor & self, const at::Tensor & A, bool upper, at::Tensor & out);
+TORCH_API at::Tensor _cholesky_solve_helper_cpu(const at::Tensor & self, const at::Tensor & A, bool upper);
+TORCH_API at::Tensor _cholesky_solve_helper_cuda(const at::Tensor & self, const at::Tensor & A, bool upper);
+} // namespace native
+} // namespace at
diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_remove_batch_dim_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_remove_batch_dim_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..4c38a770adb6a2c7ee6104d280b277118ff1bb31
--- /dev/null
+++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_remove_batch_dim_ops.h
@@ -0,0 +1,28 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API _remove_batch_dim {
+  using schema = at::Tensor (const at::Tensor &, int64_t, int64_t, int64_t);
+  using ptr_schema = schema*;
+  // See Note [static constexpr char* members for windows NVCC]
+  STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_remove_batch_dim")
+  STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
+  STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_remove_batch_dim(Tensor self, int level, int batch_size, int out_dim) -> Tensor")
+  static at::Tensor call(const at::Tensor & self, int64_t level, int64_t batch_size, int64_t out_dim);
+  static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t level, int64_t batch_size, int64_t out_dim);
+};
+
+}} // namespace at::_ops
diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/all_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/all_compositeexplicitautograd_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..9fd45ef71a96a3c9bbf6fba87ec549d5166a636c
--- /dev/null
+++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/all_compositeexplicitautograd_dispatch.h
@@ -0,0 +1,25 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace compositeexplicitautograd {
+
+TORCH_API at::Tensor all(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false);
+TORCH_API at::Tensor & all_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false);
+TORCH_API at::Tensor & all_outf(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, at::Tensor & out);
+
+} // namespace compositeexplicitautograd
+} // namespace at
diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/diagonal_scatter.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/diagonal_scatter.h
new file mode 100644
index 0000000000000000000000000000000000000000..99f583db9d9bd812581dfad258e07f10bb080670
--- /dev/null
+++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/diagonal_scatter.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::diagonal_scatter(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1) -> Tensor
+inline at::Tensor diagonal_scatter(const at::Tensor & self, const at::Tensor & src, int64_t offset=0, int64_t dim1=0, int64_t dim2=1) {
+    return at::_ops::diagonal_scatter::call(self, src, offset, dim1, dim2);
+}
+
+// aten::diagonal_scatter.out(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & diagonal_scatter_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, int64_t offset=0, int64_t dim1=0, int64_t dim2=1) {
+    return at::_ops::diagonal_scatter_out::call(self, src, offset, dim1, dim2, out);
+}
+// aten::diagonal_scatter.out(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & diagonal_scatter_outf(const at::Tensor & self, const at::Tensor & src, int64_t offset, int64_t dim1, int64_t dim2, at::Tensor & out) {
+    return at::_ops::diagonal_scatter_out::call(self, src, offset, dim1, dim2, out);
+}
+
+}
diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_neg_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_neg_ops.h
new file mode 100644
index 0000000000000000000000000000000000000000..bbdbdc6ce135ae86576da68c1e2512245cf717c8
--- /dev/null
+++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_neg_ops.h
@@ -0,0 +1,28 @@
+#pragma once
+
+// @generated by torchgen/gen.py from Operator.h
+
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+namespace _ops {
+
+
+struct TORCH_API is_neg {
+  using schema = bool (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::is_neg")
+  STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
+  STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "is_neg(Tensor self) -> bool")
+  static bool call(const at::Tensor & self);
+  static bool redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
+};
+
+}} // namespace at::_ops
diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/lcm_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/lcm_cuda_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..afe9b21d06f08f6ec6b7d27ffcc6579799866b33
--- /dev/null
+++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/lcm_cuda_dispatch.h
@@ -0,0 +1,26 @@
+#pragma once
+// @generated by torchgen/gen.py from DispatchKeyFunction.h
+
+// NB: The implementing C++ file is RegisterDispatchKey.cpp
+
+// The only #includes we need are for custom classes that have defaults in the C++ API
+#include 
+#include 
+#include 
+
+// Forward declarations of any types needed in the operator signatures.
+// We can't directly include these classes because it will cause circular include dependencies.
+// This file is included by TensorBody.h, which defines the Tensor class.
+#include 
+
+namespace at {
+
+namespace cuda {
+
+TORCH_API at::Tensor lcm(const at::Tensor & self, const at::Tensor & other);
+TORCH_API at::Tensor & lcm_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other);
+TORCH_API at::Tensor & lcm_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
+TORCH_API at::Tensor & lcm_(at::Tensor & self, const at::Tensor & other);
+
+} // namespace cuda
+} // namespace at
diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_eigh.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_eigh.h
new file mode 100644
index 0000000000000000000000000000000000000000..1cb0c49a9d885bec2e6e86dc038c4018c80aab4b
--- /dev/null
+++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linalg_eigh.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::linalg_eigh(Tensor self, str UPLO="L") -> (Tensor eigenvalues, Tensor eigenvectors)
+inline ::std::tuple linalg_eigh(const at::Tensor & self, c10::string_view UPLO="L") {
+    return at::_ops::linalg_eigh::call(self, UPLO);
+}
+
+// aten::linalg_eigh.eigvals(Tensor self, str UPLO="L", *, Tensor(a!) eigvals, Tensor(b!) eigvecs) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors)
+inline ::std::tuple linalg_eigh_out(at::Tensor & eigvals, at::Tensor & eigvecs, const at::Tensor & self, c10::string_view UPLO="L") {
+    return at::_ops::linalg_eigh_eigvals::call(self, UPLO, eigvals, eigvecs);
+}
+// aten::linalg_eigh.eigvals(Tensor self, str UPLO="L", *, Tensor(a!) eigvals, Tensor(b!) eigvecs) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors)
+inline ::std::tuple linalg_eigh_outf(const at::Tensor & self, c10::string_view UPLO, at::Tensor & eigvals, at::Tensor & eigvecs) {
+    return at::_ops::linalg_eigh_eigvals::call(self, UPLO, eigvals, eigvecs);
+}
+
+}
diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/masked_scatter_backward_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/masked_scatter_backward_native.h
new file mode 100644
index 0000000000000000000000000000000000000000..b30b8328e0b95d3936bd6594ff051be5be27cdcf
--- /dev/null
+++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/masked_scatter_backward_native.h
@@ -0,0 +1,21 @@
+#pragma once
+
+// @generated by torchgen/gen.py from NativeFunction.h
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+
+namespace at {
+namespace native {
+TORCH_API at::Tensor masked_scatter_backward_symint(const at::Tensor & grad_output, const at::Tensor & mask, c10::SymIntArrayRef sizes);
+} // namespace native
+} // namespace at
diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/quantize_per_tensor_dynamic_cpu_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/quantize_per_tensor_dynamic_cpu_dispatch.h
new file mode 100644
index 0000000000000000000000000000000000000000..e11753928b5bf51f0dfa946e1606e5de8cf1e6f8
--- /dev/null
+++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/quantize_per_tensor_dynamic_cpu_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 cpu {
+
+TORCH_API at::Tensor quantize_per_tensor_dynamic(const at::Tensor & self, at::ScalarType dtype, bool reduce_range);
+
+} // namespace cpu
+} // namespace at
diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/tensordot.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/tensordot.h
new file mode 100644
index 0000000000000000000000000000000000000000..d883b84a5ff3a79a33c0242407d2dbef256074bd
--- /dev/null
+++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/tensordot.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::tensordot(Tensor self, Tensor other, int[] dims_self, int[] dims_other) -> Tensor
+inline at::Tensor tensordot(const at::Tensor & self, const at::Tensor & other, at::IntArrayRef dims_self, at::IntArrayRef dims_other) {
+    return at::_ops::tensordot::call(self, other, dims_self, dims_other);
+}
+
+// aten::tensordot.out(Tensor self, Tensor other, int[] dims_self, int[] dims_other, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & tensordot_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other, at::IntArrayRef dims_self, at::IntArrayRef dims_other) {
+    return at::_ops::tensordot_out::call(self, other, dims_self, dims_other, out);
+}
+// aten::tensordot.out(Tensor self, Tensor other, int[] dims_self, int[] dims_other, *, Tensor(a!) out) -> Tensor(a!)
+inline at::Tensor & tensordot_outf(const at::Tensor & self, const at::Tensor & other, at::IntArrayRef dims_self, at::IntArrayRef dims_other, at::Tensor & out) {
+    return at::_ops::tensordot_out::call(self, other, dims_self, dims_other, out);
+}
+
+}