ZTWHHH commited on
Commit
e1bb021
·
verified ·
1 Parent(s): 552ea6a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +9 -0
  2. videollama2/lib/python3.10/site-packages/sklearn/cluster/_agglomerative.py +1333 -0
  3. videollama2/lib/python3.10/site-packages/sklearn/cluster/_bicluster.py +628 -0
  4. videollama2/lib/python3.10/site-packages/sklearn/cluster/_feature_agglomeration.py +75 -0
  5. videollama2/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so +3 -0
  6. videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.cpython-310-x86_64-linux-gnu.so +3 -0
  7. videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pxd +19 -0
  8. videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_elkan.cpython-310-x86_64-linux-gnu.so +3 -0
  9. videollama2/lib/python3.10/site-packages/sklearn/cluster/_mean_shift.py +536 -0
  10. videollama2/lib/python3.10/site-packages/sklearn/cluster/_spectral.py +791 -0
  11. videollama2/lib/python3.10/site-packages/sklearn/ensemble/__pycache__/_base.cpython-310.pyc +0 -0
  12. videollama2/lib/python3.10/site-packages/sklearn/ensemble/__pycache__/_iforest.cpython-310.pyc +0 -0
  13. videollama2/lib/python3.10/site-packages/sklearn/feature_selection/__init__.py +53 -0
  14. videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_from_model.py +444 -0
  15. videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_mutual_info.py +468 -0
  16. videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_rfe.py +765 -0
  17. videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_sequential.py +325 -0
  18. videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_univariate_selection.py +1052 -0
  19. videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_variance_threshold.py +135 -0
  20. videollama2/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_feature_select.py +946 -0
  21. videollama2/lib/python3.10/site-packages/sklearn/tree/_classes.py +1769 -0
  22. videollama2/lib/python3.10/site-packages/sklearn/tree/_splitter.pxd +100 -0
  23. videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__init__.py +0 -0
  24. videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  25. videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_export.cpython-310.pyc +0 -0
  26. videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_reingold_tilford.cpython-310.pyc +0 -0
  27. videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_tree.cpython-310.pyc +0 -0
  28. videollama2/lib/python3.10/site-packages/sklearn/tree/tests/test_export.py +512 -0
  29. videollama2/lib/python3.10/site-packages/sklearn/tree/tests/test_tree.py +2430 -0
  30. videollama2/lib/python3.10/site-packages/sklearn/utils/_arpack.py +30 -0
  31. videollama2/lib/python3.10/site-packages/sklearn/utils/_array_api.py +232 -0
  32. videollama2/lib/python3.10/site-packages/sklearn/utils/_joblib.py +31 -0
  33. videollama2/lib/python3.10/site-packages/sklearn/utils/_logistic_sigmoid.cpython-310-x86_64-linux-gnu.so +3 -0
  34. videollama2/lib/python3.10/site-packages/sklearn/utils/_mask.py +62 -0
  35. videollama2/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.cpython-310-x86_64-linux-gnu.so +0 -0
  36. videollama2/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.pxd +6 -0
  37. videollama2/lib/python3.10/site-packages/sklearn/utils/_param_validation.py +943 -0
  38. videollama2/lib/python3.10/site-packages/sklearn/utils/_random.cpython-310-x86_64-linux-gnu.so +3 -0
  39. videollama2/lib/python3.10/site-packages/sklearn/utils/_readonly_array_wrapper.cpython-310-x86_64-linux-gnu.so +3 -0
  40. videollama2/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.cpython-310-x86_64-linux-gnu.so +3 -0
  41. videollama2/lib/python3.10/site-packages/sklearn/utils/_show_versions.py +108 -0
  42. videollama2/lib/python3.10/site-packages/sklearn/utils/_sorting.cpython-310-x86_64-linux-gnu.so +0 -0
  43. videollama2/lib/python3.10/site-packages/sklearn/utils/_tags.py +67 -0
  44. videollama2/lib/python3.10/site-packages/sklearn/utils/_testing.py +1057 -0
  45. videollama2/lib/python3.10/site-packages/sklearn/utils/_typedefs.pxd +28 -0
  46. videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.pxd +12 -0
  47. videollama2/lib/python3.10/site-packages/sklearn/utils/discovery.py +217 -0
  48. videollama2/lib/python3.10/site-packages/sklearn/utils/estimator_checks.py +0 -0
  49. videollama2/lib/python3.10/site-packages/sklearn/utils/murmurhash.cpython-310-x86_64-linux-gnu.so +3 -0
  50. videollama2/lib/python3.10/site-packages/sklearn/utils/parallel.py +123 -0
.gitattributes CHANGED
@@ -1915,3 +1915,12 @@ videollama2/lib/python3.10/site-packages/sklearn/tree/_tree.cpython-310-x86_64-l
1915
  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
1916
  videollama2/lib/python3.10/site-packages/sklearn/utils/arrayfuncs.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1917
  videollama2/lib/python3.10/site-packages/sklearn/utils/_cython_blas.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
1915
  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
1916
  videollama2/lib/python3.10/site-packages/sklearn/utils/arrayfuncs.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1917
  videollama2/lib/python3.10/site-packages/sklearn/utils/_cython_blas.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1918
+ videollama2/lib/python3.10/site-packages/sklearn/utils/_logistic_sigmoid.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1919
+ videollama2/lib/python3.10/site-packages/sklearn/utils/murmurhash.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1920
+ videollama2/lib/python3.10/site-packages/sklearn/utils/_random.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1921
+ videollama2/lib/python3.10/site-packages/sklearn/utils/sparsefuncs_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1922
+ videollama2/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1923
+ 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
1924
+ 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
1925
+ 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
1926
+ videollama2/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
videollama2/lib/python3.10/site-packages/sklearn/cluster/_agglomerative.py ADDED
@@ -0,0 +1,1333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hierarchical Agglomerative Clustering
2
+
3
+ These routines perform some hierarchical agglomerative clustering of some
4
+ input data.
5
+
6
+ Authors : Vincent Michel, Bertrand Thirion, Alexandre Gramfort,
7
+ Gael Varoquaux
8
+ License: BSD 3 clause
9
+ """
10
+ import warnings
11
+ from heapq import heapify, heappop, heappush, heappushpop
12
+ from numbers import Integral, Real
13
+
14
+ import numpy as np
15
+ from scipy import sparse
16
+ from scipy.sparse.csgraph import connected_components
17
+
18
+ from ..base import BaseEstimator, ClusterMixin, ClassNamePrefixFeaturesOutMixin
19
+ from ..metrics.pairwise import paired_distances
20
+ from ..metrics.pairwise import _VALID_METRICS
21
+ from ..metrics import DistanceMetric
22
+ from ..metrics._dist_metrics import METRIC_MAPPING
23
+ from ..utils import check_array
24
+ from ..utils._fast_dict import IntFloatDict
25
+ from ..utils.graph import _fix_connected_components
26
+ from ..utils._param_validation import Hidden, Interval, StrOptions, HasMethods
27
+ from ..utils.validation import check_memory
28
+
29
+ # mypy error: Module 'sklearn.cluster' has no attribute '_hierarchical_fast'
30
+ from . import _hierarchical_fast as _hierarchical # type: ignore
31
+ from ._feature_agglomeration import AgglomerationTransform
32
+
33
+ ###############################################################################
34
+ # For non fully-connected graphs
35
+
36
+
37
+ def _fix_connectivity(X, connectivity, affinity):
38
+ """
39
+ Fixes the connectivity matrix.
40
+
41
+ The different steps are:
42
+
43
+ - copies it
44
+ - makes it symmetric
45
+ - converts it to LIL if necessary
46
+ - completes it if necessary.
47
+
48
+ Parameters
49
+ ----------
50
+ X : array-like of shape (n_samples, n_features)
51
+ Feature matrix representing `n_samples` samples to be clustered.
52
+
53
+ connectivity : sparse matrix, default=None
54
+ Connectivity matrix. Defines for each sample the neighboring samples
55
+ following a given structure of the data. The matrix is assumed to
56
+ be symmetric and only the upper triangular half is used.
57
+ Default is `None`, i.e, the Ward algorithm is unstructured.
58
+
59
+ affinity : {"euclidean", "precomputed"}, default="euclidean"
60
+ Which affinity to use. At the moment `precomputed` and
61
+ ``euclidean`` are supported. `euclidean` uses the
62
+ negative squared Euclidean distance between points.
63
+
64
+ Returns
65
+ -------
66
+ connectivity : sparse matrix
67
+ The fixed connectivity matrix.
68
+
69
+ n_connected_components : int
70
+ The number of connected components in the graph.
71
+ """
72
+ n_samples = X.shape[0]
73
+ if connectivity.shape[0] != n_samples or connectivity.shape[1] != n_samples:
74
+ raise ValueError(
75
+ "Wrong shape for connectivity matrix: %s when X is %s"
76
+ % (connectivity.shape, X.shape)
77
+ )
78
+
79
+ # Make the connectivity matrix symmetric:
80
+ connectivity = connectivity + connectivity.T
81
+
82
+ # Convert connectivity matrix to LIL
83
+ if not sparse.isspmatrix_lil(connectivity):
84
+ if not sparse.isspmatrix(connectivity):
85
+ connectivity = sparse.lil_matrix(connectivity)
86
+ else:
87
+ connectivity = connectivity.tolil()
88
+
89
+ # Compute the number of nodes
90
+ n_connected_components, labels = connected_components(connectivity)
91
+
92
+ if n_connected_components > 1:
93
+ warnings.warn(
94
+ "the number of connected components of the "
95
+ "connectivity matrix is %d > 1. Completing it to avoid "
96
+ "stopping the tree early." % n_connected_components,
97
+ stacklevel=2,
98
+ )
99
+ # XXX: Can we do without completing the matrix?
100
+ connectivity = _fix_connected_components(
101
+ X=X,
102
+ graph=connectivity,
103
+ n_connected_components=n_connected_components,
104
+ component_labels=labels,
105
+ metric=affinity,
106
+ mode="connectivity",
107
+ )
108
+
109
+ return connectivity, n_connected_components
110
+
111
+
112
+ def _single_linkage_tree(
113
+ connectivity,
114
+ n_samples,
115
+ n_nodes,
116
+ n_clusters,
117
+ n_connected_components,
118
+ return_distance,
119
+ ):
120
+ """
121
+ Perform single linkage clustering on sparse data via the minimum
122
+ spanning tree from scipy.sparse.csgraph, then using union-find to label.
123
+ The parent array is then generated by walking through the tree.
124
+ """
125
+ from scipy.sparse.csgraph import minimum_spanning_tree
126
+
127
+ # explicitly cast connectivity to ensure safety
128
+ connectivity = connectivity.astype(np.float64, copy=False)
129
+
130
+ # Ensure zero distances aren't ignored by setting them to "epsilon"
131
+ epsilon_value = np.finfo(dtype=connectivity.data.dtype).eps
132
+ connectivity.data[connectivity.data == 0] = epsilon_value
133
+
134
+ # Use scipy.sparse.csgraph to generate a minimum spanning tree
135
+ mst = minimum_spanning_tree(connectivity.tocsr())
136
+
137
+ # Convert the graph to scipy.cluster.hierarchy array format
138
+ mst = mst.tocoo()
139
+
140
+ # Undo the epsilon values
141
+ mst.data[mst.data == epsilon_value] = 0
142
+
143
+ mst_array = np.vstack([mst.row, mst.col, mst.data]).T
144
+
145
+ # Sort edges of the min_spanning_tree by weight
146
+ mst_array = mst_array[np.argsort(mst_array.T[2], kind="mergesort"), :]
147
+
148
+ # Convert edge list into standard hierarchical clustering format
149
+ single_linkage_tree = _hierarchical._single_linkage_label(mst_array)
150
+ children_ = single_linkage_tree[:, :2].astype(int)
151
+
152
+ # Compute parents
153
+ parent = np.arange(n_nodes, dtype=np.intp)
154
+ for i, (left, right) in enumerate(children_, n_samples):
155
+ if n_clusters is not None and i >= n_nodes:
156
+ break
157
+ if left < n_nodes:
158
+ parent[left] = i
159
+ if right < n_nodes:
160
+ parent[right] = i
161
+
162
+ if return_distance:
163
+ distances = single_linkage_tree[:, 2]
164
+ return children_, n_connected_components, n_samples, parent, distances
165
+ return children_, n_connected_components, n_samples, parent
166
+
167
+
168
+ ###############################################################################
169
+ # Hierarchical tree building functions
170
+
171
+
172
+ def ward_tree(X, *, connectivity=None, n_clusters=None, return_distance=False):
173
+ """Ward clustering based on a Feature matrix.
174
+
175
+ Recursively merges the pair of clusters that minimally increases
176
+ within-cluster variance.
177
+
178
+ The inertia matrix uses a Heapq-based representation.
179
+
180
+ This is the structured version, that takes into account some topological
181
+ structure between samples.
182
+
183
+ Read more in the :ref:`User Guide <hierarchical_clustering>`.
184
+
185
+ Parameters
186
+ ----------
187
+ X : array-like of shape (n_samples, n_features)
188
+ Feature matrix representing `n_samples` samples to be clustered.
189
+
190
+ connectivity : sparse matrix, default=None
191
+ Connectivity matrix. Defines for each sample the neighboring samples
192
+ following a given structure of the data. The matrix is assumed to
193
+ be symmetric and only the upper triangular half is used.
194
+ Default is None, i.e, the Ward algorithm is unstructured.
195
+
196
+ n_clusters : int, default=None
197
+ `n_clusters` should be less than `n_samples`. Stop early the
198
+ construction of the tree at `n_clusters.` This is useful to decrease
199
+ computation time if the number of clusters is not small compared to the
200
+ number of samples. In this case, the complete tree is not computed, thus
201
+ the 'children' output is of limited use, and the 'parents' output should
202
+ rather be used. This option is valid only when specifying a connectivity
203
+ matrix.
204
+
205
+ return_distance : bool, default=False
206
+ If `True`, return the distance between the clusters.
207
+
208
+ Returns
209
+ -------
210
+ children : ndarray of shape (n_nodes-1, 2)
211
+ The children of each non-leaf node. Values less than `n_samples`
212
+ correspond to leaves of the tree which are the original samples.
213
+ A node `i` greater than or equal to `n_samples` is a non-leaf
214
+ node and has children `children_[i - n_samples]`. Alternatively
215
+ at the i-th iteration, children[i][0] and children[i][1]
216
+ are merged to form node `n_samples + i`.
217
+
218
+ n_connected_components : int
219
+ The number of connected components in the graph.
220
+
221
+ n_leaves : int
222
+ The number of leaves in the tree.
223
+
224
+ parents : ndarray of shape (n_nodes,) or None
225
+ The parent of each node. Only returned when a connectivity matrix
226
+ is specified, elsewhere 'None' is returned.
227
+
228
+ distances : ndarray of shape (n_nodes-1,)
229
+ Only returned if `return_distance` is set to `True` (for compatibility).
230
+ The distances between the centers of the nodes. `distances[i]`
231
+ corresponds to a weighted Euclidean distance between
232
+ the nodes `children[i, 1]` and `children[i, 2]`. If the nodes refer to
233
+ leaves of the tree, then `distances[i]` is their unweighted Euclidean
234
+ distance. Distances are updated in the following way
235
+ (from scipy.hierarchy.linkage):
236
+
237
+ The new entry :math:`d(u,v)` is computed as follows,
238
+
239
+ .. math::
240
+
241
+ d(u,v) = \\sqrt{\\frac{|v|+|s|}
242
+ {T}d(v,s)^2
243
+ + \\frac{|v|+|t|}
244
+ {T}d(v,t)^2
245
+ - \\frac{|v|}
246
+ {T}d(s,t)^2}
247
+
248
+ where :math:`u` is the newly joined cluster consisting of
249
+ clusters :math:`s` and :math:`t`, :math:`v` is an unused
250
+ cluster in the forest, :math:`T=|v|+|s|+|t|`, and
251
+ :math:`|*|` is the cardinality of its argument. This is also
252
+ known as the incremental algorithm.
253
+ """
254
+ X = np.asarray(X)
255
+ if X.ndim == 1:
256
+ X = np.reshape(X, (-1, 1))
257
+ n_samples, n_features = X.shape
258
+
259
+ if connectivity is None:
260
+ from scipy.cluster import hierarchy # imports PIL
261
+
262
+ if n_clusters is not None:
263
+ warnings.warn(
264
+ "Partial build of the tree is implemented "
265
+ "only for structured clustering (i.e. with "
266
+ "explicit connectivity). The algorithm "
267
+ "will build the full tree and only "
268
+ "retain the lower branches required "
269
+ "for the specified number of clusters",
270
+ stacklevel=2,
271
+ )
272
+ X = np.require(X, requirements="W")
273
+ out = hierarchy.ward(X)
274
+ children_ = out[:, :2].astype(np.intp)
275
+
276
+ if return_distance:
277
+ distances = out[:, 2]
278
+ return children_, 1, n_samples, None, distances
279
+ else:
280
+ return children_, 1, n_samples, None
281
+
282
+ connectivity, n_connected_components = _fix_connectivity(
283
+ X, connectivity, affinity="euclidean"
284
+ )
285
+ if n_clusters is None:
286
+ n_nodes = 2 * n_samples - 1
287
+ else:
288
+ if n_clusters > n_samples:
289
+ raise ValueError(
290
+ "Cannot provide more clusters than samples. "
291
+ "%i n_clusters was asked, and there are %i "
292
+ "samples." % (n_clusters, n_samples)
293
+ )
294
+ n_nodes = 2 * n_samples - n_clusters
295
+
296
+ # create inertia matrix
297
+ coord_row = []
298
+ coord_col = []
299
+ A = []
300
+ for ind, row in enumerate(connectivity.rows):
301
+ A.append(row)
302
+ # We keep only the upper triangular for the moments
303
+ # Generator expressions are faster than arrays on the following
304
+ row = [i for i in row if i < ind]
305
+ coord_row.extend(
306
+ len(row)
307
+ * [
308
+ ind,
309
+ ]
310
+ )
311
+ coord_col.extend(row)
312
+
313
+ coord_row = np.array(coord_row, dtype=np.intp, order="C")
314
+ coord_col = np.array(coord_col, dtype=np.intp, order="C")
315
+
316
+ # build moments as a list
317
+ moments_1 = np.zeros(n_nodes, order="C")
318
+ moments_1[:n_samples] = 1
319
+ moments_2 = np.zeros((n_nodes, n_features), order="C")
320
+ moments_2[:n_samples] = X
321
+ inertia = np.empty(len(coord_row), dtype=np.float64, order="C")
322
+ _hierarchical.compute_ward_dist(moments_1, moments_2, coord_row, coord_col, inertia)
323
+ inertia = list(zip(inertia, coord_row, coord_col))
324
+ heapify(inertia)
325
+
326
+ # prepare the main fields
327
+ parent = np.arange(n_nodes, dtype=np.intp)
328
+ used_node = np.ones(n_nodes, dtype=bool)
329
+ children = []
330
+ if return_distance:
331
+ distances = np.empty(n_nodes - n_samples)
332
+
333
+ not_visited = np.empty(n_nodes, dtype=np.int8, order="C")
334
+
335
+ # recursive merge loop
336
+ for k in range(n_samples, n_nodes):
337
+ # identify the merge
338
+ while True:
339
+ inert, i, j = heappop(inertia)
340
+ if used_node[i] and used_node[j]:
341
+ break
342
+ parent[i], parent[j] = k, k
343
+ children.append((i, j))
344
+ used_node[i] = used_node[j] = False
345
+ if return_distance: # store inertia value
346
+ distances[k - n_samples] = inert
347
+
348
+ # update the moments
349
+ moments_1[k] = moments_1[i] + moments_1[j]
350
+ moments_2[k] = moments_2[i] + moments_2[j]
351
+
352
+ # update the structure matrix A and the inertia matrix
353
+ coord_col = []
354
+ not_visited.fill(1)
355
+ not_visited[k] = 0
356
+ _hierarchical._get_parents(A[i], coord_col, parent, not_visited)
357
+ _hierarchical._get_parents(A[j], coord_col, parent, not_visited)
358
+ # List comprehension is faster than a for loop
359
+ [A[col].append(k) for col in coord_col]
360
+ A.append(coord_col)
361
+ coord_col = np.array(coord_col, dtype=np.intp, order="C")
362
+ coord_row = np.empty(coord_col.shape, dtype=np.intp, order="C")
363
+ coord_row.fill(k)
364
+ n_additions = len(coord_row)
365
+ ini = np.empty(n_additions, dtype=np.float64, order="C")
366
+
367
+ _hierarchical.compute_ward_dist(moments_1, moments_2, coord_row, coord_col, ini)
368
+
369
+ # List comprehension is faster than a for loop
370
+ [heappush(inertia, (ini[idx], k, coord_col[idx])) for idx in range(n_additions)]
371
+
372
+ # Separate leaves in children (empty lists up to now)
373
+ n_leaves = n_samples
374
+ # sort children to get consistent output with unstructured version
375
+ children = [c[::-1] for c in children]
376
+ children = np.array(children) # return numpy array for efficient caching
377
+
378
+ if return_distance:
379
+ # 2 is scaling factor to compare w/ unstructured version
380
+ distances = np.sqrt(2.0 * distances)
381
+ return children, n_connected_components, n_leaves, parent, distances
382
+ else:
383
+ return children, n_connected_components, n_leaves, parent
384
+
385
+
386
+ # single average and complete linkage
387
+ def linkage_tree(
388
+ X,
389
+ connectivity=None,
390
+ n_clusters=None,
391
+ linkage="complete",
392
+ affinity="euclidean",
393
+ return_distance=False,
394
+ ):
395
+ """Linkage agglomerative clustering based on a Feature matrix.
396
+
397
+ The inertia matrix uses a Heapq-based representation.
398
+
399
+ This is the structured version, that takes into account some topological
400
+ structure between samples.
401
+
402
+ Read more in the :ref:`User Guide <hierarchical_clustering>`.
403
+
404
+ Parameters
405
+ ----------
406
+ X : array-like of shape (n_samples, n_features)
407
+ Feature matrix representing `n_samples` samples to be clustered.
408
+
409
+ connectivity : sparse matrix, default=None
410
+ Connectivity matrix. Defines for each sample the neighboring samples
411
+ following a given structure of the data. The matrix is assumed to
412
+ be symmetric and only the upper triangular half is used.
413
+ Default is `None`, i.e, the Ward algorithm is unstructured.
414
+
415
+ n_clusters : int, default=None
416
+ Stop early the construction of the tree at `n_clusters`. This is
417
+ useful to decrease computation time if the number of clusters is
418
+ not small compared to the number of samples. In this case, the
419
+ complete tree is not computed, thus the 'children' output is of
420
+ limited use, and the 'parents' output should rather be used.
421
+ This option is valid only when specifying a connectivity matrix.
422
+
423
+ linkage : {"average", "complete", "single"}, default="complete"
424
+ Which linkage criteria to use. The linkage criterion determines which
425
+ distance to use between sets of observation.
426
+ - "average" uses the average of the distances of each observation of
427
+ the two sets.
428
+ - "complete" or maximum linkage uses the maximum distances between
429
+ all observations of the two sets.
430
+ - "single" uses the minimum of the distances between all
431
+ observations of the two sets.
432
+
433
+ affinity : str or callable, default='euclidean'
434
+ Which metric to use. Can be 'euclidean', 'manhattan', or any
435
+ distance known to paired distance (see metric.pairwise).
436
+
437
+ return_distance : bool, default=False
438
+ Whether or not to return the distances between the clusters.
439
+
440
+ Returns
441
+ -------
442
+ children : ndarray of shape (n_nodes-1, 2)
443
+ The children of each non-leaf node. Values less than `n_samples`
444
+ correspond to leaves of the tree which are the original samples.
445
+ A node `i` greater than or equal to `n_samples` is a non-leaf
446
+ node and has children `children_[i - n_samples]`. Alternatively
447
+ at the i-th iteration, children[i][0] and children[i][1]
448
+ are merged to form node `n_samples + i`.
449
+
450
+ n_connected_components : int
451
+ The number of connected components in the graph.
452
+
453
+ n_leaves : int
454
+ The number of leaves in the tree.
455
+
456
+ parents : ndarray of shape (n_nodes, ) or None
457
+ The parent of each node. Only returned when a connectivity matrix
458
+ is specified, elsewhere 'None' is returned.
459
+
460
+ distances : ndarray of shape (n_nodes-1,)
461
+ Returned when `return_distance` is set to `True`.
462
+
463
+ distances[i] refers to the distance between children[i][0] and
464
+ children[i][1] when they are merged.
465
+
466
+ See Also
467
+ --------
468
+ ward_tree : Hierarchical clustering with ward linkage.
469
+ """
470
+ X = np.asarray(X)
471
+ if X.ndim == 1:
472
+ X = np.reshape(X, (-1, 1))
473
+ n_samples, n_features = X.shape
474
+
475
+ linkage_choices = {
476
+ "complete": _hierarchical.max_merge,
477
+ "average": _hierarchical.average_merge,
478
+ "single": None,
479
+ } # Single linkage is handled differently
480
+ try:
481
+ join_func = linkage_choices[linkage]
482
+ except KeyError as e:
483
+ raise ValueError(
484
+ "Unknown linkage option, linkage should be one of %s, but %s was given"
485
+ % (linkage_choices.keys(), linkage)
486
+ ) from e
487
+
488
+ if affinity == "cosine" and np.any(~np.any(X, axis=1)):
489
+ raise ValueError("Cosine affinity cannot be used when X contains zero vectors")
490
+
491
+ if connectivity is None:
492
+ from scipy.cluster import hierarchy # imports PIL
493
+
494
+ if n_clusters is not None:
495
+ warnings.warn(
496
+ "Partial build of the tree is implemented "
497
+ "only for structured clustering (i.e. with "
498
+ "explicit connectivity). The algorithm "
499
+ "will build the full tree and only "
500
+ "retain the lower branches required "
501
+ "for the specified number of clusters",
502
+ stacklevel=2,
503
+ )
504
+
505
+ if affinity == "precomputed":
506
+ # for the linkage function of hierarchy to work on precomputed
507
+ # data, provide as first argument an ndarray of the shape returned
508
+ # by sklearn.metrics.pairwise_distances.
509
+ if X.shape[0] != X.shape[1]:
510
+ raise ValueError(
511
+ f"Distance matrix should be square, got matrix of shape {X.shape}"
512
+ )
513
+ i, j = np.triu_indices(X.shape[0], k=1)
514
+ X = X[i, j]
515
+ elif affinity == "l2":
516
+ # Translate to something understood by scipy
517
+ affinity = "euclidean"
518
+ elif affinity in ("l1", "manhattan"):
519
+ affinity = "cityblock"
520
+ elif callable(affinity):
521
+ X = affinity(X)
522
+ i, j = np.triu_indices(X.shape[0], k=1)
523
+ X = X[i, j]
524
+ if (
525
+ linkage == "single"
526
+ and affinity != "precomputed"
527
+ and not callable(affinity)
528
+ and affinity in METRIC_MAPPING
529
+ ):
530
+
531
+ # We need the fast cythonized metric from neighbors
532
+ dist_metric = DistanceMetric.get_metric(affinity)
533
+
534
+ # The Cython routines used require contiguous arrays
535
+ X = np.ascontiguousarray(X, dtype=np.double)
536
+
537
+ mst = _hierarchical.mst_linkage_core(X, dist_metric)
538
+ # Sort edges of the min_spanning_tree by weight
539
+ mst = mst[np.argsort(mst.T[2], kind="mergesort"), :]
540
+
541
+ # Convert edge list into standard hierarchical clustering format
542
+ out = _hierarchical.single_linkage_label(mst)
543
+ else:
544
+ out = hierarchy.linkage(X, method=linkage, metric=affinity)
545
+ children_ = out[:, :2].astype(int, copy=False)
546
+
547
+ if return_distance:
548
+ distances = out[:, 2]
549
+ return children_, 1, n_samples, None, distances
550
+ return children_, 1, n_samples, None
551
+
552
+ connectivity, n_connected_components = _fix_connectivity(
553
+ X, connectivity, affinity=affinity
554
+ )
555
+ connectivity = connectivity.tocoo()
556
+ # Put the diagonal to zero
557
+ diag_mask = connectivity.row != connectivity.col
558
+ connectivity.row = connectivity.row[diag_mask]
559
+ connectivity.col = connectivity.col[diag_mask]
560
+ connectivity.data = connectivity.data[diag_mask]
561
+ del diag_mask
562
+
563
+ if affinity == "precomputed":
564
+ distances = X[connectivity.row, connectivity.col].astype(np.float64, copy=False)
565
+ else:
566
+ # FIXME We compute all the distances, while we could have only computed
567
+ # the "interesting" distances
568
+ distances = paired_distances(
569
+ X[connectivity.row], X[connectivity.col], metric=affinity
570
+ )
571
+ connectivity.data = distances
572
+
573
+ if n_clusters is None:
574
+ n_nodes = 2 * n_samples - 1
575
+ else:
576
+ assert n_clusters <= n_samples
577
+ n_nodes = 2 * n_samples - n_clusters
578
+
579
+ if linkage == "single":
580
+ return _single_linkage_tree(
581
+ connectivity,
582
+ n_samples,
583
+ n_nodes,
584
+ n_clusters,
585
+ n_connected_components,
586
+ return_distance,
587
+ )
588
+
589
+ if return_distance:
590
+ distances = np.empty(n_nodes - n_samples)
591
+ # create inertia heap and connection matrix
592
+ A = np.empty(n_nodes, dtype=object)
593
+ inertia = list()
594
+
595
+ # LIL seems to the best format to access the rows quickly,
596
+ # without the numpy overhead of slicing CSR indices and data.
597
+ connectivity = connectivity.tolil()
598
+ # We are storing the graph in a list of IntFloatDict
599
+ for ind, (data, row) in enumerate(zip(connectivity.data, connectivity.rows)):
600
+ A[ind] = IntFloatDict(
601
+ np.asarray(row, dtype=np.intp), np.asarray(data, dtype=np.float64)
602
+ )
603
+ # We keep only the upper triangular for the heap
604
+ # Generator expressions are faster than arrays on the following
605
+ inertia.extend(
606
+ _hierarchical.WeightedEdge(d, ind, r) for r, d in zip(row, data) if r < ind
607
+ )
608
+ del connectivity
609
+
610
+ heapify(inertia)
611
+
612
+ # prepare the main fields
613
+ parent = np.arange(n_nodes, dtype=np.intp)
614
+ used_node = np.ones(n_nodes, dtype=np.intp)
615
+ children = []
616
+
617
+ # recursive merge loop
618
+ for k in range(n_samples, n_nodes):
619
+ # identify the merge
620
+ while True:
621
+ edge = heappop(inertia)
622
+ if used_node[edge.a] and used_node[edge.b]:
623
+ break
624
+ i = edge.a
625
+ j = edge.b
626
+
627
+ if return_distance:
628
+ # store distances
629
+ distances[k - n_samples] = edge.weight
630
+
631
+ parent[i] = parent[j] = k
632
+ children.append((i, j))
633
+ # Keep track of the number of elements per cluster
634
+ n_i = used_node[i]
635
+ n_j = used_node[j]
636
+ used_node[k] = n_i + n_j
637
+ used_node[i] = used_node[j] = False
638
+
639
+ # update the structure matrix A and the inertia matrix
640
+ # a clever 'min', or 'max' operation between A[i] and A[j]
641
+ coord_col = join_func(A[i], A[j], used_node, n_i, n_j)
642
+ for col, d in coord_col:
643
+ A[col].append(k, d)
644
+ # Here we use the information from coord_col (containing the
645
+ # distances) to update the heap
646
+ heappush(inertia, _hierarchical.WeightedEdge(d, k, col))
647
+ A[k] = coord_col
648
+ # Clear A[i] and A[j] to save memory
649
+ A[i] = A[j] = 0
650
+
651
+ # Separate leaves in children (empty lists up to now)
652
+ n_leaves = n_samples
653
+
654
+ # # return numpy array for efficient caching
655
+ children = np.array(children)[:, ::-1]
656
+
657
+ if return_distance:
658
+ return children, n_connected_components, n_leaves, parent, distances
659
+ return children, n_connected_components, n_leaves, parent
660
+
661
+
662
+ # Matching names to tree-building strategies
663
+ def _complete_linkage(*args, **kwargs):
664
+ kwargs["linkage"] = "complete"
665
+ return linkage_tree(*args, **kwargs)
666
+
667
+
668
+ def _average_linkage(*args, **kwargs):
669
+ kwargs["linkage"] = "average"
670
+ return linkage_tree(*args, **kwargs)
671
+
672
+
673
+ def _single_linkage(*args, **kwargs):
674
+ kwargs["linkage"] = "single"
675
+ return linkage_tree(*args, **kwargs)
676
+
677
+
678
+ _TREE_BUILDERS = dict(
679
+ ward=ward_tree,
680
+ complete=_complete_linkage,
681
+ average=_average_linkage,
682
+ single=_single_linkage,
683
+ )
684
+
685
+ ###############################################################################
686
+ # Functions for cutting hierarchical clustering tree
687
+
688
+
689
+ def _hc_cut(n_clusters, children, n_leaves):
690
+ """Function cutting the ward tree for a given number of clusters.
691
+
692
+ Parameters
693
+ ----------
694
+ n_clusters : int or ndarray
695
+ The number of clusters to form.
696
+
697
+ children : ndarray of shape (n_nodes-1, 2)
698
+ The children of each non-leaf node. Values less than `n_samples`
699
+ correspond to leaves of the tree which are the original samples.
700
+ A node `i` greater than or equal to `n_samples` is a non-leaf
701
+ node and has children `children_[i - n_samples]`. Alternatively
702
+ at the i-th iteration, children[i][0] and children[i][1]
703
+ are merged to form node `n_samples + i`.
704
+
705
+ n_leaves : int
706
+ Number of leaves of the tree.
707
+
708
+ Returns
709
+ -------
710
+ labels : array [n_samples]
711
+ Cluster labels for each point.
712
+ """
713
+ if n_clusters > n_leaves:
714
+ raise ValueError(
715
+ "Cannot extract more clusters than samples: "
716
+ "%s clusters where given for a tree with %s leaves."
717
+ % (n_clusters, n_leaves)
718
+ )
719
+ # In this function, we store nodes as a heap to avoid recomputing
720
+ # the max of the nodes: the first element is always the smallest
721
+ # We use negated indices as heaps work on smallest elements, and we
722
+ # are interested in largest elements
723
+ # children[-1] is the root of the tree
724
+ nodes = [-(max(children[-1]) + 1)]
725
+ for _ in range(n_clusters - 1):
726
+ # As we have a heap, nodes[0] is the smallest element
727
+ these_children = children[-nodes[0] - n_leaves]
728
+ # Insert the 2 children and remove the largest node
729
+ heappush(nodes, -these_children[0])
730
+ heappushpop(nodes, -these_children[1])
731
+ label = np.zeros(n_leaves, dtype=np.intp)
732
+ for i, node in enumerate(nodes):
733
+ label[_hierarchical._hc_get_descendent(-node, children, n_leaves)] = i
734
+ return label
735
+
736
+
737
+ ###############################################################################
738
+
739
+
740
+ class AgglomerativeClustering(ClusterMixin, BaseEstimator):
741
+ """
742
+ Agglomerative Clustering.
743
+
744
+ Recursively merges pair of clusters of sample data; uses linkage distance.
745
+
746
+ Read more in the :ref:`User Guide <hierarchical_clustering>`.
747
+
748
+ Parameters
749
+ ----------
750
+ n_clusters : int or None, default=2
751
+ The number of clusters to find. It must be ``None`` if
752
+ ``distance_threshold`` is not ``None``.
753
+
754
+ affinity : str or callable, default='euclidean'
755
+ The metric to use when calculating distance between instances in a
756
+ feature array. If metric is a string or callable, it must be one of
757
+ the options allowed by :func:`sklearn.metrics.pairwise_distances` for
758
+ its metric parameter.
759
+ If linkage is "ward", only "euclidean" is accepted.
760
+ If "precomputed", a distance matrix (instead of a similarity matrix)
761
+ is needed as input for the fit method.
762
+
763
+ .. deprecated:: 1.2
764
+ `affinity` was deprecated in version 1.2 and will be renamed to
765
+ `metric` in 1.4.
766
+
767
+ metric : str or callable, default=None
768
+ Metric used to compute the linkage. Can be "euclidean", "l1", "l2",
769
+ "manhattan", "cosine", or "precomputed". If set to `None` then
770
+ "euclidean" is used. If linkage is "ward", only "euclidean" is
771
+ accepted. If "precomputed", a distance matrix is needed as input for
772
+ the fit method.
773
+
774
+ .. versionadded:: 1.2
775
+
776
+ memory : str or object with the joblib.Memory interface, default=None
777
+ Used to cache the output of the computation of the tree.
778
+ By default, no caching is done. If a string is given, it is the
779
+ path to the caching directory.
780
+
781
+ connectivity : array-like or callable, default=None
782
+ Connectivity matrix. Defines for each sample the neighboring
783
+ samples following a given structure of the data.
784
+ This can be a connectivity matrix itself or a callable that transforms
785
+ the data into a connectivity matrix, such as derived from
786
+ `kneighbors_graph`. Default is ``None``, i.e, the
787
+ hierarchical clustering algorithm is unstructured.
788
+
789
+ compute_full_tree : 'auto' or bool, default='auto'
790
+ Stop early the construction of the tree at ``n_clusters``. This is
791
+ useful to decrease computation time if the number of clusters is not
792
+ small compared to the number of samples. This option is useful only
793
+ when specifying a connectivity matrix. Note also that when varying the
794
+ number of clusters and using caching, it may be advantageous to compute
795
+ the full tree. It must be ``True`` if ``distance_threshold`` is not
796
+ ``None``. By default `compute_full_tree` is "auto", which is equivalent
797
+ to `True` when `distance_threshold` is not `None` or that `n_clusters`
798
+ is inferior to the maximum between 100 or `0.02 * n_samples`.
799
+ Otherwise, "auto" is equivalent to `False`.
800
+
801
+ linkage : {'ward', 'complete', 'average', 'single'}, default='ward'
802
+ Which linkage criterion to use. The linkage criterion determines which
803
+ distance to use between sets of observation. The algorithm will merge
804
+ the pairs of cluster that minimize this criterion.
805
+
806
+ - 'ward' minimizes the variance of the clusters being merged.
807
+ - 'average' uses the average of the distances of each observation of
808
+ the two sets.
809
+ - 'complete' or 'maximum' linkage uses the maximum distances between
810
+ all observations of the two sets.
811
+ - 'single' uses the minimum of the distances between all observations
812
+ of the two sets.
813
+
814
+ .. versionadded:: 0.20
815
+ Added the 'single' option
816
+
817
+ distance_threshold : float, default=None
818
+ The linkage distance threshold at or above which clusters will not be
819
+ merged. If not ``None``, ``n_clusters`` must be ``None`` and
820
+ ``compute_full_tree`` must be ``True``.
821
+
822
+ .. versionadded:: 0.21
823
+
824
+ compute_distances : bool, default=False
825
+ Computes distances between clusters even if `distance_threshold` is not
826
+ used. This can be used to make dendrogram visualization, but introduces
827
+ a computational and memory overhead.
828
+
829
+ .. versionadded:: 0.24
830
+
831
+ Attributes
832
+ ----------
833
+ n_clusters_ : int
834
+ The number of clusters found by the algorithm. If
835
+ ``distance_threshold=None``, it will be equal to the given
836
+ ``n_clusters``.
837
+
838
+ labels_ : ndarray of shape (n_samples)
839
+ Cluster labels for each point.
840
+
841
+ n_leaves_ : int
842
+ Number of leaves in the hierarchical tree.
843
+
844
+ n_connected_components_ : int
845
+ The estimated number of connected components in the graph.
846
+
847
+ .. versionadded:: 0.21
848
+ ``n_connected_components_`` was added to replace ``n_components_``.
849
+
850
+ n_features_in_ : int
851
+ Number of features seen during :term:`fit`.
852
+
853
+ .. versionadded:: 0.24
854
+
855
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
856
+ Names of features seen during :term:`fit`. Defined only when `X`
857
+ has feature names that are all strings.
858
+
859
+ .. versionadded:: 1.0
860
+
861
+ children_ : array-like of shape (n_samples-1, 2)
862
+ The children of each non-leaf node. Values less than `n_samples`
863
+ correspond to leaves of the tree which are the original samples.
864
+ A node `i` greater than or equal to `n_samples` is a non-leaf
865
+ node and has children `children_[i - n_samples]`. Alternatively
866
+ at the i-th iteration, children[i][0] and children[i][1]
867
+ are merged to form node `n_samples + i`.
868
+
869
+ distances_ : array-like of shape (n_nodes-1,)
870
+ Distances between nodes in the corresponding place in `children_`.
871
+ Only computed if `distance_threshold` is used or `compute_distances`
872
+ is set to `True`.
873
+
874
+ See Also
875
+ --------
876
+ FeatureAgglomeration : Agglomerative clustering but for features instead of
877
+ samples.
878
+ ward_tree : Hierarchical clustering with ward linkage.
879
+
880
+ Examples
881
+ --------
882
+ >>> from sklearn.cluster import AgglomerativeClustering
883
+ >>> import numpy as np
884
+ >>> X = np.array([[1, 2], [1, 4], [1, 0],
885
+ ... [4, 2], [4, 4], [4, 0]])
886
+ >>> clustering = AgglomerativeClustering().fit(X)
887
+ >>> clustering
888
+ AgglomerativeClustering()
889
+ >>> clustering.labels_
890
+ array([1, 1, 1, 0, 0, 0])
891
+ """
892
+
893
+ _parameter_constraints: dict = {
894
+ "n_clusters": [Interval(Integral, 1, None, closed="left"), None],
895
+ "affinity": [
896
+ Hidden(StrOptions({"deprecated"})),
897
+ StrOptions(set(_VALID_METRICS) | {"precomputed"}),
898
+ callable,
899
+ ],
900
+ "metric": [
901
+ StrOptions(set(_VALID_METRICS) | {"precomputed"}),
902
+ callable,
903
+ None,
904
+ ],
905
+ "memory": [str, HasMethods("cache"), None],
906
+ "connectivity": ["array-like", callable, None],
907
+ "compute_full_tree": [StrOptions({"auto"}), "boolean"],
908
+ "linkage": [StrOptions(set(_TREE_BUILDERS.keys()))],
909
+ "distance_threshold": [Interval(Real, 0, None, closed="left"), None],
910
+ "compute_distances": ["boolean"],
911
+ }
912
+
913
+ def __init__(
914
+ self,
915
+ n_clusters=2,
916
+ *,
917
+ affinity="deprecated", # TODO(1.4): Remove
918
+ metric=None, # TODO(1.4): Set to "euclidean"
919
+ memory=None,
920
+ connectivity=None,
921
+ compute_full_tree="auto",
922
+ linkage="ward",
923
+ distance_threshold=None,
924
+ compute_distances=False,
925
+ ):
926
+ self.n_clusters = n_clusters
927
+ self.distance_threshold = distance_threshold
928
+ self.memory = memory
929
+ self.connectivity = connectivity
930
+ self.compute_full_tree = compute_full_tree
931
+ self.linkage = linkage
932
+ self.affinity = affinity
933
+ self.metric = metric
934
+ self.compute_distances = compute_distances
935
+
936
+ def fit(self, X, y=None):
937
+ """Fit the hierarchical clustering from features, or distance matrix.
938
+
939
+ Parameters
940
+ ----------
941
+ X : array-like, shape (n_samples, n_features) or \
942
+ (n_samples, n_samples)
943
+ Training instances to cluster, or distances between instances if
944
+ ``metric='precomputed'``.
945
+
946
+ y : Ignored
947
+ Not used, present here for API consistency by convention.
948
+
949
+ Returns
950
+ -------
951
+ self : object
952
+ Returns the fitted instance.
953
+ """
954
+ self._validate_params()
955
+ X = self._validate_data(X, ensure_min_samples=2)
956
+ return self._fit(X)
957
+
958
+ def _fit(self, X):
959
+ """Fit without validation
960
+
961
+ Parameters
962
+ ----------
963
+ X : ndarray of shape (n_samples, n_features) or (n_samples, n_samples)
964
+ Training instances to cluster, or distances between instances if
965
+ ``affinity='precomputed'``.
966
+
967
+ Returns
968
+ -------
969
+ self : object
970
+ Returns the fitted instance.
971
+ """
972
+ memory = check_memory(self.memory)
973
+
974
+ self._metric = self.metric
975
+ # TODO(1.4): Remove
976
+ if self.affinity != "deprecated":
977
+ if self.metric is not None:
978
+ raise ValueError(
979
+ "Both `affinity` and `metric` attributes were set. Attribute"
980
+ " `affinity` was deprecated in version 1.2 and will be removed in"
981
+ " 1.4. To avoid this error, only set the `metric` attribute."
982
+ )
983
+ warnings.warn(
984
+ "Attribute `affinity` was deprecated in version 1.2 and will be removed"
985
+ " in 1.4. Use `metric` instead",
986
+ FutureWarning,
987
+ )
988
+ self._metric = self.affinity
989
+ elif self.metric is None:
990
+ self._metric = "euclidean"
991
+
992
+ if not ((self.n_clusters is None) ^ (self.distance_threshold is None)):
993
+ raise ValueError(
994
+ "Exactly one of n_clusters and "
995
+ "distance_threshold has to be set, and the other "
996
+ "needs to be None."
997
+ )
998
+
999
+ if self.distance_threshold is not None and not self.compute_full_tree:
1000
+ raise ValueError(
1001
+ "compute_full_tree must be True if distance_threshold is set."
1002
+ )
1003
+
1004
+ if self.linkage == "ward" and self._metric != "euclidean":
1005
+ raise ValueError(
1006
+ f"{self._metric} was provided as metric. Ward can only "
1007
+ "work with euclidean distances."
1008
+ )
1009
+
1010
+ tree_builder = _TREE_BUILDERS[self.linkage]
1011
+
1012
+ connectivity = self.connectivity
1013
+ if self.connectivity is not None:
1014
+ if callable(self.connectivity):
1015
+ connectivity = self.connectivity(X)
1016
+ connectivity = check_array(
1017
+ connectivity, accept_sparse=["csr", "coo", "lil"]
1018
+ )
1019
+
1020
+ n_samples = len(X)
1021
+ compute_full_tree = self.compute_full_tree
1022
+ if self.connectivity is None:
1023
+ compute_full_tree = True
1024
+ if compute_full_tree == "auto":
1025
+ if self.distance_threshold is not None:
1026
+ compute_full_tree = True
1027
+ else:
1028
+ # Early stopping is likely to give a speed up only for
1029
+ # a large number of clusters. The actual threshold
1030
+ # implemented here is heuristic
1031
+ compute_full_tree = self.n_clusters < max(100, 0.02 * n_samples)
1032
+ n_clusters = self.n_clusters
1033
+ if compute_full_tree:
1034
+ n_clusters = None
1035
+
1036
+ # Construct the tree
1037
+ kwargs = {}
1038
+ if self.linkage != "ward":
1039
+ kwargs["linkage"] = self.linkage
1040
+ kwargs["affinity"] = self._metric
1041
+
1042
+ distance_threshold = self.distance_threshold
1043
+
1044
+ return_distance = (distance_threshold is not None) or self.compute_distances
1045
+
1046
+ out = memory.cache(tree_builder)(
1047
+ X,
1048
+ connectivity=connectivity,
1049
+ n_clusters=n_clusters,
1050
+ return_distance=return_distance,
1051
+ **kwargs,
1052
+ )
1053
+ (self.children_, self.n_connected_components_, self.n_leaves_, parents) = out[
1054
+ :4
1055
+ ]
1056
+
1057
+ if return_distance:
1058
+ self.distances_ = out[-1]
1059
+
1060
+ if self.distance_threshold is not None: # distance_threshold is used
1061
+ self.n_clusters_ = (
1062
+ np.count_nonzero(self.distances_ >= distance_threshold) + 1
1063
+ )
1064
+ else: # n_clusters is used
1065
+ self.n_clusters_ = self.n_clusters
1066
+
1067
+ # Cut the tree
1068
+ if compute_full_tree:
1069
+ self.labels_ = _hc_cut(self.n_clusters_, self.children_, self.n_leaves_)
1070
+ else:
1071
+ labels = _hierarchical.hc_get_heads(parents, copy=False)
1072
+ # copy to avoid holding a reference on the original array
1073
+ labels = np.copy(labels[:n_samples])
1074
+ # Reassign cluster numbers
1075
+ self.labels_ = np.searchsorted(np.unique(labels), labels)
1076
+ return self
1077
+
1078
+ def fit_predict(self, X, y=None):
1079
+ """Fit and return the result of each sample's clustering assignment.
1080
+
1081
+ In addition to fitting, this method also return the result of the
1082
+ clustering assignment for each sample in the training set.
1083
+
1084
+ Parameters
1085
+ ----------
1086
+ X : array-like of shape (n_samples, n_features) or \
1087
+ (n_samples, n_samples)
1088
+ Training instances to cluster, or distances between instances if
1089
+ ``affinity='precomputed'``.
1090
+
1091
+ y : Ignored
1092
+ Not used, present here for API consistency by convention.
1093
+
1094
+ Returns
1095
+ -------
1096
+ labels : ndarray of shape (n_samples,)
1097
+ Cluster labels.
1098
+ """
1099
+ return super().fit_predict(X, y)
1100
+
1101
+
1102
+ class FeatureAgglomeration(
1103
+ ClassNamePrefixFeaturesOutMixin, AgglomerativeClustering, AgglomerationTransform
1104
+ ):
1105
+ """Agglomerate features.
1106
+
1107
+ Recursively merges pair of clusters of features.
1108
+
1109
+ Read more in the :ref:`User Guide <hierarchical_clustering>`.
1110
+
1111
+ Parameters
1112
+ ----------
1113
+ n_clusters : int or None, default=2
1114
+ The number of clusters to find. It must be ``None`` if
1115
+ ``distance_threshold`` is not ``None``.
1116
+
1117
+ affinity : str or callable, default='euclidean'
1118
+ The metric to use when calculating distance between instances in a
1119
+ feature array. If metric is a string or callable, it must be one of
1120
+ the options allowed by :func:`sklearn.metrics.pairwise_distances` for
1121
+ its metric parameter.
1122
+ If linkage is "ward", only "euclidean" is accepted.
1123
+ If "precomputed", a distance matrix (instead of a similarity matrix)
1124
+ is needed as input for the fit method.
1125
+
1126
+ .. deprecated:: 1.2
1127
+ `affinity` was deprecated in version 1.2 and will be renamed to
1128
+ `metric` in 1.4.
1129
+
1130
+ metric : str or callable, default=None
1131
+ Metric used to compute the linkage. Can be "euclidean", "l1", "l2",
1132
+ "manhattan", "cosine", or "precomputed". If set to `None` then
1133
+ "euclidean" is used. If linkage is "ward", only "euclidean" is
1134
+ accepted. If "precomputed", a distance matrix is needed as input for
1135
+ the fit method.
1136
+
1137
+ .. versionadded:: 1.2
1138
+
1139
+ memory : str or object with the joblib.Memory interface, default=None
1140
+ Used to cache the output of the computation of the tree.
1141
+ By default, no caching is done. If a string is given, it is the
1142
+ path to the caching directory.
1143
+
1144
+ connectivity : array-like or callable, default=None
1145
+ Connectivity matrix. Defines for each feature the neighboring
1146
+ features following a given structure of the data.
1147
+ This can be a connectivity matrix itself or a callable that transforms
1148
+ the data into a connectivity matrix, such as derived from
1149
+ `kneighbors_graph`. Default is `None`, i.e, the
1150
+ hierarchical clustering algorithm is unstructured.
1151
+
1152
+ compute_full_tree : 'auto' or bool, default='auto'
1153
+ Stop early the construction of the tree at `n_clusters`. This is useful
1154
+ to decrease computation time if the number of clusters is not small
1155
+ compared to the number of features. This option is useful only when
1156
+ specifying a connectivity matrix. Note also that when varying the
1157
+ number of clusters and using caching, it may be advantageous to compute
1158
+ the full tree. It must be ``True`` if ``distance_threshold`` is not
1159
+ ``None``. By default `compute_full_tree` is "auto", which is equivalent
1160
+ to `True` when `distance_threshold` is not `None` or that `n_clusters`
1161
+ is inferior to the maximum between 100 or `0.02 * n_samples`.
1162
+ Otherwise, "auto" is equivalent to `False`.
1163
+
1164
+ linkage : {"ward", "complete", "average", "single"}, default="ward"
1165
+ Which linkage criterion to use. The linkage criterion determines which
1166
+ distance to use between sets of features. The algorithm will merge
1167
+ the pairs of cluster that minimize this criterion.
1168
+
1169
+ - "ward" minimizes the variance of the clusters being merged.
1170
+ - "complete" or maximum linkage uses the maximum distances between
1171
+ all features of the two sets.
1172
+ - "average" uses the average of the distances of each feature of
1173
+ the two sets.
1174
+ - "single" uses the minimum of the distances between all features
1175
+ of the two sets.
1176
+
1177
+ pooling_func : callable, default=np.mean
1178
+ This combines the values of agglomerated features into a single
1179
+ value, and should accept an array of shape [M, N] and the keyword
1180
+ argument `axis=1`, and reduce it to an array of size [M].
1181
+
1182
+ distance_threshold : float, default=None
1183
+ The linkage distance threshold at or above which clusters will not be
1184
+ merged. If not ``None``, ``n_clusters`` must be ``None`` and
1185
+ ``compute_full_tree`` must be ``True``.
1186
+
1187
+ .. versionadded:: 0.21
1188
+
1189
+ compute_distances : bool, default=False
1190
+ Computes distances between clusters even if `distance_threshold` is not
1191
+ used. This can be used to make dendrogram visualization, but introduces
1192
+ a computational and memory overhead.
1193
+
1194
+ .. versionadded:: 0.24
1195
+
1196
+ Attributes
1197
+ ----------
1198
+ n_clusters_ : int
1199
+ The number of clusters found by the algorithm. If
1200
+ ``distance_threshold=None``, it will be equal to the given
1201
+ ``n_clusters``.
1202
+
1203
+ labels_ : array-like of (n_features,)
1204
+ Cluster labels for each feature.
1205
+
1206
+ n_leaves_ : int
1207
+ Number of leaves in the hierarchical tree.
1208
+
1209
+ n_connected_components_ : int
1210
+ The estimated number of connected components in the graph.
1211
+
1212
+ .. versionadded:: 0.21
1213
+ ``n_connected_components_`` was added to replace ``n_components_``.
1214
+
1215
+ n_features_in_ : int
1216
+ Number of features seen during :term:`fit`.
1217
+
1218
+ .. versionadded:: 0.24
1219
+
1220
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
1221
+ Names of features seen during :term:`fit`. Defined only when `X`
1222
+ has feature names that are all strings.
1223
+
1224
+ .. versionadded:: 1.0
1225
+
1226
+ children_ : array-like of shape (n_nodes-1, 2)
1227
+ The children of each non-leaf node. Values less than `n_features`
1228
+ correspond to leaves of the tree which are the original samples.
1229
+ A node `i` greater than or equal to `n_features` is a non-leaf
1230
+ node and has children `children_[i - n_features]`. Alternatively
1231
+ at the i-th iteration, children[i][0] and children[i][1]
1232
+ are merged to form node `n_features + i`.
1233
+
1234
+ distances_ : array-like of shape (n_nodes-1,)
1235
+ Distances between nodes in the corresponding place in `children_`.
1236
+ Only computed if `distance_threshold` is used or `compute_distances`
1237
+ is set to `True`.
1238
+
1239
+ See Also
1240
+ --------
1241
+ AgglomerativeClustering : Agglomerative clustering samples instead of
1242
+ features.
1243
+ ward_tree : Hierarchical clustering with ward linkage.
1244
+
1245
+ Examples
1246
+ --------
1247
+ >>> import numpy as np
1248
+ >>> from sklearn import datasets, cluster
1249
+ >>> digits = datasets.load_digits()
1250
+ >>> images = digits.images
1251
+ >>> X = np.reshape(images, (len(images), -1))
1252
+ >>> agglo = cluster.FeatureAgglomeration(n_clusters=32)
1253
+ >>> agglo.fit(X)
1254
+ FeatureAgglomeration(n_clusters=32)
1255
+ >>> X_reduced = agglo.transform(X)
1256
+ >>> X_reduced.shape
1257
+ (1797, 32)
1258
+ """
1259
+
1260
+ _parameter_constraints: dict = {
1261
+ "n_clusters": [Interval(Integral, 1, None, closed="left"), None],
1262
+ "affinity": [
1263
+ Hidden(StrOptions({"deprecated"})),
1264
+ StrOptions(set(_VALID_METRICS) | {"precomputed"}),
1265
+ callable,
1266
+ ],
1267
+ "metric": [
1268
+ StrOptions(set(_VALID_METRICS) | {"precomputed"}),
1269
+ callable,
1270
+ None,
1271
+ ],
1272
+ "memory": [str, HasMethods("cache"), None],
1273
+ "connectivity": ["array-like", callable, None],
1274
+ "compute_full_tree": [StrOptions({"auto"}), "boolean"],
1275
+ "linkage": [StrOptions(set(_TREE_BUILDERS.keys()))],
1276
+ "pooling_func": [callable],
1277
+ "distance_threshold": [Interval(Real, 0, None, closed="left"), None],
1278
+ "compute_distances": ["boolean"],
1279
+ }
1280
+
1281
+ def __init__(
1282
+ self,
1283
+ n_clusters=2,
1284
+ *,
1285
+ affinity="deprecated", # TODO(1.4): Remove
1286
+ metric=None, # TODO(1.4): Set to "euclidean"
1287
+ memory=None,
1288
+ connectivity=None,
1289
+ compute_full_tree="auto",
1290
+ linkage="ward",
1291
+ pooling_func=np.mean,
1292
+ distance_threshold=None,
1293
+ compute_distances=False,
1294
+ ):
1295
+ super().__init__(
1296
+ n_clusters=n_clusters,
1297
+ memory=memory,
1298
+ connectivity=connectivity,
1299
+ compute_full_tree=compute_full_tree,
1300
+ linkage=linkage,
1301
+ affinity=affinity,
1302
+ metric=metric,
1303
+ distance_threshold=distance_threshold,
1304
+ compute_distances=compute_distances,
1305
+ )
1306
+ self.pooling_func = pooling_func
1307
+
1308
+ def fit(self, X, y=None):
1309
+ """Fit the hierarchical clustering on the data.
1310
+
1311
+ Parameters
1312
+ ----------
1313
+ X : array-like of shape (n_samples, n_features)
1314
+ The data.
1315
+
1316
+ y : Ignored
1317
+ Not used, present here for API consistency by convention.
1318
+
1319
+ Returns
1320
+ -------
1321
+ self : object
1322
+ Returns the transformer.
1323
+ """
1324
+ self._validate_params()
1325
+ X = self._validate_data(X, ensure_min_features=2)
1326
+ super()._fit(X.T)
1327
+ self._n_features_out = self.n_clusters_
1328
+ return self
1329
+
1330
+ @property
1331
+ def fit_predict(self):
1332
+ """Fit and return the result of each sample's clustering assignment."""
1333
+ raise AttributeError
videollama2/lib/python3.10/site-packages/sklearn/cluster/_bicluster.py ADDED
@@ -0,0 +1,628 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spectral biclustering algorithms."""
2
+ # Authors : Kemal Eren
3
+ # License: BSD 3 clause
4
+
5
+ from abc import ABCMeta, abstractmethod
6
+
7
+ import numpy as np
8
+ from numbers import Integral
9
+
10
+ from scipy.linalg import norm
11
+ from scipy.sparse import dia_matrix, issparse
12
+ from scipy.sparse.linalg import eigsh, svds
13
+
14
+ from . import KMeans, MiniBatchKMeans
15
+ from ..base import BaseEstimator, BiclusterMixin
16
+ from ..utils import check_random_state
17
+ from ..utils import check_scalar
18
+
19
+ from ..utils.extmath import make_nonnegative, randomized_svd, safe_sparse_dot
20
+
21
+ from ..utils.validation import assert_all_finite
22
+ from ..utils._param_validation import Interval, StrOptions
23
+
24
+
25
+ __all__ = ["SpectralCoclustering", "SpectralBiclustering"]
26
+
27
+
28
+ def _scale_normalize(X):
29
+ """Normalize ``X`` by scaling rows and columns independently.
30
+
31
+ Returns the normalized matrix and the row and column scaling
32
+ factors.
33
+ """
34
+ X = make_nonnegative(X)
35
+ row_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=1))).squeeze()
36
+ col_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=0))).squeeze()
37
+ row_diag = np.where(np.isnan(row_diag), 0, row_diag)
38
+ col_diag = np.where(np.isnan(col_diag), 0, col_diag)
39
+ if issparse(X):
40
+ n_rows, n_cols = X.shape
41
+ r = dia_matrix((row_diag, [0]), shape=(n_rows, n_rows))
42
+ c = dia_matrix((col_diag, [0]), shape=(n_cols, n_cols))
43
+ an = r * X * c
44
+ else:
45
+ an = row_diag[:, np.newaxis] * X * col_diag
46
+ return an, row_diag, col_diag
47
+
48
+
49
+ def _bistochastic_normalize(X, max_iter=1000, tol=1e-5):
50
+ """Normalize rows and columns of ``X`` simultaneously so that all
51
+ rows sum to one constant and all columns sum to a different
52
+ constant.
53
+ """
54
+ # According to paper, this can also be done more efficiently with
55
+ # deviation reduction and balancing algorithms.
56
+ X = make_nonnegative(X)
57
+ X_scaled = X
58
+ for _ in range(max_iter):
59
+ X_new, _, _ = _scale_normalize(X_scaled)
60
+ if issparse(X):
61
+ dist = norm(X_scaled.data - X.data)
62
+ else:
63
+ dist = norm(X_scaled - X_new)
64
+ X_scaled = X_new
65
+ if dist is not None and dist < tol:
66
+ break
67
+ return X_scaled
68
+
69
+
70
+ def _log_normalize(X):
71
+ """Normalize ``X`` according to Kluger's log-interactions scheme."""
72
+ X = make_nonnegative(X, min_value=1)
73
+ if issparse(X):
74
+ raise ValueError(
75
+ "Cannot compute log of a sparse matrix,"
76
+ " because log(x) diverges to -infinity as x"
77
+ " goes to 0."
78
+ )
79
+ L = np.log(X)
80
+ row_avg = L.mean(axis=1)[:, np.newaxis]
81
+ col_avg = L.mean(axis=0)
82
+ avg = L.mean()
83
+ return L - row_avg - col_avg + avg
84
+
85
+
86
+ class BaseSpectral(BiclusterMixin, BaseEstimator, metaclass=ABCMeta):
87
+ """Base class for spectral biclustering."""
88
+
89
+ _parameter_constraints: dict = {
90
+ "svd_method": [StrOptions({"randomized", "arpack"})],
91
+ "n_svd_vecs": [Interval(Integral, 0, None, closed="left"), None],
92
+ "mini_batch": ["boolean"],
93
+ "init": [StrOptions({"k-means++", "random"}), np.ndarray],
94
+ "n_init": [Interval(Integral, 1, None, closed="left")],
95
+ "random_state": ["random_state"],
96
+ }
97
+
98
+ @abstractmethod
99
+ def __init__(
100
+ self,
101
+ n_clusters=3,
102
+ svd_method="randomized",
103
+ n_svd_vecs=None,
104
+ mini_batch=False,
105
+ init="k-means++",
106
+ n_init=10,
107
+ random_state=None,
108
+ ):
109
+ self.n_clusters = n_clusters
110
+ self.svd_method = svd_method
111
+ self.n_svd_vecs = n_svd_vecs
112
+ self.mini_batch = mini_batch
113
+ self.init = init
114
+ self.n_init = n_init
115
+ self.random_state = random_state
116
+
117
+ @abstractmethod
118
+ def _check_parameters(self, n_samples):
119
+ """Validate parameters depending on the input data."""
120
+
121
+ def fit(self, X, y=None):
122
+ """Create a biclustering for X.
123
+
124
+ Parameters
125
+ ----------
126
+ X : array-like of shape (n_samples, n_features)
127
+ Training data.
128
+
129
+ y : Ignored
130
+ Not used, present for API consistency by convention.
131
+
132
+ Returns
133
+ -------
134
+ self : object
135
+ SpectralBiclustering instance.
136
+ """
137
+ self._validate_params()
138
+
139
+ X = self._validate_data(X, accept_sparse="csr", dtype=np.float64)
140
+ self._check_parameters(X.shape[0])
141
+ self._fit(X)
142
+ return self
143
+
144
+ def _svd(self, array, n_components, n_discard):
145
+ """Returns first `n_components` left and right singular
146
+ vectors u and v, discarding the first `n_discard`.
147
+ """
148
+ if self.svd_method == "randomized":
149
+ kwargs = {}
150
+ if self.n_svd_vecs is not None:
151
+ kwargs["n_oversamples"] = self.n_svd_vecs
152
+ u, _, vt = randomized_svd(
153
+ array, n_components, random_state=self.random_state, **kwargs
154
+ )
155
+
156
+ elif self.svd_method == "arpack":
157
+ u, _, vt = svds(array, k=n_components, ncv=self.n_svd_vecs)
158
+ if np.any(np.isnan(vt)):
159
+ # some eigenvalues of A * A.T are negative, causing
160
+ # sqrt() to be np.nan. This causes some vectors in vt
161
+ # to be np.nan.
162
+ A = safe_sparse_dot(array.T, array)
163
+ random_state = check_random_state(self.random_state)
164
+ # initialize with [-1,1] as in ARPACK
165
+ v0 = random_state.uniform(-1, 1, A.shape[0])
166
+ _, v = eigsh(A, ncv=self.n_svd_vecs, v0=v0)
167
+ vt = v.T
168
+ if np.any(np.isnan(u)):
169
+ A = safe_sparse_dot(array, array.T)
170
+ random_state = check_random_state(self.random_state)
171
+ # initialize with [-1,1] as in ARPACK
172
+ v0 = random_state.uniform(-1, 1, A.shape[0])
173
+ _, u = eigsh(A, ncv=self.n_svd_vecs, v0=v0)
174
+
175
+ assert_all_finite(u)
176
+ assert_all_finite(vt)
177
+ u = u[:, n_discard:]
178
+ vt = vt[n_discard:]
179
+ return u, vt.T
180
+
181
+ def _k_means(self, data, n_clusters):
182
+ if self.mini_batch:
183
+ model = MiniBatchKMeans(
184
+ n_clusters,
185
+ init=self.init,
186
+ n_init=self.n_init,
187
+ random_state=self.random_state,
188
+ )
189
+ else:
190
+ model = KMeans(
191
+ n_clusters,
192
+ init=self.init,
193
+ n_init=self.n_init,
194
+ random_state=self.random_state,
195
+ )
196
+ model.fit(data)
197
+ centroid = model.cluster_centers_
198
+ labels = model.labels_
199
+ return centroid, labels
200
+
201
+ def _more_tags(self):
202
+ return {
203
+ "_xfail_checks": {
204
+ "check_estimators_dtypes": "raises nan error",
205
+ "check_fit2d_1sample": "_scale_normalize fails",
206
+ "check_fit2d_1feature": "raises apply_along_axis error",
207
+ "check_estimator_sparse_data": "does not fail gracefully",
208
+ "check_methods_subset_invariance": "empty array passed inside",
209
+ "check_dont_overwrite_parameters": "empty array passed inside",
210
+ "check_fit2d_predict1d": "empty array passed inside",
211
+ }
212
+ }
213
+
214
+
215
+ class SpectralCoclustering(BaseSpectral):
216
+ """Spectral Co-Clustering algorithm (Dhillon, 2001).
217
+
218
+ Clusters rows and columns of an array `X` to solve the relaxed
219
+ normalized cut of the bipartite graph created from `X` as follows:
220
+ the edge between row vertex `i` and column vertex `j` has weight
221
+ `X[i, j]`.
222
+
223
+ The resulting bicluster structure is block-diagonal, since each
224
+ row and each column belongs to exactly one bicluster.
225
+
226
+ Supports sparse matrices, as long as they are nonnegative.
227
+
228
+ Read more in the :ref:`User Guide <spectral_coclustering>`.
229
+
230
+ Parameters
231
+ ----------
232
+ n_clusters : int, default=3
233
+ The number of biclusters to find.
234
+
235
+ svd_method : {'randomized', 'arpack'}, default='randomized'
236
+ Selects the algorithm for finding singular vectors. May be
237
+ 'randomized' or 'arpack'. If 'randomized', use
238
+ :func:`sklearn.utils.extmath.randomized_svd`, which may be faster
239
+ for large matrices. If 'arpack', use
240
+ :func:`scipy.sparse.linalg.svds`, which is more accurate, but
241
+ possibly slower in some cases.
242
+
243
+ n_svd_vecs : int, default=None
244
+ Number of vectors to use in calculating the SVD. Corresponds
245
+ to `ncv` when `svd_method=arpack` and `n_oversamples` when
246
+ `svd_method` is 'randomized`.
247
+
248
+ mini_batch : bool, default=False
249
+ Whether to use mini-batch k-means, which is faster but may get
250
+ different results.
251
+
252
+ init : {'k-means++', 'random'}, or ndarray of shape \
253
+ (n_clusters, n_features), default='k-means++'
254
+ Method for initialization of k-means algorithm; defaults to
255
+ 'k-means++'.
256
+
257
+ n_init : int, default=10
258
+ Number of random initializations that are tried with the
259
+ k-means algorithm.
260
+
261
+ If mini-batch k-means is used, the best initialization is
262
+ chosen and the algorithm runs once. Otherwise, the algorithm
263
+ is run for each initialization and the best solution chosen.
264
+
265
+ random_state : int, RandomState instance, default=None
266
+ Used for randomizing the singular value decomposition and the k-means
267
+ initialization. Use an int to make the randomness deterministic.
268
+ See :term:`Glossary <random_state>`.
269
+
270
+ Attributes
271
+ ----------
272
+ rows_ : array-like of shape (n_row_clusters, n_rows)
273
+ Results of the clustering. `rows[i, r]` is True if
274
+ cluster `i` contains row `r`. Available only after calling ``fit``.
275
+
276
+ columns_ : array-like of shape (n_column_clusters, n_columns)
277
+ Results of the clustering, like `rows`.
278
+
279
+ row_labels_ : array-like of shape (n_rows,)
280
+ The bicluster label of each row.
281
+
282
+ column_labels_ : array-like of shape (n_cols,)
283
+ The bicluster label of each column.
284
+
285
+ biclusters_ : tuple of two ndarrays
286
+ The tuple contains the `rows_` and `columns_` arrays.
287
+
288
+ n_features_in_ : int
289
+ Number of features seen during :term:`fit`.
290
+
291
+ .. versionadded:: 0.24
292
+
293
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
294
+ Names of features seen during :term:`fit`. Defined only when `X`
295
+ has feature names that are all strings.
296
+
297
+ .. versionadded:: 1.0
298
+
299
+ See Also
300
+ --------
301
+ SpectralBiclustering : Partitions rows and columns under the assumption
302
+ that the data has an underlying checkerboard structure.
303
+
304
+ References
305
+ ----------
306
+ * :doi:`Dhillon, Inderjit S, 2001. Co-clustering documents and words using
307
+ bipartite spectral graph partitioning.
308
+ <10.1145/502512.502550>`
309
+
310
+ Examples
311
+ --------
312
+ >>> from sklearn.cluster import SpectralCoclustering
313
+ >>> import numpy as np
314
+ >>> X = np.array([[1, 1], [2, 1], [1, 0],
315
+ ... [4, 7], [3, 5], [3, 6]])
316
+ >>> clustering = SpectralCoclustering(n_clusters=2, random_state=0).fit(X)
317
+ >>> clustering.row_labels_ #doctest: +SKIP
318
+ array([0, 1, 1, 0, 0, 0], dtype=int32)
319
+ >>> clustering.column_labels_ #doctest: +SKIP
320
+ array([0, 0], dtype=int32)
321
+ >>> clustering
322
+ SpectralCoclustering(n_clusters=2, random_state=0)
323
+ """
324
+
325
+ _parameter_constraints: dict = {
326
+ **BaseSpectral._parameter_constraints,
327
+ "n_clusters": [Interval(Integral, 1, None, closed="left")],
328
+ }
329
+
330
+ def __init__(
331
+ self,
332
+ n_clusters=3,
333
+ *,
334
+ svd_method="randomized",
335
+ n_svd_vecs=None,
336
+ mini_batch=False,
337
+ init="k-means++",
338
+ n_init=10,
339
+ random_state=None,
340
+ ):
341
+ super().__init__(
342
+ n_clusters, svd_method, n_svd_vecs, mini_batch, init, n_init, random_state
343
+ )
344
+
345
+ def _check_parameters(self, n_samples):
346
+ if self.n_clusters > n_samples:
347
+ raise ValueError(
348
+ f"n_clusters should be <= n_samples={n_samples}. Got"
349
+ f" {self.n_clusters} instead."
350
+ )
351
+
352
+ def _fit(self, X):
353
+ normalized_data, row_diag, col_diag = _scale_normalize(X)
354
+ n_sv = 1 + int(np.ceil(np.log2(self.n_clusters)))
355
+ u, v = self._svd(normalized_data, n_sv, n_discard=1)
356
+ z = np.vstack((row_diag[:, np.newaxis] * u, col_diag[:, np.newaxis] * v))
357
+
358
+ _, labels = self._k_means(z, self.n_clusters)
359
+
360
+ n_rows = X.shape[0]
361
+ self.row_labels_ = labels[:n_rows]
362
+ self.column_labels_ = labels[n_rows:]
363
+
364
+ self.rows_ = np.vstack([self.row_labels_ == c for c in range(self.n_clusters)])
365
+ self.columns_ = np.vstack(
366
+ [self.column_labels_ == c for c in range(self.n_clusters)]
367
+ )
368
+
369
+
370
+ class SpectralBiclustering(BaseSpectral):
371
+ """Spectral biclustering (Kluger, 2003).
372
+
373
+ Partitions rows and columns under the assumption that the data has
374
+ an underlying checkerboard structure. For instance, if there are
375
+ two row partitions and three column partitions, each row will
376
+ belong to three biclusters, and each column will belong to two
377
+ biclusters. The outer product of the corresponding row and column
378
+ label vectors gives this checkerboard structure.
379
+
380
+ Read more in the :ref:`User Guide <spectral_biclustering>`.
381
+
382
+ Parameters
383
+ ----------
384
+ n_clusters : int or tuple (n_row_clusters, n_column_clusters), default=3
385
+ The number of row and column clusters in the checkerboard
386
+ structure.
387
+
388
+ method : {'bistochastic', 'scale', 'log'}, default='bistochastic'
389
+ Method of normalizing and converting singular vectors into
390
+ biclusters. May be one of 'scale', 'bistochastic', or 'log'.
391
+ The authors recommend using 'log'. If the data is sparse,
392
+ however, log normalization will not work, which is why the
393
+ default is 'bistochastic'.
394
+
395
+ .. warning::
396
+ if `method='log'`, the data must not be sparse.
397
+
398
+ n_components : int, default=6
399
+ Number of singular vectors to check.
400
+
401
+ n_best : int, default=3
402
+ Number of best singular vectors to which to project the data
403
+ for clustering.
404
+
405
+ svd_method : {'randomized', 'arpack'}, default='randomized'
406
+ Selects the algorithm for finding singular vectors. May be
407
+ 'randomized' or 'arpack'. If 'randomized', uses
408
+ :func:`~sklearn.utils.extmath.randomized_svd`, which may be faster
409
+ for large matrices. If 'arpack', uses
410
+ `scipy.sparse.linalg.svds`, which is more accurate, but
411
+ possibly slower in some cases.
412
+
413
+ n_svd_vecs : int, default=None
414
+ Number of vectors to use in calculating the SVD. Corresponds
415
+ to `ncv` when `svd_method=arpack` and `n_oversamples` when
416
+ `svd_method` is 'randomized`.
417
+
418
+ mini_batch : bool, default=False
419
+ Whether to use mini-batch k-means, which is faster but may get
420
+ different results.
421
+
422
+ init : {'k-means++', 'random'} or ndarray of shape (n_clusters, n_features), \
423
+ default='k-means++'
424
+ Method for initialization of k-means algorithm; defaults to
425
+ 'k-means++'.
426
+
427
+ n_init : int, default=10
428
+ Number of random initializations that are tried with the
429
+ k-means algorithm.
430
+
431
+ If mini-batch k-means is used, the best initialization is
432
+ chosen and the algorithm runs once. Otherwise, the algorithm
433
+ is run for each initialization and the best solution chosen.
434
+
435
+ random_state : int, RandomState instance, default=None
436
+ Used for randomizing the singular value decomposition and the k-means
437
+ initialization. Use an int to make the randomness deterministic.
438
+ See :term:`Glossary <random_state>`.
439
+
440
+ Attributes
441
+ ----------
442
+ rows_ : array-like of shape (n_row_clusters, n_rows)
443
+ Results of the clustering. `rows[i, r]` is True if
444
+ cluster `i` contains row `r`. Available only after calling ``fit``.
445
+
446
+ columns_ : array-like of shape (n_column_clusters, n_columns)
447
+ Results of the clustering, like `rows`.
448
+
449
+ row_labels_ : array-like of shape (n_rows,)
450
+ Row partition labels.
451
+
452
+ column_labels_ : array-like of shape (n_cols,)
453
+ Column partition labels.
454
+
455
+ biclusters_ : tuple of two ndarrays
456
+ The tuple contains the `rows_` and `columns_` arrays.
457
+
458
+ n_features_in_ : int
459
+ Number of features seen during :term:`fit`.
460
+
461
+ .. versionadded:: 0.24
462
+
463
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
464
+ Names of features seen during :term:`fit`. Defined only when `X`
465
+ has feature names that are all strings.
466
+
467
+ .. versionadded:: 1.0
468
+
469
+ See Also
470
+ --------
471
+ SpectralCoclustering : Spectral Co-Clustering algorithm (Dhillon, 2001).
472
+
473
+ References
474
+ ----------
475
+
476
+ * :doi:`Kluger, Yuval, et. al., 2003. Spectral biclustering of microarray
477
+ data: coclustering genes and conditions.
478
+ <10.1101/gr.648603>`
479
+
480
+ Examples
481
+ --------
482
+ >>> from sklearn.cluster import SpectralBiclustering
483
+ >>> import numpy as np
484
+ >>> X = np.array([[1, 1], [2, 1], [1, 0],
485
+ ... [4, 7], [3, 5], [3, 6]])
486
+ >>> clustering = SpectralBiclustering(n_clusters=2, random_state=0).fit(X)
487
+ >>> clustering.row_labels_
488
+ array([1, 1, 1, 0, 0, 0], dtype=int32)
489
+ >>> clustering.column_labels_
490
+ array([0, 1], dtype=int32)
491
+ >>> clustering
492
+ SpectralBiclustering(n_clusters=2, random_state=0)
493
+ """
494
+
495
+ _parameter_constraints: dict = {
496
+ **BaseSpectral._parameter_constraints,
497
+ "n_clusters": [Interval(Integral, 1, None, closed="left"), tuple],
498
+ "method": [StrOptions({"bistochastic", "scale", "log"})],
499
+ "n_components": [Interval(Integral, 1, None, closed="left")],
500
+ "n_best": [Interval(Integral, 1, None, closed="left")],
501
+ }
502
+
503
+ def __init__(
504
+ self,
505
+ n_clusters=3,
506
+ *,
507
+ method="bistochastic",
508
+ n_components=6,
509
+ n_best=3,
510
+ svd_method="randomized",
511
+ n_svd_vecs=None,
512
+ mini_batch=False,
513
+ init="k-means++",
514
+ n_init=10,
515
+ random_state=None,
516
+ ):
517
+ super().__init__(
518
+ n_clusters, svd_method, n_svd_vecs, mini_batch, init, n_init, random_state
519
+ )
520
+ self.method = method
521
+ self.n_components = n_components
522
+ self.n_best = n_best
523
+
524
+ def _check_parameters(self, n_samples):
525
+ if isinstance(self.n_clusters, Integral):
526
+ if self.n_clusters > n_samples:
527
+ raise ValueError(
528
+ f"n_clusters should be <= n_samples={n_samples}. Got"
529
+ f" {self.n_clusters} instead."
530
+ )
531
+ else: # tuple
532
+ try:
533
+ n_row_clusters, n_column_clusters = self.n_clusters
534
+ check_scalar(
535
+ n_row_clusters,
536
+ "n_row_clusters",
537
+ target_type=Integral,
538
+ min_val=1,
539
+ max_val=n_samples,
540
+ )
541
+ check_scalar(
542
+ n_column_clusters,
543
+ "n_column_clusters",
544
+ target_type=Integral,
545
+ min_val=1,
546
+ max_val=n_samples,
547
+ )
548
+ except (ValueError, TypeError) as e:
549
+ raise ValueError(
550
+ "Incorrect parameter n_clusters has value:"
551
+ f" {self.n_clusters}. It should either be a single integer"
552
+ " or an iterable with two integers:"
553
+ " (n_row_clusters, n_column_clusters)"
554
+ " And the values are should be in the"
555
+ " range: (1, n_samples)"
556
+ ) from e
557
+
558
+ if self.n_best > self.n_components:
559
+ raise ValueError(
560
+ f"n_best={self.n_best} must be <= n_components={self.n_components}."
561
+ )
562
+
563
+ def _fit(self, X):
564
+ n_sv = self.n_components
565
+ if self.method == "bistochastic":
566
+ normalized_data = _bistochastic_normalize(X)
567
+ n_sv += 1
568
+ elif self.method == "scale":
569
+ normalized_data, _, _ = _scale_normalize(X)
570
+ n_sv += 1
571
+ elif self.method == "log":
572
+ normalized_data = _log_normalize(X)
573
+ n_discard = 0 if self.method == "log" else 1
574
+ u, v = self._svd(normalized_data, n_sv, n_discard)
575
+ ut = u.T
576
+ vt = v.T
577
+
578
+ try:
579
+ n_row_clusters, n_col_clusters = self.n_clusters
580
+ except TypeError:
581
+ n_row_clusters = n_col_clusters = self.n_clusters
582
+
583
+ best_ut = self._fit_best_piecewise(ut, self.n_best, n_row_clusters)
584
+
585
+ best_vt = self._fit_best_piecewise(vt, self.n_best, n_col_clusters)
586
+
587
+ self.row_labels_ = self._project_and_cluster(X, best_vt.T, n_row_clusters)
588
+
589
+ self.column_labels_ = self._project_and_cluster(X.T, best_ut.T, n_col_clusters)
590
+
591
+ self.rows_ = np.vstack(
592
+ [
593
+ self.row_labels_ == label
594
+ for label in range(n_row_clusters)
595
+ for _ in range(n_col_clusters)
596
+ ]
597
+ )
598
+ self.columns_ = np.vstack(
599
+ [
600
+ self.column_labels_ == label
601
+ for _ in range(n_row_clusters)
602
+ for label in range(n_col_clusters)
603
+ ]
604
+ )
605
+
606
+ def _fit_best_piecewise(self, vectors, n_best, n_clusters):
607
+ """Find the ``n_best`` vectors that are best approximated by piecewise
608
+ constant vectors.
609
+
610
+ The piecewise vectors are found by k-means; the best is chosen
611
+ according to Euclidean distance.
612
+
613
+ """
614
+
615
+ def make_piecewise(v):
616
+ centroid, labels = self._k_means(v.reshape(-1, 1), n_clusters)
617
+ return centroid[labels].ravel()
618
+
619
+ piecewise_vectors = np.apply_along_axis(make_piecewise, axis=1, arr=vectors)
620
+ dists = np.apply_along_axis(norm, axis=1, arr=(vectors - piecewise_vectors))
621
+ result = vectors[np.argsort(dists)[:n_best]]
622
+ return result
623
+
624
+ def _project_and_cluster(self, data, vectors, n_clusters):
625
+ """Project ``data`` to ``vectors`` and cluster the result."""
626
+ projected = safe_sparse_dot(data, vectors)
627
+ _, labels = self._k_means(projected, n_clusters)
628
+ return labels
videollama2/lib/python3.10/site-packages/sklearn/cluster/_feature_agglomeration.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Feature agglomeration. Base classes and functions for performing feature
3
+ agglomeration.
4
+ """
5
+ # Author: V. Michel, A. Gramfort
6
+ # License: BSD 3 clause
7
+
8
+ import numpy as np
9
+
10
+ from ..base import TransformerMixin
11
+ from ..utils.validation import check_is_fitted
12
+ from scipy.sparse import issparse
13
+
14
+ ###############################################################################
15
+ # Mixin class for feature agglomeration.
16
+
17
+
18
+ class AgglomerationTransform(TransformerMixin):
19
+ """
20
+ A class for feature agglomeration via the transform interface.
21
+ """
22
+
23
+ def transform(self, X):
24
+ """
25
+ Transform a new matrix using the built clustering.
26
+
27
+ Parameters
28
+ ----------
29
+ X : array-like of shape (n_samples, n_features) or \
30
+ (n_samples, n_samples)
31
+ A M by N array of M observations in N dimensions or a length
32
+ M array of M one-dimensional observations.
33
+
34
+ Returns
35
+ -------
36
+ Y : ndarray of shape (n_samples, n_clusters) or (n_clusters,)
37
+ The pooled values for each feature cluster.
38
+ """
39
+ check_is_fitted(self)
40
+
41
+ X = self._validate_data(X, reset=False)
42
+ if self.pooling_func == np.mean and not issparse(X):
43
+ size = np.bincount(self.labels_)
44
+ n_samples = X.shape[0]
45
+ # a fast way to compute the mean of grouped features
46
+ nX = np.array(
47
+ [np.bincount(self.labels_, X[i, :]) / size for i in range(n_samples)]
48
+ )
49
+ else:
50
+ nX = [
51
+ self.pooling_func(X[:, self.labels_ == l], axis=1)
52
+ for l in np.unique(self.labels_)
53
+ ]
54
+ nX = np.array(nX).T
55
+ return nX
56
+
57
+ def inverse_transform(self, Xred):
58
+ """
59
+ Inverse the transformation and return a vector of size `n_features`.
60
+
61
+ Parameters
62
+ ----------
63
+ Xred : array-like of shape (n_samples, n_clusters) or (n_clusters,)
64
+ The values to be assigned to each cluster of samples.
65
+
66
+ Returns
67
+ -------
68
+ X : ndarray of shape (n_samples, n_features) or (n_features,)
69
+ A vector of size `n_samples` with the values of `Xred` assigned to
70
+ each of the cluster of samples.
71
+ """
72
+ check_is_fitted(self)
73
+
74
+ unil, inverse = np.unique(self.labels_, return_inverse=True)
75
+ return Xred[..., inverse]
videollama2/lib/python3.10/site-packages/sklearn/cluster/_hierarchical_fast.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbab2dfb377c76cc63b49b08c32f7f7c3848f951b42019bc08cd41b58f02d397
3
+ size 327769
videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f2d3838bfb6b911e555204f2e11c0bc2097fe95370c871103e0b4f622b5dd059
3
+ size 417737
videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_common.pxd ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from cython cimport floating
2
+
3
+
4
+ cdef floating _euclidean_dense_dense(floating*, floating*, int, bint) nogil
5
+
6
+ cdef floating _euclidean_sparse_dense(floating[::1], int[::1], floating[::1],
7
+ floating, bint) nogil
8
+
9
+ cpdef void _relocate_empty_clusters_dense(
10
+ floating[:, ::1], floating[::1], floating[:, ::1],
11
+ floating[:, ::1], floating[::1], int[::1])
12
+
13
+ cpdef void _relocate_empty_clusters_sparse(
14
+ floating[::1], int[::1], int[::1], floating[::1], floating[:, ::1],
15
+ floating[:, ::1], floating[::1], int[::1])
16
+
17
+ cdef void _average_centers(floating[:, ::1], floating[::1])
18
+
19
+ cdef void _center_shift(floating[:, ::1], floating[:, ::1], floating[::1])
videollama2/lib/python3.10/site-packages/sklearn/cluster/_k_means_elkan.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:edfd181e6be2fe2da302115e3d5729c53f06d0a7d66d42a19b5e21f87d37ea6d
3
+ size 431033
videollama2/lib/python3.10/site-packages/sklearn/cluster/_mean_shift.py ADDED
@@ -0,0 +1,536 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mean shift clustering algorithm.
2
+
3
+ Mean shift clustering aims to discover *blobs* in a smooth density of
4
+ samples. It is a centroid based algorithm, which works by updating candidates
5
+ for centroids to be the mean of the points within a given region. These
6
+ candidates are then filtered in a post-processing stage to eliminate
7
+ near-duplicates to form the final set of centroids.
8
+
9
+ Seeding is performed using a binning technique for scalability.
10
+ """
11
+
12
+ # Authors: Conrad Lee <conradlee@gmail.com>
13
+ # Alexandre Gramfort <alexandre.gramfort@inria.fr>
14
+ # Gael Varoquaux <gael.varoquaux@normalesup.org>
15
+ # Martino Sorbaro <martino.sorbaro@ed.ac.uk>
16
+
17
+ import numpy as np
18
+ import warnings
19
+ from numbers import Integral, Real
20
+
21
+ from collections import defaultdict
22
+ from ..utils._param_validation import Interval
23
+ from ..utils.validation import check_is_fitted
24
+ from ..utils.parallel import delayed, Parallel
25
+ from ..utils import check_random_state, gen_batches, check_array
26
+ from ..base import BaseEstimator, ClusterMixin
27
+ from ..neighbors import NearestNeighbors
28
+ from ..metrics.pairwise import pairwise_distances_argmin
29
+ from .._config import config_context
30
+
31
+
32
+ def estimate_bandwidth(X, *, quantile=0.3, n_samples=None, random_state=0, n_jobs=None):
33
+ """Estimate the bandwidth to use with the mean-shift algorithm.
34
+
35
+ That this function takes time at least quadratic in n_samples. For large
36
+ datasets, it's wise to set that parameter to a small value.
37
+
38
+ Parameters
39
+ ----------
40
+ X : array-like of shape (n_samples, n_features)
41
+ Input points.
42
+
43
+ quantile : float, default=0.3
44
+ Should be between [0, 1]
45
+ 0.5 means that the median of all pairwise distances is used.
46
+
47
+ n_samples : int, default=None
48
+ The number of samples to use. If not given, all samples are used.
49
+
50
+ random_state : int, RandomState instance, default=None
51
+ The generator used to randomly select the samples from input points
52
+ for bandwidth estimation. Use an int to make the randomness
53
+ deterministic.
54
+ See :term:`Glossary <random_state>`.
55
+
56
+ n_jobs : int, default=None
57
+ The number of parallel jobs to run for neighbors search.
58
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
59
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
60
+ for more details.
61
+
62
+ Returns
63
+ -------
64
+ bandwidth : float
65
+ The bandwidth parameter.
66
+ """
67
+ X = check_array(X)
68
+
69
+ random_state = check_random_state(random_state)
70
+ if n_samples is not None:
71
+ idx = random_state.permutation(X.shape[0])[:n_samples]
72
+ X = X[idx]
73
+ n_neighbors = int(X.shape[0] * quantile)
74
+ if n_neighbors < 1: # cannot fit NearestNeighbors with n_neighbors = 0
75
+ n_neighbors = 1
76
+ nbrs = NearestNeighbors(n_neighbors=n_neighbors, n_jobs=n_jobs)
77
+ nbrs.fit(X)
78
+
79
+ bandwidth = 0.0
80
+ for batch in gen_batches(len(X), 500):
81
+ d, _ = nbrs.kneighbors(X[batch, :], return_distance=True)
82
+ bandwidth += np.max(d, axis=1).sum()
83
+
84
+ return bandwidth / X.shape[0]
85
+
86
+
87
+ # separate function for each seed's iterative loop
88
+ def _mean_shift_single_seed(my_mean, X, nbrs, max_iter):
89
+ # For each seed, climb gradient until convergence or max_iter
90
+ bandwidth = nbrs.get_params()["radius"]
91
+ stop_thresh = 1e-3 * bandwidth # when mean has converged
92
+ completed_iterations = 0
93
+ while True:
94
+ # Find mean of points within bandwidth
95
+ i_nbrs = nbrs.radius_neighbors([my_mean], bandwidth, return_distance=False)[0]
96
+ points_within = X[i_nbrs]
97
+ if len(points_within) == 0:
98
+ break # Depending on seeding strategy this condition may occur
99
+ my_old_mean = my_mean # save the old mean
100
+ my_mean = np.mean(points_within, axis=0)
101
+ # If converged or at max_iter, adds the cluster
102
+ if (
103
+ np.linalg.norm(my_mean - my_old_mean) < stop_thresh
104
+ or completed_iterations == max_iter
105
+ ):
106
+ break
107
+ completed_iterations += 1
108
+ return tuple(my_mean), len(points_within), completed_iterations
109
+
110
+
111
+ def mean_shift(
112
+ X,
113
+ *,
114
+ bandwidth=None,
115
+ seeds=None,
116
+ bin_seeding=False,
117
+ min_bin_freq=1,
118
+ cluster_all=True,
119
+ max_iter=300,
120
+ n_jobs=None,
121
+ ):
122
+ """Perform mean shift clustering of data using a flat kernel.
123
+
124
+ Read more in the :ref:`User Guide <mean_shift>`.
125
+
126
+ Parameters
127
+ ----------
128
+
129
+ X : array-like of shape (n_samples, n_features)
130
+ Input data.
131
+
132
+ bandwidth : float, default=None
133
+ Kernel bandwidth.
134
+
135
+ If bandwidth is not given, it is determined using a heuristic based on
136
+ the median of all pairwise distances. This will take quadratic time in
137
+ the number of samples. The sklearn.cluster.estimate_bandwidth function
138
+ can be used to do this more efficiently.
139
+
140
+ seeds : array-like of shape (n_seeds, n_features) or None
141
+ Point used as initial kernel locations. If None and bin_seeding=False,
142
+ each data point is used as a seed. If None and bin_seeding=True,
143
+ see bin_seeding.
144
+
145
+ bin_seeding : bool, default=False
146
+ If true, initial kernel locations are not locations of all
147
+ points, but rather the location of the discretized version of
148
+ points, where points are binned onto a grid whose coarseness
149
+ corresponds to the bandwidth. Setting this option to True will speed
150
+ up the algorithm because fewer seeds will be initialized.
151
+ Ignored if seeds argument is not None.
152
+
153
+ min_bin_freq : int, default=1
154
+ To speed up the algorithm, accept only those bins with at least
155
+ min_bin_freq points as seeds.
156
+
157
+ cluster_all : bool, default=True
158
+ If true, then all points are clustered, even those orphans that are
159
+ not within any kernel. Orphans are assigned to the nearest kernel.
160
+ If false, then orphans are given cluster label -1.
161
+
162
+ max_iter : int, default=300
163
+ Maximum number of iterations, per seed point before the clustering
164
+ operation terminates (for that seed point), if has not converged yet.
165
+
166
+ n_jobs : int, default=None
167
+ The number of jobs to use for the computation. The following tasks benefit
168
+ from the parallelization:
169
+
170
+ - The search of nearest neighbors for bandwidth estimation and label
171
+ assignments. See the details in the docstring of the
172
+ ``NearestNeighbors`` class.
173
+ - Hill-climbing optimization for all seeds.
174
+
175
+ See :term:`Glossary <n_jobs>` for more details.
176
+
177
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
178
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
179
+ for more details.
180
+
181
+ .. versionadded:: 0.17
182
+ Parallel Execution using *n_jobs*.
183
+
184
+ Returns
185
+ -------
186
+
187
+ cluster_centers : ndarray of shape (n_clusters, n_features)
188
+ Coordinates of cluster centers.
189
+
190
+ labels : ndarray of shape (n_samples,)
191
+ Cluster labels for each point.
192
+
193
+ Notes
194
+ -----
195
+ For an example, see :ref:`examples/cluster/plot_mean_shift.py
196
+ <sphx_glr_auto_examples_cluster_plot_mean_shift.py>`.
197
+ """
198
+ model = MeanShift(
199
+ bandwidth=bandwidth,
200
+ seeds=seeds,
201
+ min_bin_freq=min_bin_freq,
202
+ bin_seeding=bin_seeding,
203
+ cluster_all=cluster_all,
204
+ n_jobs=n_jobs,
205
+ max_iter=max_iter,
206
+ ).fit(X)
207
+ return model.cluster_centers_, model.labels_
208
+
209
+
210
+ def get_bin_seeds(X, bin_size, min_bin_freq=1):
211
+ """Find seeds for mean_shift.
212
+
213
+ Finds seeds by first binning data onto a grid whose lines are
214
+ spaced bin_size apart, and then choosing those bins with at least
215
+ min_bin_freq points.
216
+
217
+ Parameters
218
+ ----------
219
+
220
+ X : array-like of shape (n_samples, n_features)
221
+ Input points, the same points that will be used in mean_shift.
222
+
223
+ bin_size : float
224
+ Controls the coarseness of the binning. Smaller values lead
225
+ to more seeding (which is computationally more expensive). If you're
226
+ not sure how to set this, set it to the value of the bandwidth used
227
+ in clustering.mean_shift.
228
+
229
+ min_bin_freq : int, default=1
230
+ Only bins with at least min_bin_freq will be selected as seeds.
231
+ Raising this value decreases the number of seeds found, which
232
+ makes mean_shift computationally cheaper.
233
+
234
+ Returns
235
+ -------
236
+ bin_seeds : array-like of shape (n_samples, n_features)
237
+ Points used as initial kernel positions in clustering.mean_shift.
238
+ """
239
+ if bin_size == 0:
240
+ return X
241
+
242
+ # Bin points
243
+ bin_sizes = defaultdict(int)
244
+ for point in X:
245
+ binned_point = np.round(point / bin_size)
246
+ bin_sizes[tuple(binned_point)] += 1
247
+
248
+ # Select only those bins as seeds which have enough members
249
+ bin_seeds = np.array(
250
+ [point for point, freq in bin_sizes.items() if freq >= min_bin_freq],
251
+ dtype=np.float32,
252
+ )
253
+ if len(bin_seeds) == len(X):
254
+ warnings.warn(
255
+ "Binning data failed with provided bin_size=%f, using data points as seeds."
256
+ % bin_size
257
+ )
258
+ return X
259
+ bin_seeds = bin_seeds * bin_size
260
+ return bin_seeds
261
+
262
+
263
+ class MeanShift(ClusterMixin, BaseEstimator):
264
+ """Mean shift clustering using a flat kernel.
265
+
266
+ Mean shift clustering aims to discover "blobs" in a smooth density of
267
+ samples. It is a centroid-based algorithm, which works by updating
268
+ candidates for centroids to be the mean of the points within a given
269
+ region. These candidates are then filtered in a post-processing stage to
270
+ eliminate near-duplicates to form the final set of centroids.
271
+
272
+ Seeding is performed using a binning technique for scalability.
273
+
274
+ Read more in the :ref:`User Guide <mean_shift>`.
275
+
276
+ Parameters
277
+ ----------
278
+ bandwidth : float, default=None
279
+ Bandwidth used in the flat kernel.
280
+
281
+ If not given, the bandwidth is estimated using
282
+ sklearn.cluster.estimate_bandwidth; see the documentation for that
283
+ function for hints on scalability (see also the Notes, below).
284
+
285
+ seeds : array-like of shape (n_samples, n_features), default=None
286
+ Seeds used to initialize kernels. If not set,
287
+ the seeds are calculated by clustering.get_bin_seeds
288
+ with bandwidth as the grid size and default values for
289
+ other parameters.
290
+
291
+ bin_seeding : bool, default=False
292
+ If true, initial kernel locations are not locations of all
293
+ points, but rather the location of the discretized version of
294
+ points, where points are binned onto a grid whose coarseness
295
+ corresponds to the bandwidth. Setting this option to True will speed
296
+ up the algorithm because fewer seeds will be initialized.
297
+ The default value is False.
298
+ Ignored if seeds argument is not None.
299
+
300
+ min_bin_freq : int, default=1
301
+ To speed up the algorithm, accept only those bins with at least
302
+ min_bin_freq points as seeds.
303
+
304
+ cluster_all : bool, default=True
305
+ If true, then all points are clustered, even those orphans that are
306
+ not within any kernel. Orphans are assigned to the nearest kernel.
307
+ If false, then orphans are given cluster label -1.
308
+
309
+ n_jobs : int, default=None
310
+ The number of jobs to use for the computation. The following tasks benefit
311
+ from the parallelization:
312
+
313
+ - The search of nearest neighbors for bandwidth estimation and label
314
+ assignments. See the details in the docstring of the
315
+ ``NearestNeighbors`` class.
316
+ - Hill-climbing optimization for all seeds.
317
+
318
+ See :term:`Glossary <n_jobs>` for more details.
319
+
320
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
321
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
322
+ for more details.
323
+
324
+ max_iter : int, default=300
325
+ Maximum number of iterations, per seed point before the clustering
326
+ operation terminates (for that seed point), if has not converged yet.
327
+
328
+ .. versionadded:: 0.22
329
+
330
+ Attributes
331
+ ----------
332
+ cluster_centers_ : ndarray of shape (n_clusters, n_features)
333
+ Coordinates of cluster centers.
334
+
335
+ labels_ : ndarray of shape (n_samples,)
336
+ Labels of each point.
337
+
338
+ n_iter_ : int
339
+ Maximum number of iterations performed on each seed.
340
+
341
+ .. versionadded:: 0.22
342
+
343
+ n_features_in_ : int
344
+ Number of features seen during :term:`fit`.
345
+
346
+ .. versionadded:: 0.24
347
+
348
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
349
+ Names of features seen during :term:`fit`. Defined only when `X`
350
+ has feature names that are all strings.
351
+
352
+ .. versionadded:: 1.0
353
+
354
+ See Also
355
+ --------
356
+ KMeans : K-Means clustering.
357
+
358
+ Notes
359
+ -----
360
+
361
+ Scalability:
362
+
363
+ Because this implementation uses a flat kernel and
364
+ a Ball Tree to look up members of each kernel, the complexity will tend
365
+ towards O(T*n*log(n)) in lower dimensions, with n the number of samples
366
+ and T the number of points. In higher dimensions the complexity will
367
+ tend towards O(T*n^2).
368
+
369
+ Scalability can be boosted by using fewer seeds, for example by using
370
+ a higher value of min_bin_freq in the get_bin_seeds function.
371
+
372
+ Note that the estimate_bandwidth function is much less scalable than the
373
+ mean shift algorithm and will be the bottleneck if it is used.
374
+
375
+ References
376
+ ----------
377
+
378
+ Dorin Comaniciu and Peter Meer, "Mean Shift: A robust approach toward
379
+ feature space analysis". IEEE Transactions on Pattern Analysis and
380
+ Machine Intelligence. 2002. pp. 603-619.
381
+
382
+ Examples
383
+ --------
384
+ >>> from sklearn.cluster import MeanShift
385
+ >>> import numpy as np
386
+ >>> X = np.array([[1, 1], [2, 1], [1, 0],
387
+ ... [4, 7], [3, 5], [3, 6]])
388
+ >>> clustering = MeanShift(bandwidth=2).fit(X)
389
+ >>> clustering.labels_
390
+ array([1, 1, 1, 0, 0, 0])
391
+ >>> clustering.predict([[0, 0], [5, 5]])
392
+ array([1, 0])
393
+ >>> clustering
394
+ MeanShift(bandwidth=2)
395
+ """
396
+
397
+ _parameter_constraints: dict = {
398
+ "bandwidth": [Interval(Real, 0, None, closed="neither"), None],
399
+ "seeds": ["array-like", None],
400
+ "bin_seeding": ["boolean"],
401
+ "min_bin_freq": [Interval(Integral, 1, None, closed="left")],
402
+ "cluster_all": ["boolean"],
403
+ "n_jobs": [Integral, None],
404
+ "max_iter": [Interval(Integral, 0, None, closed="left")],
405
+ }
406
+
407
+ def __init__(
408
+ self,
409
+ *,
410
+ bandwidth=None,
411
+ seeds=None,
412
+ bin_seeding=False,
413
+ min_bin_freq=1,
414
+ cluster_all=True,
415
+ n_jobs=None,
416
+ max_iter=300,
417
+ ):
418
+ self.bandwidth = bandwidth
419
+ self.seeds = seeds
420
+ self.bin_seeding = bin_seeding
421
+ self.cluster_all = cluster_all
422
+ self.min_bin_freq = min_bin_freq
423
+ self.n_jobs = n_jobs
424
+ self.max_iter = max_iter
425
+
426
+ def fit(self, X, y=None):
427
+ """Perform clustering.
428
+
429
+ Parameters
430
+ ----------
431
+ X : array-like of shape (n_samples, n_features)
432
+ Samples to cluster.
433
+
434
+ y : Ignored
435
+ Not used, present for API consistency by convention.
436
+
437
+ Returns
438
+ -------
439
+ self : object
440
+ Fitted instance.
441
+ """
442
+ self._validate_params()
443
+ X = self._validate_data(X)
444
+ bandwidth = self.bandwidth
445
+ if bandwidth is None:
446
+ bandwidth = estimate_bandwidth(X, n_jobs=self.n_jobs)
447
+
448
+ seeds = self.seeds
449
+ if seeds is None:
450
+ if self.bin_seeding:
451
+ seeds = get_bin_seeds(X, bandwidth, self.min_bin_freq)
452
+ else:
453
+ seeds = X
454
+ n_samples, n_features = X.shape
455
+ center_intensity_dict = {}
456
+
457
+ # We use n_jobs=1 because this will be used in nested calls under
458
+ # parallel calls to _mean_shift_single_seed so there is no need for
459
+ # for further parallelism.
460
+ nbrs = NearestNeighbors(radius=bandwidth, n_jobs=1).fit(X)
461
+
462
+ # execute iterations on all seeds in parallel
463
+ all_res = Parallel(n_jobs=self.n_jobs)(
464
+ delayed(_mean_shift_single_seed)(seed, X, nbrs, self.max_iter)
465
+ for seed in seeds
466
+ )
467
+ # copy results in a dictionary
468
+ for i in range(len(seeds)):
469
+ if all_res[i][1]: # i.e. len(points_within) > 0
470
+ center_intensity_dict[all_res[i][0]] = all_res[i][1]
471
+
472
+ self.n_iter_ = max([x[2] for x in all_res])
473
+
474
+ if not center_intensity_dict:
475
+ # nothing near seeds
476
+ raise ValueError(
477
+ "No point was within bandwidth=%f of any seed. Try a different seeding"
478
+ " strategy or increase the bandwidth."
479
+ % bandwidth
480
+ )
481
+
482
+ # POST PROCESSING: remove near duplicate points
483
+ # If the distance between two kernels is less than the bandwidth,
484
+ # then we have to remove one because it is a duplicate. Remove the
485
+ # one with fewer points.
486
+
487
+ sorted_by_intensity = sorted(
488
+ center_intensity_dict.items(),
489
+ key=lambda tup: (tup[1], tup[0]),
490
+ reverse=True,
491
+ )
492
+ sorted_centers = np.array([tup[0] for tup in sorted_by_intensity])
493
+ unique = np.ones(len(sorted_centers), dtype=bool)
494
+ nbrs = NearestNeighbors(radius=bandwidth, n_jobs=self.n_jobs).fit(
495
+ sorted_centers
496
+ )
497
+ for i, center in enumerate(sorted_centers):
498
+ if unique[i]:
499
+ neighbor_idxs = nbrs.radius_neighbors([center], return_distance=False)[
500
+ 0
501
+ ]
502
+ unique[neighbor_idxs] = 0
503
+ unique[i] = 1 # leave the current point as unique
504
+ cluster_centers = sorted_centers[unique]
505
+
506
+ # ASSIGN LABELS: a point belongs to the cluster that it is closest to
507
+ nbrs = NearestNeighbors(n_neighbors=1, n_jobs=self.n_jobs).fit(cluster_centers)
508
+ labels = np.zeros(n_samples, dtype=int)
509
+ distances, idxs = nbrs.kneighbors(X)
510
+ if self.cluster_all:
511
+ labels = idxs.flatten()
512
+ else:
513
+ labels.fill(-1)
514
+ bool_selector = distances.flatten() <= bandwidth
515
+ labels[bool_selector] = idxs.flatten()[bool_selector]
516
+
517
+ self.cluster_centers_, self.labels_ = cluster_centers, labels
518
+ return self
519
+
520
+ def predict(self, X):
521
+ """Predict the closest cluster each sample in X belongs to.
522
+
523
+ Parameters
524
+ ----------
525
+ X : array-like of shape (n_samples, n_features)
526
+ New data to predict.
527
+
528
+ Returns
529
+ -------
530
+ labels : ndarray of shape (n_samples,)
531
+ Index of the cluster each sample belongs to.
532
+ """
533
+ check_is_fitted(self)
534
+ X = self._validate_data(X, reset=False)
535
+ with config_context(assume_finite=True):
536
+ return pairwise_distances_argmin(X, self.cluster_centers_)
videollama2/lib/python3.10/site-packages/sklearn/cluster/_spectral.py ADDED
@@ -0,0 +1,791 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Algorithms for spectral clustering"""
2
+
3
+ # Author: Gael Varoquaux <gael.varoquaux@normalesup.org>
4
+ # Brian Cheung
5
+ # Wei LI <kuantkid@gmail.com>
6
+ # Andrew Knyazev <Andrew.Knyazev@ucdenver.edu>
7
+ # License: BSD 3 clause
8
+
9
+ from numbers import Integral, Real
10
+ import warnings
11
+
12
+ import numpy as np
13
+
14
+ from scipy.linalg import LinAlgError, qr, svd
15
+ from scipy.sparse import csc_matrix
16
+
17
+ from ..base import BaseEstimator, ClusterMixin
18
+ from ..utils._param_validation import Interval, StrOptions
19
+ from ..utils import check_random_state, as_float_array
20
+ from ..metrics.pairwise import pairwise_kernels, KERNEL_PARAMS
21
+ from ..neighbors import kneighbors_graph, NearestNeighbors
22
+ from ..manifold import spectral_embedding
23
+ from ._kmeans import k_means
24
+
25
+
26
+ def cluster_qr(vectors):
27
+ """Find the discrete partition closest to the eigenvector embedding.
28
+
29
+ This implementation was proposed in [1]_.
30
+
31
+ .. versionadded:: 1.1
32
+
33
+ Parameters
34
+ ----------
35
+ vectors : array-like, shape: (n_samples, n_clusters)
36
+ The embedding space of the samples.
37
+
38
+ Returns
39
+ -------
40
+ labels : array of integers, shape: n_samples
41
+ The cluster labels of vectors.
42
+
43
+ References
44
+ ----------
45
+ .. [1] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019
46
+ Anil Damle, Victor Minden, Lexing Ying
47
+ <10.1093/imaiai/iay008>`
48
+
49
+ """
50
+
51
+ k = vectors.shape[1]
52
+ _, _, piv = qr(vectors.T, pivoting=True)
53
+ ut, _, v = svd(vectors[piv[:k], :].T)
54
+ vectors = abs(np.dot(vectors, np.dot(ut, v.conj())))
55
+ return vectors.argmax(axis=1)
56
+
57
+
58
+ def discretize(
59
+ vectors, *, copy=True, max_svd_restarts=30, n_iter_max=20, random_state=None
60
+ ):
61
+ """Search for a partition matrix which is closest to the eigenvector embedding.
62
+
63
+ This implementation was proposed in [1]_.
64
+
65
+ Parameters
66
+ ----------
67
+ vectors : array-like of shape (n_samples, n_clusters)
68
+ The embedding space of the samples.
69
+
70
+ copy : bool, default=True
71
+ Whether to copy vectors, or perform in-place normalization.
72
+
73
+ max_svd_restarts : int, default=30
74
+ Maximum number of attempts to restart SVD if convergence fails
75
+
76
+ n_iter_max : int, default=30
77
+ Maximum number of iterations to attempt in rotation and partition
78
+ matrix search if machine precision convergence is not reached
79
+
80
+ random_state : int, RandomState instance, default=None
81
+ Determines random number generation for rotation matrix initialization.
82
+ Use an int to make the randomness deterministic.
83
+ See :term:`Glossary <random_state>`.
84
+
85
+ Returns
86
+ -------
87
+ labels : array of integers, shape: n_samples
88
+ The labels of the clusters.
89
+
90
+ References
91
+ ----------
92
+
93
+ .. [1] `Multiclass spectral clustering, 2003
94
+ Stella X. Yu, Jianbo Shi
95
+ <https://people.eecs.berkeley.edu/~jordan/courses/281B-spring04/readings/yu-shi.pdf>`_
96
+
97
+ Notes
98
+ -----
99
+
100
+ The eigenvector embedding is used to iteratively search for the
101
+ closest discrete partition. First, the eigenvector embedding is
102
+ normalized to the space of partition matrices. An optimal discrete
103
+ partition matrix closest to this normalized embedding multiplied by
104
+ an initial rotation is calculated. Fixing this discrete partition
105
+ matrix, an optimal rotation matrix is calculated. These two
106
+ calculations are performed until convergence. The discrete partition
107
+ matrix is returned as the clustering solution. Used in spectral
108
+ clustering, this method tends to be faster and more robust to random
109
+ initialization than k-means.
110
+
111
+ """
112
+
113
+ random_state = check_random_state(random_state)
114
+
115
+ vectors = as_float_array(vectors, copy=copy)
116
+
117
+ eps = np.finfo(float).eps
118
+ n_samples, n_components = vectors.shape
119
+
120
+ # Normalize the eigenvectors to an equal length of a vector of ones.
121
+ # Reorient the eigenvectors to point in the negative direction with respect
122
+ # to the first element. This may have to do with constraining the
123
+ # eigenvectors to lie in a specific quadrant to make the discretization
124
+ # search easier.
125
+ norm_ones = np.sqrt(n_samples)
126
+ for i in range(vectors.shape[1]):
127
+ vectors[:, i] = (vectors[:, i] / np.linalg.norm(vectors[:, i])) * norm_ones
128
+ if vectors[0, i] != 0:
129
+ vectors[:, i] = -1 * vectors[:, i] * np.sign(vectors[0, i])
130
+
131
+ # Normalize the rows of the eigenvectors. Samples should lie on the unit
132
+ # hypersphere centered at the origin. This transforms the samples in the
133
+ # embedding space to the space of partition matrices.
134
+ vectors = vectors / np.sqrt((vectors**2).sum(axis=1))[:, np.newaxis]
135
+
136
+ svd_restarts = 0
137
+ has_converged = False
138
+
139
+ # If there is an exception we try to randomize and rerun SVD again
140
+ # do this max_svd_restarts times.
141
+ while (svd_restarts < max_svd_restarts) and not has_converged:
142
+
143
+ # Initialize first column of rotation matrix with a row of the
144
+ # eigenvectors
145
+ rotation = np.zeros((n_components, n_components))
146
+ rotation[:, 0] = vectors[random_state.randint(n_samples), :].T
147
+
148
+ # To initialize the rest of the rotation matrix, find the rows
149
+ # of the eigenvectors that are as orthogonal to each other as
150
+ # possible
151
+ c = np.zeros(n_samples)
152
+ for j in range(1, n_components):
153
+ # Accumulate c to ensure row is as orthogonal as possible to
154
+ # previous picks as well as current one
155
+ c += np.abs(np.dot(vectors, rotation[:, j - 1]))
156
+ rotation[:, j] = vectors[c.argmin(), :].T
157
+
158
+ last_objective_value = 0.0
159
+ n_iter = 0
160
+
161
+ while not has_converged:
162
+ n_iter += 1
163
+
164
+ t_discrete = np.dot(vectors, rotation)
165
+
166
+ labels = t_discrete.argmax(axis=1)
167
+ vectors_discrete = csc_matrix(
168
+ (np.ones(len(labels)), (np.arange(0, n_samples), labels)),
169
+ shape=(n_samples, n_components),
170
+ )
171
+
172
+ t_svd = vectors_discrete.T * vectors
173
+
174
+ try:
175
+ U, S, Vh = np.linalg.svd(t_svd)
176
+ except LinAlgError:
177
+ svd_restarts += 1
178
+ print("SVD did not converge, randomizing and trying again")
179
+ break
180
+
181
+ ncut_value = 2.0 * (n_samples - S.sum())
182
+ if (abs(ncut_value - last_objective_value) < eps) or (n_iter > n_iter_max):
183
+ has_converged = True
184
+ else:
185
+ # otherwise calculate rotation and continue
186
+ last_objective_value = ncut_value
187
+ rotation = np.dot(Vh.T, U.T)
188
+
189
+ if not has_converged:
190
+ raise LinAlgError("SVD did not converge")
191
+ return labels
192
+
193
+
194
+ def spectral_clustering(
195
+ affinity,
196
+ *,
197
+ n_clusters=8,
198
+ n_components=None,
199
+ eigen_solver=None,
200
+ random_state=None,
201
+ n_init=10,
202
+ eigen_tol="auto",
203
+ assign_labels="kmeans",
204
+ verbose=False,
205
+ ):
206
+ """Apply clustering to a projection of the normalized Laplacian.
207
+
208
+ In practice Spectral Clustering is very useful when the structure of
209
+ the individual clusters is highly non-convex or more generally when
210
+ a measure of the center and spread of the cluster is not a suitable
211
+ description of the complete cluster. For instance, when clusters are
212
+ nested circles on the 2D plane.
213
+
214
+ If affinity is the adjacency matrix of a graph, this method can be
215
+ used to find normalized graph cuts [1]_, [2]_.
216
+
217
+ Read more in the :ref:`User Guide <spectral_clustering>`.
218
+
219
+ Parameters
220
+ ----------
221
+ affinity : {array-like, sparse matrix} of shape (n_samples, n_samples)
222
+ The affinity matrix describing the relationship of the samples to
223
+ embed. **Must be symmetric**.
224
+
225
+ Possible examples:
226
+ - adjacency matrix of a graph,
227
+ - heat kernel of the pairwise distance matrix of the samples,
228
+ - symmetric k-nearest neighbours connectivity matrix of the samples.
229
+
230
+ n_clusters : int, default=None
231
+ Number of clusters to extract.
232
+
233
+ n_components : int, default=n_clusters
234
+ Number of eigenvectors to use for the spectral embedding.
235
+
236
+ eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'}
237
+ The eigenvalue decomposition method. If None then ``'arpack'`` is used.
238
+ See [4]_ for more details regarding ``'lobpcg'``.
239
+ Eigensolver ``'amg'`` runs ``'lobpcg'`` with optional
240
+ Algebraic MultiGrid preconditioning and requires pyamg to be installed.
241
+ It can be faster on very large sparse problems [6]_ and [7]_.
242
+
243
+ random_state : int, RandomState instance, default=None
244
+ A pseudo random number generator used for the initialization
245
+ of the lobpcg eigenvectors decomposition when `eigen_solver ==
246
+ 'amg'`, and for the K-Means initialization. Use an int to make
247
+ the results deterministic across calls (See
248
+ :term:`Glossary <random_state>`).
249
+
250
+ .. note::
251
+ When using `eigen_solver == 'amg'`,
252
+ it is necessary to also fix the global numpy seed with
253
+ `np.random.seed(int)` to get deterministic results. See
254
+ https://github.com/pyamg/pyamg/issues/139 for further
255
+ information.
256
+
257
+ n_init : int, default=10
258
+ Number of time the k-means algorithm will be run with different
259
+ centroid seeds. The final results will be the best output of n_init
260
+ consecutive runs in terms of inertia. Only used if
261
+ ``assign_labels='kmeans'``.
262
+
263
+ eigen_tol : float, default="auto"
264
+ Stopping criterion for eigendecomposition of the Laplacian matrix.
265
+ If `eigen_tol="auto"` then the passed tolerance will depend on the
266
+ `eigen_solver`:
267
+
268
+ - If `eigen_solver="arpack"`, then `eigen_tol=0.0`;
269
+ - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then
270
+ `eigen_tol=None` which configures the underlying `lobpcg` solver to
271
+ automatically resolve the value according to their heuristics. See,
272
+ :func:`scipy.sparse.linalg.lobpcg` for details.
273
+
274
+ Note that when using `eigen_solver="lobpcg"` or `eigen_solver="amg"`
275
+ values of `tol<1e-5` may lead to convergence issues and should be
276
+ avoided.
277
+
278
+ .. versionadded:: 1.2
279
+ Added 'auto' option.
280
+
281
+ assign_labels : {'kmeans', 'discretize', 'cluster_qr'}, default='kmeans'
282
+ The strategy to use to assign labels in the embedding
283
+ space. There are three ways to assign labels after the Laplacian
284
+ embedding. k-means can be applied and is a popular choice. But it can
285
+ also be sensitive to initialization. Discretization is another
286
+ approach which is less sensitive to random initialization [3]_.
287
+ The cluster_qr method [5]_ directly extracts clusters from eigenvectors
288
+ in spectral clustering. In contrast to k-means and discretization, cluster_qr
289
+ has no tuning parameters and is not an iterative method, yet may outperform
290
+ k-means and discretization in terms of both quality and speed.
291
+
292
+ .. versionchanged:: 1.1
293
+ Added new labeling method 'cluster_qr'.
294
+
295
+ verbose : bool, default=False
296
+ Verbosity mode.
297
+
298
+ .. versionadded:: 0.24
299
+
300
+ Returns
301
+ -------
302
+ labels : array of integers, shape: n_samples
303
+ The labels of the clusters.
304
+
305
+ Notes
306
+ -----
307
+ The graph should contain only one connected component, elsewhere
308
+ the results make little sense.
309
+
310
+ This algorithm solves the normalized cut for `k=2`: it is a
311
+ normalized spectral clustering.
312
+
313
+ References
314
+ ----------
315
+
316
+ .. [1] :doi:`Normalized cuts and image segmentation, 2000
317
+ Jianbo Shi, Jitendra Malik
318
+ <10.1109/34.868688>`
319
+
320
+ .. [2] :doi:`A Tutorial on Spectral Clustering, 2007
321
+ Ulrike von Luxburg
322
+ <10.1007/s11222-007-9033-z>`
323
+
324
+ .. [3] `Multiclass spectral clustering, 2003
325
+ Stella X. Yu, Jianbo Shi
326
+ <https://people.eecs.berkeley.edu/~jordan/courses/281B-spring04/readings/yu-shi.pdf>`_
327
+
328
+ .. [4] :doi:`Toward the Optimal Preconditioned Eigensolver:
329
+ Locally Optimal Block Preconditioned Conjugate Gradient Method, 2001
330
+ A. V. Knyazev
331
+ SIAM Journal on Scientific Computing 23, no. 2, pp. 517-541.
332
+ <10.1137/S1064827500366124>`
333
+
334
+ .. [5] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019
335
+ Anil Damle, Victor Minden, Lexing Ying
336
+ <10.1093/imaiai/iay008>`
337
+
338
+ .. [6] :doi:`Multiscale Spectral Image Segmentation Multiscale preconditioning
339
+ for computing eigenvalues of graph Laplacians in image segmentation, 2006
340
+ Andrew Knyazev
341
+ <10.13140/RG.2.2.35280.02565>`
342
+
343
+ .. [7] :doi:`Preconditioned spectral clustering for stochastic block partition
344
+ streaming graph challenge (Preliminary version at arXiv.)
345
+ David Zhuzhunashvili, Andrew Knyazev
346
+ <10.1109/HPEC.2017.8091045>`
347
+ """
348
+ if assign_labels not in ("kmeans", "discretize", "cluster_qr"):
349
+ raise ValueError(
350
+ "The 'assign_labels' parameter should be "
351
+ "'kmeans' or 'discretize', or 'cluster_qr', "
352
+ f"but {assign_labels!r} was given"
353
+ )
354
+ if isinstance(affinity, np.matrix):
355
+ raise TypeError(
356
+ "spectral_clustering does not support passing in affinity as an "
357
+ "np.matrix. Please convert to a numpy array with np.asarray. For "
358
+ "more information see: "
359
+ "https://numpy.org/doc/stable/reference/generated/numpy.matrix.html", # noqa
360
+ )
361
+
362
+ random_state = check_random_state(random_state)
363
+ n_components = n_clusters if n_components is None else n_components
364
+
365
+ # We now obtain the real valued solution matrix to the
366
+ # relaxed Ncut problem, solving the eigenvalue problem
367
+ # L_sym x = lambda x and recovering u = D^-1/2 x.
368
+ # The first eigenvector is constant only for fully connected graphs
369
+ # and should be kept for spectral clustering (drop_first = False)
370
+ # See spectral_embedding documentation.
371
+ maps = spectral_embedding(
372
+ affinity,
373
+ n_components=n_components,
374
+ eigen_solver=eigen_solver,
375
+ random_state=random_state,
376
+ eigen_tol=eigen_tol,
377
+ drop_first=False,
378
+ )
379
+ if verbose:
380
+ print(f"Computing label assignment using {assign_labels}")
381
+
382
+ if assign_labels == "kmeans":
383
+ _, labels, _ = k_means(
384
+ maps, n_clusters, random_state=random_state, n_init=n_init, verbose=verbose
385
+ )
386
+ elif assign_labels == "cluster_qr":
387
+ labels = cluster_qr(maps)
388
+ else:
389
+ labels = discretize(maps, random_state=random_state)
390
+
391
+ return labels
392
+
393
+
394
+ class SpectralClustering(ClusterMixin, BaseEstimator):
395
+ """Apply clustering to a projection of the normalized Laplacian.
396
+
397
+ In practice Spectral Clustering is very useful when the structure of
398
+ the individual clusters is highly non-convex, or more generally when
399
+ a measure of the center and spread of the cluster is not a suitable
400
+ description of the complete cluster, such as when clusters are
401
+ nested circles on the 2D plane.
402
+
403
+ If the affinity matrix is the adjacency matrix of a graph, this method
404
+ can be used to find normalized graph cuts [1]_, [2]_.
405
+
406
+ When calling ``fit``, an affinity matrix is constructed using either
407
+ a kernel function such the Gaussian (aka RBF) kernel with Euclidean
408
+ distance ``d(X, X)``::
409
+
410
+ np.exp(-gamma * d(X,X) ** 2)
411
+
412
+ or a k-nearest neighbors connectivity matrix.
413
+
414
+ Alternatively, a user-provided affinity matrix can be specified by
415
+ setting ``affinity='precomputed'``.
416
+
417
+ Read more in the :ref:`User Guide <spectral_clustering>`.
418
+
419
+ Parameters
420
+ ----------
421
+ n_clusters : int, default=8
422
+ The dimension of the projection subspace.
423
+
424
+ eigen_solver : {'arpack', 'lobpcg', 'amg'}, default=None
425
+ The eigenvalue decomposition strategy to use. AMG requires pyamg
426
+ to be installed. It can be faster on very large, sparse problems,
427
+ but may also lead to instabilities. If None, then ``'arpack'`` is
428
+ used. See [4]_ for more details regarding `'lobpcg'`.
429
+
430
+ n_components : int, default=None
431
+ Number of eigenvectors to use for the spectral embedding. If None,
432
+ defaults to `n_clusters`.
433
+
434
+ random_state : int, RandomState instance, default=None
435
+ A pseudo random number generator used for the initialization
436
+ of the lobpcg eigenvectors decomposition when `eigen_solver ==
437
+ 'amg'`, and for the K-Means initialization. Use an int to make
438
+ the results deterministic across calls (See
439
+ :term:`Glossary <random_state>`).
440
+
441
+ .. note::
442
+ When using `eigen_solver == 'amg'`,
443
+ it is necessary to also fix the global numpy seed with
444
+ `np.random.seed(int)` to get deterministic results. See
445
+ https://github.com/pyamg/pyamg/issues/139 for further
446
+ information.
447
+
448
+ n_init : int, default=10
449
+ Number of time the k-means algorithm will be run with different
450
+ centroid seeds. The final results will be the best output of n_init
451
+ consecutive runs in terms of inertia. Only used if
452
+ ``assign_labels='kmeans'``.
453
+
454
+ gamma : float, default=1.0
455
+ Kernel coefficient for rbf, poly, sigmoid, laplacian and chi2 kernels.
456
+ Ignored for ``affinity='nearest_neighbors'``.
457
+
458
+ affinity : str or callable, default='rbf'
459
+ How to construct the affinity matrix.
460
+ - 'nearest_neighbors': construct the affinity matrix by computing a
461
+ graph of nearest neighbors.
462
+ - 'rbf': construct the affinity matrix using a radial basis function
463
+ (RBF) kernel.
464
+ - 'precomputed': interpret ``X`` as a precomputed affinity matrix,
465
+ where larger values indicate greater similarity between instances.
466
+ - 'precomputed_nearest_neighbors': interpret ``X`` as a sparse graph
467
+ of precomputed distances, and construct a binary affinity matrix
468
+ from the ``n_neighbors`` nearest neighbors of each instance.
469
+ - one of the kernels supported by
470
+ :func:`~sklearn.metrics.pairwise_kernels`.
471
+
472
+ Only kernels that produce similarity scores (non-negative values that
473
+ increase with similarity) should be used. This property is not checked
474
+ by the clustering algorithm.
475
+
476
+ n_neighbors : int, default=10
477
+ Number of neighbors to use when constructing the affinity matrix using
478
+ the nearest neighbors method. Ignored for ``affinity='rbf'``.
479
+
480
+ eigen_tol : float, default="auto"
481
+ Stopping criterion for eigendecomposition of the Laplacian matrix.
482
+ If `eigen_tol="auto"` then the passed tolerance will depend on the
483
+ `eigen_solver`:
484
+
485
+ - If `eigen_solver="arpack"`, then `eigen_tol=0.0`;
486
+ - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then
487
+ `eigen_tol=None` which configures the underlying `lobpcg` solver to
488
+ automatically resolve the value according to their heuristics. See,
489
+ :func:`scipy.sparse.linalg.lobpcg` for details.
490
+
491
+ Note that when using `eigen_solver="lobpcg"` or `eigen_solver="amg"`
492
+ values of `tol<1e-5` may lead to convergence issues and should be
493
+ avoided.
494
+
495
+ .. versionadded:: 1.2
496
+ Added 'auto' option.
497
+
498
+ assign_labels : {'kmeans', 'discretize', 'cluster_qr'}, default='kmeans'
499
+ The strategy for assigning labels in the embedding space. There are two
500
+ ways to assign labels after the Laplacian embedding. k-means is a
501
+ popular choice, but it can be sensitive to initialization.
502
+ Discretization is another approach which is less sensitive to random
503
+ initialization [3]_.
504
+ The cluster_qr method [5]_ directly extract clusters from eigenvectors
505
+ in spectral clustering. In contrast to k-means and discretization, cluster_qr
506
+ has no tuning parameters and runs no iterations, yet may outperform
507
+ k-means and discretization in terms of both quality and speed.
508
+
509
+ .. versionchanged:: 1.1
510
+ Added new labeling method 'cluster_qr'.
511
+
512
+ degree : float, default=3
513
+ Degree of the polynomial kernel. Ignored by other kernels.
514
+
515
+ coef0 : float, default=1
516
+ Zero coefficient for polynomial and sigmoid kernels.
517
+ Ignored by other kernels.
518
+
519
+ kernel_params : dict of str to any, default=None
520
+ Parameters (keyword arguments) and values for kernel passed as
521
+ callable object. Ignored by other kernels.
522
+
523
+ n_jobs : int, default=None
524
+ The number of parallel jobs to run when `affinity='nearest_neighbors'`
525
+ or `affinity='precomputed_nearest_neighbors'`. The neighbors search
526
+ will be done in parallel.
527
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
528
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
529
+ for more details.
530
+
531
+ verbose : bool, default=False
532
+ Verbosity mode.
533
+
534
+ .. versionadded:: 0.24
535
+
536
+ Attributes
537
+ ----------
538
+ affinity_matrix_ : array-like of shape (n_samples, n_samples)
539
+ Affinity matrix used for clustering. Available only after calling
540
+ ``fit``.
541
+
542
+ labels_ : ndarray of shape (n_samples,)
543
+ Labels of each point
544
+
545
+ n_features_in_ : int
546
+ Number of features seen during :term:`fit`.
547
+
548
+ .. versionadded:: 0.24
549
+
550
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
551
+ Names of features seen during :term:`fit`. Defined only when `X`
552
+ has feature names that are all strings.
553
+
554
+ .. versionadded:: 1.0
555
+
556
+ See Also
557
+ --------
558
+ sklearn.cluster.KMeans : K-Means clustering.
559
+ sklearn.cluster.DBSCAN : Density-Based Spatial Clustering of
560
+ Applications with Noise.
561
+
562
+ Notes
563
+ -----
564
+ A distance matrix for which 0 indicates identical elements and high values
565
+ indicate very dissimilar elements can be transformed into an affinity /
566
+ similarity matrix that is well-suited for the algorithm by
567
+ applying the Gaussian (aka RBF, heat) kernel::
568
+
569
+ np.exp(- dist_matrix ** 2 / (2. * delta ** 2))
570
+
571
+ where ``delta`` is a free parameter representing the width of the Gaussian
572
+ kernel.
573
+
574
+ An alternative is to take a symmetric version of the k-nearest neighbors
575
+ connectivity matrix of the points.
576
+
577
+ If the pyamg package is installed, it is used: this greatly
578
+ speeds up computation.
579
+
580
+ References
581
+ ----------
582
+ .. [1] :doi:`Normalized cuts and image segmentation, 2000
583
+ Jianbo Shi, Jitendra Malik
584
+ <10.1109/34.868688>`
585
+
586
+ .. [2] :doi:`A Tutorial on Spectral Clustering, 2007
587
+ Ulrike von Luxburg
588
+ <10.1007/s11222-007-9033-z>`
589
+
590
+ .. [3] `Multiclass spectral clustering, 2003
591
+ Stella X. Yu, Jianbo Shi
592
+ <https://people.eecs.berkeley.edu/~jordan/courses/281B-spring04/readings/yu-shi.pdf>`_
593
+
594
+ .. [4] :doi:`Toward the Optimal Preconditioned Eigensolver:
595
+ Locally Optimal Block Preconditioned Conjugate Gradient Method, 2001
596
+ A. V. Knyazev
597
+ SIAM Journal on Scientific Computing 23, no. 2, pp. 517-541.
598
+ <10.1137/S1064827500366124>`
599
+
600
+ .. [5] :doi:`Simple, direct, and efficient multi-way spectral clustering, 2019
601
+ Anil Damle, Victor Minden, Lexing Ying
602
+ <10.1093/imaiai/iay008>`
603
+
604
+ Examples
605
+ --------
606
+ >>> from sklearn.cluster import SpectralClustering
607
+ >>> import numpy as np
608
+ >>> X = np.array([[1, 1], [2, 1], [1, 0],
609
+ ... [4, 7], [3, 5], [3, 6]])
610
+ >>> clustering = SpectralClustering(n_clusters=2,
611
+ ... assign_labels='discretize',
612
+ ... random_state=0).fit(X)
613
+ >>> clustering.labels_
614
+ array([1, 1, 1, 0, 0, 0])
615
+ >>> clustering
616
+ SpectralClustering(assign_labels='discretize', n_clusters=2,
617
+ random_state=0)
618
+ """
619
+
620
+ _parameter_constraints: dict = {
621
+ "n_clusters": [Interval(Integral, 1, None, closed="left")],
622
+ "eigen_solver": [StrOptions({"arpack", "lobpcg", "amg"}), None],
623
+ "n_components": [Interval(Integral, 1, None, closed="left"), None],
624
+ "random_state": ["random_state"],
625
+ "n_init": [Interval(Integral, 1, None, closed="left")],
626
+ "gamma": [Interval(Real, 0, None, closed="left")],
627
+ "affinity": [
628
+ callable,
629
+ StrOptions(
630
+ set(KERNEL_PARAMS)
631
+ | {"nearest_neighbors", "precomputed", "precomputed_nearest_neighbors"}
632
+ ),
633
+ ],
634
+ "n_neighbors": [Interval(Integral, 1, None, closed="left")],
635
+ "eigen_tol": [
636
+ Interval(Real, 0.0, None, closed="left"),
637
+ StrOptions({"auto"}),
638
+ ],
639
+ "assign_labels": [StrOptions({"kmeans", "discretize", "cluster_qr"})],
640
+ "degree": [Interval(Integral, 0, None, closed="left")],
641
+ "coef0": [Interval(Real, None, None, closed="neither")],
642
+ "kernel_params": [dict, None],
643
+ "n_jobs": [Integral, None],
644
+ "verbose": ["verbose"],
645
+ }
646
+
647
+ def __init__(
648
+ self,
649
+ n_clusters=8,
650
+ *,
651
+ eigen_solver=None,
652
+ n_components=None,
653
+ random_state=None,
654
+ n_init=10,
655
+ gamma=1.0,
656
+ affinity="rbf",
657
+ n_neighbors=10,
658
+ eigen_tol="auto",
659
+ assign_labels="kmeans",
660
+ degree=3,
661
+ coef0=1,
662
+ kernel_params=None,
663
+ n_jobs=None,
664
+ verbose=False,
665
+ ):
666
+ self.n_clusters = n_clusters
667
+ self.eigen_solver = eigen_solver
668
+ self.n_components = n_components
669
+ self.random_state = random_state
670
+ self.n_init = n_init
671
+ self.gamma = gamma
672
+ self.affinity = affinity
673
+ self.n_neighbors = n_neighbors
674
+ self.eigen_tol = eigen_tol
675
+ self.assign_labels = assign_labels
676
+ self.degree = degree
677
+ self.coef0 = coef0
678
+ self.kernel_params = kernel_params
679
+ self.n_jobs = n_jobs
680
+ self.verbose = verbose
681
+
682
+ def fit(self, X, y=None):
683
+ """Perform spectral clustering from features, or affinity matrix.
684
+
685
+ Parameters
686
+ ----------
687
+ X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
688
+ (n_samples, n_samples)
689
+ Training instances to cluster, similarities / affinities between
690
+ instances if ``affinity='precomputed'``, or distances between
691
+ instances if ``affinity='precomputed_nearest_neighbors``. If a
692
+ sparse matrix is provided in a format other than ``csr_matrix``,
693
+ ``csc_matrix``, or ``coo_matrix``, it will be converted into a
694
+ sparse ``csr_matrix``.
695
+
696
+ y : Ignored
697
+ Not used, present here for API consistency by convention.
698
+
699
+ Returns
700
+ -------
701
+ self : object
702
+ A fitted instance of the estimator.
703
+ """
704
+ self._validate_params()
705
+
706
+ X = self._validate_data(
707
+ X,
708
+ accept_sparse=["csr", "csc", "coo"],
709
+ dtype=np.float64,
710
+ ensure_min_samples=2,
711
+ )
712
+ allow_squared = self.affinity in [
713
+ "precomputed",
714
+ "precomputed_nearest_neighbors",
715
+ ]
716
+ if X.shape[0] == X.shape[1] and not allow_squared:
717
+ warnings.warn(
718
+ "The spectral clustering API has changed. ``fit``"
719
+ "now constructs an affinity matrix from data. To use"
720
+ " a custom affinity matrix, "
721
+ "set ``affinity=precomputed``."
722
+ )
723
+
724
+ if self.affinity == "nearest_neighbors":
725
+ connectivity = kneighbors_graph(
726
+ X, n_neighbors=self.n_neighbors, include_self=True, n_jobs=self.n_jobs
727
+ )
728
+ self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T)
729
+ elif self.affinity == "precomputed_nearest_neighbors":
730
+ estimator = NearestNeighbors(
731
+ n_neighbors=self.n_neighbors, n_jobs=self.n_jobs, metric="precomputed"
732
+ ).fit(X)
733
+ connectivity = estimator.kneighbors_graph(X=X, mode="connectivity")
734
+ self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T)
735
+ elif self.affinity == "precomputed":
736
+ self.affinity_matrix_ = X
737
+ else:
738
+ params = self.kernel_params
739
+ if params is None:
740
+ params = {}
741
+ if not callable(self.affinity):
742
+ params["gamma"] = self.gamma
743
+ params["degree"] = self.degree
744
+ params["coef0"] = self.coef0
745
+ self.affinity_matrix_ = pairwise_kernels(
746
+ X, metric=self.affinity, filter_params=True, **params
747
+ )
748
+
749
+ random_state = check_random_state(self.random_state)
750
+ self.labels_ = spectral_clustering(
751
+ self.affinity_matrix_,
752
+ n_clusters=self.n_clusters,
753
+ n_components=self.n_components,
754
+ eigen_solver=self.eigen_solver,
755
+ random_state=random_state,
756
+ n_init=self.n_init,
757
+ eigen_tol=self.eigen_tol,
758
+ assign_labels=self.assign_labels,
759
+ verbose=self.verbose,
760
+ )
761
+ return self
762
+
763
+ def fit_predict(self, X, y=None):
764
+ """Perform spectral clustering on `X` and return cluster labels.
765
+
766
+ Parameters
767
+ ----------
768
+ X : {array-like, sparse matrix} of shape (n_samples, n_features) or \
769
+ (n_samples, n_samples)
770
+ Training instances to cluster, similarities / affinities between
771
+ instances if ``affinity='precomputed'``, or distances between
772
+ instances if ``affinity='precomputed_nearest_neighbors``. If a
773
+ sparse matrix is provided in a format other than ``csr_matrix``,
774
+ ``csc_matrix``, or ``coo_matrix``, it will be converted into a
775
+ sparse ``csr_matrix``.
776
+
777
+ y : Ignored
778
+ Not used, present here for API consistency by convention.
779
+
780
+ Returns
781
+ -------
782
+ labels : ndarray of shape (n_samples,)
783
+ Cluster labels.
784
+ """
785
+ return super().fit_predict(X, y)
786
+
787
+ def _more_tags(self):
788
+ return {
789
+ "pairwise": self.affinity
790
+ in ["precomputed", "precomputed_nearest_neighbors"]
791
+ }
videollama2/lib/python3.10/site-packages/sklearn/ensemble/__pycache__/_base.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/ensemble/__pycache__/_iforest.cpython-310.pyc ADDED
Binary file (16.7 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/feature_selection/__init__.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The :mod:`sklearn.feature_selection` module implements feature selection
3
+ algorithms. It currently includes univariate filter selection methods and the
4
+ recursive feature elimination algorithm.
5
+ """
6
+
7
+ from ._univariate_selection import chi2
8
+ from ._univariate_selection import f_classif
9
+ from ._univariate_selection import f_oneway
10
+ from ._univariate_selection import f_regression
11
+ from ._univariate_selection import r_regression
12
+ from ._univariate_selection import SelectPercentile
13
+ from ._univariate_selection import SelectKBest
14
+ from ._univariate_selection import SelectFpr
15
+ from ._univariate_selection import SelectFdr
16
+ from ._univariate_selection import SelectFwe
17
+ from ._univariate_selection import GenericUnivariateSelect
18
+
19
+ from ._variance_threshold import VarianceThreshold
20
+
21
+ from ._rfe import RFE
22
+ from ._rfe import RFECV
23
+
24
+ from ._from_model import SelectFromModel
25
+
26
+ from ._sequential import SequentialFeatureSelector
27
+
28
+ from ._mutual_info import mutual_info_regression, mutual_info_classif
29
+
30
+ from ._base import SelectorMixin
31
+
32
+
33
+ __all__ = [
34
+ "GenericUnivariateSelect",
35
+ "SequentialFeatureSelector",
36
+ "RFE",
37
+ "RFECV",
38
+ "SelectFdr",
39
+ "SelectFpr",
40
+ "SelectFwe",
41
+ "SelectKBest",
42
+ "SelectFromModel",
43
+ "SelectPercentile",
44
+ "VarianceThreshold",
45
+ "chi2",
46
+ "f_classif",
47
+ "f_oneway",
48
+ "f_regression",
49
+ "r_regression",
50
+ "mutual_info_classif",
51
+ "mutual_info_regression",
52
+ "SelectorMixin",
53
+ ]
videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_from_model.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors: Gilles Louppe, Mathieu Blondel, Maheshakya Wijewardena
2
+ # License: BSD 3 clause
3
+
4
+ from copy import deepcopy
5
+
6
+ import numpy as np
7
+ from numbers import Integral, Real
8
+
9
+ from ._base import SelectorMixin
10
+ from ._base import _get_feature_importances
11
+ from ..base import BaseEstimator, clone, MetaEstimatorMixin
12
+ from ..utils._tags import _safe_tags
13
+ from ..utils.validation import check_is_fitted, check_scalar, _num_features
14
+ from ..utils._param_validation import HasMethods, Interval, Options
15
+
16
+ from ..exceptions import NotFittedError
17
+ from ..utils.metaestimators import available_if
18
+
19
+
20
+ def _calculate_threshold(estimator, importances, threshold):
21
+ """Interpret the threshold value"""
22
+
23
+ if threshold is None:
24
+ # determine default from estimator
25
+ est_name = estimator.__class__.__name__
26
+ is_l1_penalized = hasattr(estimator, "penalty") and estimator.penalty == "l1"
27
+ is_lasso = "Lasso" in est_name
28
+ is_elasticnet_l1_penalized = "ElasticNet" in est_name and (
29
+ (hasattr(estimator, "l1_ratio_") and np.isclose(estimator.l1_ratio_, 1.0))
30
+ or (hasattr(estimator, "l1_ratio") and np.isclose(estimator.l1_ratio, 1.0))
31
+ )
32
+ if is_l1_penalized or is_lasso or is_elasticnet_l1_penalized:
33
+ # the natural default threshold is 0 when l1 penalty was used
34
+ threshold = 1e-5
35
+ else:
36
+ threshold = "mean"
37
+
38
+ if isinstance(threshold, str):
39
+ if "*" in threshold:
40
+ scale, reference = threshold.split("*")
41
+ scale = float(scale.strip())
42
+ reference = reference.strip()
43
+
44
+ if reference == "median":
45
+ reference = np.median(importances)
46
+ elif reference == "mean":
47
+ reference = np.mean(importances)
48
+ else:
49
+ raise ValueError("Unknown reference: " + reference)
50
+
51
+ threshold = scale * reference
52
+
53
+ elif threshold == "median":
54
+ threshold = np.median(importances)
55
+
56
+ elif threshold == "mean":
57
+ threshold = np.mean(importances)
58
+
59
+ else:
60
+ raise ValueError(
61
+ "Expected threshold='mean' or threshold='median' got %s" % threshold
62
+ )
63
+
64
+ else:
65
+ threshold = float(threshold)
66
+
67
+ return threshold
68
+
69
+
70
+ def _estimator_has(attr):
71
+ """Check if we can delegate a method to the underlying estimator.
72
+
73
+ First, we check the fitted estimator if available, otherwise we
74
+ check the unfitted estimator.
75
+ """
76
+ return lambda self: (
77
+ hasattr(self.estimator_, attr)
78
+ if hasattr(self, "estimator_")
79
+ else hasattr(self.estimator, attr)
80
+ )
81
+
82
+
83
+ class SelectFromModel(MetaEstimatorMixin, SelectorMixin, BaseEstimator):
84
+ """Meta-transformer for selecting features based on importance weights.
85
+
86
+ .. versionadded:: 0.17
87
+
88
+ Read more in the :ref:`User Guide <select_from_model>`.
89
+
90
+ Parameters
91
+ ----------
92
+ estimator : object
93
+ The base estimator from which the transformer is built.
94
+ This can be both a fitted (if ``prefit`` is set to True)
95
+ or a non-fitted estimator. The estimator should have a
96
+ ``feature_importances_`` or ``coef_`` attribute after fitting.
97
+ Otherwise, the ``importance_getter`` parameter should be used.
98
+
99
+ threshold : str or float, default=None
100
+ The threshold value to use for feature selection. Features whose
101
+ absolute importance value is greater or equal are kept while the others
102
+ are discarded. If "median" (resp. "mean"), then the ``threshold`` value
103
+ is the median (resp. the mean) of the feature importances. A scaling
104
+ factor (e.g., "1.25*mean") may also be used. If None and if the
105
+ estimator has a parameter penalty set to l1, either explicitly
106
+ or implicitly (e.g, Lasso), the threshold used is 1e-5.
107
+ Otherwise, "mean" is used by default.
108
+
109
+ prefit : bool, default=False
110
+ Whether a prefit model is expected to be passed into the constructor
111
+ directly or not.
112
+ If `True`, `estimator` must be a fitted estimator.
113
+ If `False`, `estimator` is fitted and updated by calling
114
+ `fit` and `partial_fit`, respectively.
115
+
116
+ norm_order : non-zero int, inf, -inf, default=1
117
+ Order of the norm used to filter the vectors of coefficients below
118
+ ``threshold`` in the case where the ``coef_`` attribute of the
119
+ estimator is of dimension 2.
120
+
121
+ max_features : int, callable, default=None
122
+ The maximum number of features to select.
123
+
124
+ - If an integer, then it specifies the maximum number of features to
125
+ allow.
126
+ - If a callable, then it specifies how to calculate the maximum number of
127
+ features allowed by using the output of `max_features(X)`.
128
+ - If `None`, then all features are kept.
129
+
130
+ To only select based on ``max_features``, set ``threshold=-np.inf``.
131
+
132
+ .. versionadded:: 0.20
133
+ .. versionchanged:: 1.1
134
+ `max_features` accepts a callable.
135
+
136
+ importance_getter : str or callable, default='auto'
137
+ If 'auto', uses the feature importance either through a ``coef_``
138
+ attribute or ``feature_importances_`` attribute of estimator.
139
+
140
+ Also accepts a string that specifies an attribute name/path
141
+ for extracting feature importance (implemented with `attrgetter`).
142
+ For example, give `regressor_.coef_` in case of
143
+ :class:`~sklearn.compose.TransformedTargetRegressor` or
144
+ `named_steps.clf.feature_importances_` in case of
145
+ :class:`~sklearn.pipeline.Pipeline` with its last step named `clf`.
146
+
147
+ If `callable`, overrides the default feature importance getter.
148
+ The callable is passed with the fitted estimator and it should
149
+ return importance for each feature.
150
+
151
+ .. versionadded:: 0.24
152
+
153
+ Attributes
154
+ ----------
155
+ estimator_ : estimator
156
+ The base estimator from which the transformer is built. This attribute
157
+ exist only when `fit` has been called.
158
+
159
+ - If `prefit=True`, it is a deep copy of `estimator`.
160
+ - If `prefit=False`, it is a clone of `estimator` and fit on the data
161
+ passed to `fit` or `partial_fit`.
162
+
163
+ n_features_in_ : int
164
+ Number of features seen during :term:`fit`. Only defined if the
165
+ underlying estimator exposes such an attribute when fit.
166
+
167
+ .. versionadded:: 0.24
168
+
169
+ max_features_ : int
170
+ Maximum number of features calculated during :term:`fit`. Only defined
171
+ if the ``max_features`` is not `None`.
172
+
173
+ - If `max_features` is an `int`, then `max_features_ = max_features`.
174
+ - If `max_features` is a callable, then `max_features_ = max_features(X)`.
175
+
176
+ .. versionadded:: 1.1
177
+
178
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
179
+ Names of features seen during :term:`fit`. Defined only when `X`
180
+ has feature names that are all strings.
181
+
182
+ .. versionadded:: 1.0
183
+
184
+ threshold_ : float
185
+ The threshold value used for feature selection.
186
+
187
+ See Also
188
+ --------
189
+ RFE : Recursive feature elimination based on importance weights.
190
+ RFECV : Recursive feature elimination with built-in cross-validated
191
+ selection of the best number of features.
192
+ SequentialFeatureSelector : Sequential cross-validation based feature
193
+ selection. Does not rely on importance weights.
194
+
195
+ Notes
196
+ -----
197
+ Allows NaN/Inf in the input if the underlying estimator does as well.
198
+
199
+ Examples
200
+ --------
201
+ >>> from sklearn.feature_selection import SelectFromModel
202
+ >>> from sklearn.linear_model import LogisticRegression
203
+ >>> X = [[ 0.87, -1.34, 0.31 ],
204
+ ... [-2.79, -0.02, -0.85 ],
205
+ ... [-1.34, -0.48, -2.55 ],
206
+ ... [ 1.92, 1.48, 0.65 ]]
207
+ >>> y = [0, 1, 0, 1]
208
+ >>> selector = SelectFromModel(estimator=LogisticRegression()).fit(X, y)
209
+ >>> selector.estimator_.coef_
210
+ array([[-0.3252302 , 0.83462377, 0.49750423]])
211
+ >>> selector.threshold_
212
+ 0.55245...
213
+ >>> selector.get_support()
214
+ array([False, True, False])
215
+ >>> selector.transform(X)
216
+ array([[-1.34],
217
+ [-0.02],
218
+ [-0.48],
219
+ [ 1.48]])
220
+
221
+ Using a callable to create a selector that can use no more than half
222
+ of the input features.
223
+
224
+ >>> def half_callable(X):
225
+ ... return round(len(X[0]) / 2)
226
+ >>> half_selector = SelectFromModel(estimator=LogisticRegression(),
227
+ ... max_features=half_callable)
228
+ >>> _ = half_selector.fit(X, y)
229
+ >>> half_selector.max_features_
230
+ 2
231
+ """
232
+
233
+ _parameter_constraints: dict = {
234
+ "estimator": [HasMethods("fit")],
235
+ "threshold": [Interval(Real, None, None, closed="both"), str, None],
236
+ "prefit": ["boolean"],
237
+ "norm_order": [
238
+ Interval(Integral, None, -1, closed="right"),
239
+ Interval(Integral, 1, None, closed="left"),
240
+ Options(Real, {np.inf, -np.inf}),
241
+ ],
242
+ "max_features": [Interval(Integral, 0, None, closed="left"), callable, None],
243
+ "importance_getter": [str, callable],
244
+ }
245
+
246
+ def __init__(
247
+ self,
248
+ estimator,
249
+ *,
250
+ threshold=None,
251
+ prefit=False,
252
+ norm_order=1,
253
+ max_features=None,
254
+ importance_getter="auto",
255
+ ):
256
+ self.estimator = estimator
257
+ self.threshold = threshold
258
+ self.prefit = prefit
259
+ self.importance_getter = importance_getter
260
+ self.norm_order = norm_order
261
+ self.max_features = max_features
262
+
263
+ def _get_support_mask(self):
264
+ estimator = getattr(self, "estimator_", self.estimator)
265
+ max_features = getattr(self, "max_features_", self.max_features)
266
+
267
+ if self.prefit:
268
+ try:
269
+ check_is_fitted(self.estimator)
270
+ except NotFittedError as exc:
271
+ raise NotFittedError(
272
+ "When `prefit=True`, `estimator` is expected to be a fitted "
273
+ "estimator."
274
+ ) from exc
275
+ if callable(max_features):
276
+ # This branch is executed when `transform` is called directly and thus
277
+ # `max_features_` is not set and we fallback using `self.max_features`
278
+ # that is not validated
279
+ raise NotFittedError(
280
+ "When `prefit=True` and `max_features` is a callable, call `fit` "
281
+ "before calling `transform`."
282
+ )
283
+ elif max_features is not None and not isinstance(max_features, Integral):
284
+ raise ValueError(
285
+ f"`max_features` must be an integer. Got `max_features={max_features}` "
286
+ "instead."
287
+ )
288
+
289
+ scores = _get_feature_importances(
290
+ estimator=estimator,
291
+ getter=self.importance_getter,
292
+ transform_func="norm",
293
+ norm_order=self.norm_order,
294
+ )
295
+ threshold = _calculate_threshold(estimator, scores, self.threshold)
296
+ if self.max_features is not None:
297
+ mask = np.zeros_like(scores, dtype=bool)
298
+ candidate_indices = np.argsort(-scores, kind="mergesort")[:max_features]
299
+ mask[candidate_indices] = True
300
+ else:
301
+ mask = np.ones_like(scores, dtype=bool)
302
+ mask[scores < threshold] = False
303
+ return mask
304
+
305
+ def _check_max_features(self, X):
306
+ if self.max_features is not None:
307
+ n_features = _num_features(X)
308
+
309
+ if callable(self.max_features):
310
+ max_features = self.max_features(X)
311
+ else: # int
312
+ max_features = self.max_features
313
+
314
+ check_scalar(
315
+ max_features,
316
+ "max_features",
317
+ Integral,
318
+ min_val=0,
319
+ max_val=n_features,
320
+ )
321
+ self.max_features_ = max_features
322
+
323
+ def fit(self, X, y=None, **fit_params):
324
+ """Fit the SelectFromModel meta-transformer.
325
+
326
+ Parameters
327
+ ----------
328
+ X : array-like of shape (n_samples, n_features)
329
+ The training input samples.
330
+
331
+ y : array-like of shape (n_samples,), default=None
332
+ The target values (integers that correspond to classes in
333
+ classification, real numbers in regression).
334
+
335
+ **fit_params : dict
336
+ Other estimator specific parameters.
337
+
338
+ Returns
339
+ -------
340
+ self : object
341
+ Fitted estimator.
342
+ """
343
+ self._validate_params()
344
+ self._check_max_features(X)
345
+
346
+ if self.prefit:
347
+ try:
348
+ check_is_fitted(self.estimator)
349
+ except NotFittedError as exc:
350
+ raise NotFittedError(
351
+ "When `prefit=True`, `estimator` is expected to be a fitted "
352
+ "estimator."
353
+ ) from exc
354
+ self.estimator_ = deepcopy(self.estimator)
355
+ else:
356
+ self.estimator_ = clone(self.estimator)
357
+ self.estimator_.fit(X, y, **fit_params)
358
+
359
+ if hasattr(self.estimator_, "feature_names_in_"):
360
+ self.feature_names_in_ = self.estimator_.feature_names_in_
361
+ else:
362
+ self._check_feature_names(X, reset=True)
363
+
364
+ return self
365
+
366
+ @property
367
+ def threshold_(self):
368
+ """Threshold value used for feature selection."""
369
+ scores = _get_feature_importances(
370
+ estimator=self.estimator_,
371
+ getter=self.importance_getter,
372
+ transform_func="norm",
373
+ norm_order=self.norm_order,
374
+ )
375
+ return _calculate_threshold(self.estimator, scores, self.threshold)
376
+
377
+ @available_if(_estimator_has("partial_fit"))
378
+ def partial_fit(self, X, y=None, **fit_params):
379
+ """Fit the SelectFromModel meta-transformer only once.
380
+
381
+ Parameters
382
+ ----------
383
+ X : array-like of shape (n_samples, n_features)
384
+ The training input samples.
385
+
386
+ y : array-like of shape (n_samples,), default=None
387
+ The target values (integers that correspond to classes in
388
+ classification, real numbers in regression).
389
+
390
+ **fit_params : dict
391
+ Other estimator specific parameters.
392
+
393
+ Returns
394
+ -------
395
+ self : object
396
+ Fitted estimator.
397
+ """
398
+ first_call = not hasattr(self, "estimator_")
399
+
400
+ if first_call:
401
+ self._validate_params()
402
+ self._check_max_features(X)
403
+
404
+ if self.prefit:
405
+ if first_call:
406
+ try:
407
+ check_is_fitted(self.estimator)
408
+ except NotFittedError as exc:
409
+ raise NotFittedError(
410
+ "When `prefit=True`, `estimator` is expected to be a fitted "
411
+ "estimator."
412
+ ) from exc
413
+ self.estimator_ = deepcopy(self.estimator)
414
+ return self
415
+
416
+ if first_call:
417
+ self.estimator_ = clone(self.estimator)
418
+ self.estimator_.partial_fit(X, y, **fit_params)
419
+
420
+ if hasattr(self.estimator_, "feature_names_in_"):
421
+ self.feature_names_in_ = self.estimator_.feature_names_in_
422
+ else:
423
+ self._check_feature_names(X, reset=first_call)
424
+
425
+ return self
426
+
427
+ @property
428
+ def n_features_in_(self):
429
+ """Number of features seen during `fit`."""
430
+ # For consistency with other estimators we raise a AttributeError so
431
+ # that hasattr() fails if the estimator isn't fitted.
432
+ try:
433
+ check_is_fitted(self)
434
+ except NotFittedError as nfe:
435
+ raise AttributeError(
436
+ "{} object has no n_features_in_ attribute.".format(
437
+ self.__class__.__name__
438
+ )
439
+ ) from nfe
440
+
441
+ return self.estimator_.n_features_in_
442
+
443
+ def _more_tags(self):
444
+ return {"allow_nan": _safe_tags(self.estimator, key="allow_nan")}
videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_mutual_info.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Author: Nikolay Mayorov <n59_ru@hotmail.com>
2
+ # License: 3-clause BSD
3
+
4
+ import numpy as np
5
+ from scipy.sparse import issparse
6
+ from scipy.special import digamma
7
+
8
+ from ..metrics.cluster import mutual_info_score
9
+ from ..neighbors import NearestNeighbors, KDTree
10
+ from ..preprocessing import scale
11
+ from ..utils import check_random_state
12
+ from ..utils.validation import check_array, check_X_y
13
+ from ..utils.multiclass import check_classification_targets
14
+
15
+
16
+ def _compute_mi_cc(x, y, n_neighbors):
17
+ """Compute mutual information between two continuous variables.
18
+
19
+ Parameters
20
+ ----------
21
+ x, y : ndarray, shape (n_samples,)
22
+ Samples of two continuous random variables, must have an identical
23
+ shape.
24
+
25
+ n_neighbors : int
26
+ Number of nearest neighbors to search for each point, see [1]_.
27
+
28
+ Returns
29
+ -------
30
+ mi : float
31
+ Estimated mutual information. If it turned out to be negative it is
32
+ replace by 0.
33
+
34
+ Notes
35
+ -----
36
+ True mutual information can't be negative. If its estimate by a numerical
37
+ method is negative, it means (providing the method is adequate) that the
38
+ mutual information is close to 0 and replacing it by 0 is a reasonable
39
+ strategy.
40
+
41
+ References
42
+ ----------
43
+ .. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
44
+ information". Phys. Rev. E 69, 2004.
45
+ """
46
+ n_samples = x.size
47
+
48
+ x = x.reshape((-1, 1))
49
+ y = y.reshape((-1, 1))
50
+ xy = np.hstack((x, y))
51
+
52
+ # Here we rely on NearestNeighbors to select the fastest algorithm.
53
+ nn = NearestNeighbors(metric="chebyshev", n_neighbors=n_neighbors)
54
+
55
+ nn.fit(xy)
56
+ radius = nn.kneighbors()[0]
57
+ radius = np.nextafter(radius[:, -1], 0)
58
+
59
+ # KDTree is explicitly fit to allow for the querying of number of
60
+ # neighbors within a specified radius
61
+ kd = KDTree(x, metric="chebyshev")
62
+ nx = kd.query_radius(x, radius, count_only=True, return_distance=False)
63
+ nx = np.array(nx) - 1.0
64
+
65
+ kd = KDTree(y, metric="chebyshev")
66
+ ny = kd.query_radius(y, radius, count_only=True, return_distance=False)
67
+ ny = np.array(ny) - 1.0
68
+
69
+ mi = (
70
+ digamma(n_samples)
71
+ + digamma(n_neighbors)
72
+ - np.mean(digamma(nx + 1))
73
+ - np.mean(digamma(ny + 1))
74
+ )
75
+
76
+ return max(0, mi)
77
+
78
+
79
+ def _compute_mi_cd(c, d, n_neighbors):
80
+ """Compute mutual information between continuous and discrete variables.
81
+
82
+ Parameters
83
+ ----------
84
+ c : ndarray, shape (n_samples,)
85
+ Samples of a continuous random variable.
86
+
87
+ d : ndarray, shape (n_samples,)
88
+ Samples of a discrete random variable.
89
+
90
+ n_neighbors : int
91
+ Number of nearest neighbors to search for each point, see [1]_.
92
+
93
+ Returns
94
+ -------
95
+ mi : float
96
+ Estimated mutual information. If it turned out to be negative it is
97
+ replace by 0.
98
+
99
+ Notes
100
+ -----
101
+ True mutual information can't be negative. If its estimate by a numerical
102
+ method is negative, it means (providing the method is adequate) that the
103
+ mutual information is close to 0 and replacing it by 0 is a reasonable
104
+ strategy.
105
+
106
+ References
107
+ ----------
108
+ .. [1] B. C. Ross "Mutual Information between Discrete and Continuous
109
+ Data Sets". PLoS ONE 9(2), 2014.
110
+ """
111
+ n_samples = c.shape[0]
112
+ c = c.reshape((-1, 1))
113
+
114
+ radius = np.empty(n_samples)
115
+ label_counts = np.empty(n_samples)
116
+ k_all = np.empty(n_samples)
117
+ nn = NearestNeighbors()
118
+ for label in np.unique(d):
119
+ mask = d == label
120
+ count = np.sum(mask)
121
+ if count > 1:
122
+ k = min(n_neighbors, count - 1)
123
+ nn.set_params(n_neighbors=k)
124
+ nn.fit(c[mask])
125
+ r = nn.kneighbors()[0]
126
+ radius[mask] = np.nextafter(r[:, -1], 0)
127
+ k_all[mask] = k
128
+ label_counts[mask] = count
129
+
130
+ # Ignore points with unique labels.
131
+ mask = label_counts > 1
132
+ n_samples = np.sum(mask)
133
+ label_counts = label_counts[mask]
134
+ k_all = k_all[mask]
135
+ c = c[mask]
136
+ radius = radius[mask]
137
+
138
+ kd = KDTree(c)
139
+ m_all = kd.query_radius(c, radius, count_only=True, return_distance=False)
140
+ m_all = np.array(m_all)
141
+
142
+ mi = (
143
+ digamma(n_samples)
144
+ + np.mean(digamma(k_all))
145
+ - np.mean(digamma(label_counts))
146
+ - np.mean(digamma(m_all))
147
+ )
148
+
149
+ return max(0, mi)
150
+
151
+
152
+ def _compute_mi(x, y, x_discrete, y_discrete, n_neighbors=3):
153
+ """Compute mutual information between two variables.
154
+
155
+ This is a simple wrapper which selects a proper function to call based on
156
+ whether `x` and `y` are discrete or not.
157
+ """
158
+ if x_discrete and y_discrete:
159
+ return mutual_info_score(x, y)
160
+ elif x_discrete and not y_discrete:
161
+ return _compute_mi_cd(y, x, n_neighbors)
162
+ elif not x_discrete and y_discrete:
163
+ return _compute_mi_cd(x, y, n_neighbors)
164
+ else:
165
+ return _compute_mi_cc(x, y, n_neighbors)
166
+
167
+
168
+ def _iterate_columns(X, columns=None):
169
+ """Iterate over columns of a matrix.
170
+
171
+ Parameters
172
+ ----------
173
+ X : ndarray or csc_matrix, shape (n_samples, n_features)
174
+ Matrix over which to iterate.
175
+
176
+ columns : iterable or None, default=None
177
+ Indices of columns to iterate over. If None, iterate over all columns.
178
+
179
+ Yields
180
+ ------
181
+ x : ndarray, shape (n_samples,)
182
+ Columns of `X` in dense format.
183
+ """
184
+ if columns is None:
185
+ columns = range(X.shape[1])
186
+
187
+ if issparse(X):
188
+ for i in columns:
189
+ x = np.zeros(X.shape[0])
190
+ start_ptr, end_ptr = X.indptr[i], X.indptr[i + 1]
191
+ x[X.indices[start_ptr:end_ptr]] = X.data[start_ptr:end_ptr]
192
+ yield x
193
+ else:
194
+ for i in columns:
195
+ yield X[:, i]
196
+
197
+
198
+ def _estimate_mi(
199
+ X,
200
+ y,
201
+ discrete_features="auto",
202
+ discrete_target=False,
203
+ n_neighbors=3,
204
+ copy=True,
205
+ random_state=None,
206
+ ):
207
+ """Estimate mutual information between the features and the target.
208
+
209
+ Parameters
210
+ ----------
211
+ X : array-like or sparse matrix, shape (n_samples, n_features)
212
+ Feature matrix.
213
+
214
+ y : array-like of shape (n_samples,)
215
+ Target vector.
216
+
217
+ discrete_features : {'auto', bool, array-like}, default='auto'
218
+ If bool, then determines whether to consider all features discrete
219
+ or continuous. If array, then it should be either a boolean mask
220
+ with shape (n_features,) or array with indices of discrete features.
221
+ If 'auto', it is assigned to False for dense `X` and to True for
222
+ sparse `X`.
223
+
224
+ discrete_target : bool, default=False
225
+ Whether to consider `y` as a discrete variable.
226
+
227
+ n_neighbors : int, default=3
228
+ Number of neighbors to use for MI estimation for continuous variables,
229
+ see [1]_ and [2]_. Higher values reduce variance of the estimation, but
230
+ could introduce a bias.
231
+
232
+ copy : bool, default=True
233
+ Whether to make a copy of the given data. If set to False, the initial
234
+ data will be overwritten.
235
+
236
+ random_state : int, RandomState instance or None, default=None
237
+ Determines random number generation for adding small noise to
238
+ continuous variables in order to remove repeated values.
239
+ Pass an int for reproducible results across multiple function calls.
240
+ See :term:`Glossary <random_state>`.
241
+
242
+ Returns
243
+ -------
244
+ mi : ndarray, shape (n_features,)
245
+ Estimated mutual information between each feature and the target.
246
+ A negative value will be replaced by 0.
247
+
248
+ References
249
+ ----------
250
+ .. [1] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
251
+ information". Phys. Rev. E 69, 2004.
252
+ .. [2] B. C. Ross "Mutual Information between Discrete and Continuous
253
+ Data Sets". PLoS ONE 9(2), 2014.
254
+ """
255
+ X, y = check_X_y(X, y, accept_sparse="csc", y_numeric=not discrete_target)
256
+ n_samples, n_features = X.shape
257
+
258
+ if isinstance(discrete_features, (str, bool)):
259
+ if isinstance(discrete_features, str):
260
+ if discrete_features == "auto":
261
+ discrete_features = issparse(X)
262
+ else:
263
+ raise ValueError("Invalid string value for discrete_features.")
264
+ discrete_mask = np.empty(n_features, dtype=bool)
265
+ discrete_mask.fill(discrete_features)
266
+ else:
267
+ discrete_features = check_array(discrete_features, ensure_2d=False)
268
+ if discrete_features.dtype != "bool":
269
+ discrete_mask = np.zeros(n_features, dtype=bool)
270
+ discrete_mask[discrete_features] = True
271
+ else:
272
+ discrete_mask = discrete_features
273
+
274
+ continuous_mask = ~discrete_mask
275
+ if np.any(continuous_mask) and issparse(X):
276
+ raise ValueError("Sparse matrix `X` can't have continuous features.")
277
+
278
+ rng = check_random_state(random_state)
279
+ if np.any(continuous_mask):
280
+ if copy:
281
+ X = X.copy()
282
+
283
+ X[:, continuous_mask] = scale(
284
+ X[:, continuous_mask], with_mean=False, copy=False
285
+ )
286
+
287
+ # Add small noise to continuous features as advised in Kraskov et. al.
288
+ X = X.astype(np.float64, copy=False)
289
+ means = np.maximum(1, np.mean(np.abs(X[:, continuous_mask]), axis=0))
290
+ X[:, continuous_mask] += (
291
+ 1e-10
292
+ * means
293
+ * rng.standard_normal(size=(n_samples, np.sum(continuous_mask)))
294
+ )
295
+
296
+ if not discrete_target:
297
+ y = scale(y, with_mean=False)
298
+ y += (
299
+ 1e-10
300
+ * np.maximum(1, np.mean(np.abs(y)))
301
+ * rng.standard_normal(size=n_samples)
302
+ )
303
+
304
+ mi = [
305
+ _compute_mi(x, y, discrete_feature, discrete_target, n_neighbors)
306
+ for x, discrete_feature in zip(_iterate_columns(X), discrete_mask)
307
+ ]
308
+
309
+ return np.array(mi)
310
+
311
+
312
+ def mutual_info_regression(
313
+ X, y, *, discrete_features="auto", n_neighbors=3, copy=True, random_state=None
314
+ ):
315
+ """Estimate mutual information for a continuous target variable.
316
+
317
+ Mutual information (MI) [1]_ between two random variables is a non-negative
318
+ value, which measures the dependency between the variables. It is equal
319
+ to zero if and only if two random variables are independent, and higher
320
+ values mean higher dependency.
321
+
322
+ The function relies on nonparametric methods based on entropy estimation
323
+ from k-nearest neighbors distances as described in [2]_ and [3]_. Both
324
+ methods are based on the idea originally proposed in [4]_.
325
+
326
+ It can be used for univariate features selection, read more in the
327
+ :ref:`User Guide <univariate_feature_selection>`.
328
+
329
+ Parameters
330
+ ----------
331
+ X : array-like or sparse matrix, shape (n_samples, n_features)
332
+ Feature matrix.
333
+
334
+ y : array-like of shape (n_samples,)
335
+ Target vector.
336
+
337
+ discrete_features : {'auto', bool, array-like}, default='auto'
338
+ If bool, then determines whether to consider all features discrete
339
+ or continuous. If array, then it should be either a boolean mask
340
+ with shape (n_features,) or array with indices of discrete features.
341
+ If 'auto', it is assigned to False for dense `X` and to True for
342
+ sparse `X`.
343
+
344
+ n_neighbors : int, default=3
345
+ Number of neighbors to use for MI estimation for continuous variables,
346
+ see [2]_ and [3]_. Higher values reduce variance of the estimation, but
347
+ could introduce a bias.
348
+
349
+ copy : bool, default=True
350
+ Whether to make a copy of the given data. If set to False, the initial
351
+ data will be overwritten.
352
+
353
+ random_state : int, RandomState instance or None, default=None
354
+ Determines random number generation for adding small noise to
355
+ continuous variables in order to remove repeated values.
356
+ Pass an int for reproducible results across multiple function calls.
357
+ See :term:`Glossary <random_state>`.
358
+
359
+ Returns
360
+ -------
361
+ mi : ndarray, shape (n_features,)
362
+ Estimated mutual information between each feature and the target.
363
+
364
+ Notes
365
+ -----
366
+ 1. The term "discrete features" is used instead of naming them
367
+ "categorical", because it describes the essence more accurately.
368
+ For example, pixel intensities of an image are discrete features
369
+ (but hardly categorical) and you will get better results if mark them
370
+ as such. Also note, that treating a continuous variable as discrete and
371
+ vice versa will usually give incorrect results, so be attentive about
372
+ that.
373
+ 2. True mutual information can't be negative. If its estimate turns out
374
+ to be negative, it is replaced by zero.
375
+
376
+ References
377
+ ----------
378
+ .. [1] `Mutual Information
379
+ <https://en.wikipedia.org/wiki/Mutual_information>`_
380
+ on Wikipedia.
381
+ .. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
382
+ information". Phys. Rev. E 69, 2004.
383
+ .. [3] B. C. Ross "Mutual Information between Discrete and Continuous
384
+ Data Sets". PLoS ONE 9(2), 2014.
385
+ .. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
386
+ of a Random Vector", Probl. Peredachi Inf., 23:2 (1987), 9-16
387
+ """
388
+ return _estimate_mi(X, y, discrete_features, False, n_neighbors, copy, random_state)
389
+
390
+
391
+ def mutual_info_classif(
392
+ X, y, *, discrete_features="auto", n_neighbors=3, copy=True, random_state=None
393
+ ):
394
+ """Estimate mutual information for a discrete target variable.
395
+
396
+ Mutual information (MI) [1]_ between two random variables is a non-negative
397
+ value, which measures the dependency between the variables. It is equal
398
+ to zero if and only if two random variables are independent, and higher
399
+ values mean higher dependency.
400
+
401
+ The function relies on nonparametric methods based on entropy estimation
402
+ from k-nearest neighbors distances as described in [2]_ and [3]_. Both
403
+ methods are based on the idea originally proposed in [4]_.
404
+
405
+ It can be used for univariate features selection, read more in the
406
+ :ref:`User Guide <univariate_feature_selection>`.
407
+
408
+ Parameters
409
+ ----------
410
+ X : array-like or sparse matrix, shape (n_samples, n_features)
411
+ Feature matrix.
412
+
413
+ y : array-like of shape (n_samples,)
414
+ Target vector.
415
+
416
+ discrete_features : {'auto', bool, array-like}, default='auto'
417
+ If bool, then determines whether to consider all features discrete
418
+ or continuous. If array, then it should be either a boolean mask
419
+ with shape (n_features,) or array with indices of discrete features.
420
+ If 'auto', it is assigned to False for dense `X` and to True for
421
+ sparse `X`.
422
+
423
+ n_neighbors : int, default=3
424
+ Number of neighbors to use for MI estimation for continuous variables,
425
+ see [2]_ and [3]_. Higher values reduce variance of the estimation, but
426
+ could introduce a bias.
427
+
428
+ copy : bool, default=True
429
+ Whether to make a copy of the given data. If set to False, the initial
430
+ data will be overwritten.
431
+
432
+ random_state : int, RandomState instance or None, default=None
433
+ Determines random number generation for adding small noise to
434
+ continuous variables in order to remove repeated values.
435
+ Pass an int for reproducible results across multiple function calls.
436
+ See :term:`Glossary <random_state>`.
437
+
438
+ Returns
439
+ -------
440
+ mi : ndarray, shape (n_features,)
441
+ Estimated mutual information between each feature and the target.
442
+
443
+ Notes
444
+ -----
445
+ 1. The term "discrete features" is used instead of naming them
446
+ "categorical", because it describes the essence more accurately.
447
+ For example, pixel intensities of an image are discrete features
448
+ (but hardly categorical) and you will get better results if mark them
449
+ as such. Also note, that treating a continuous variable as discrete and
450
+ vice versa will usually give incorrect results, so be attentive about
451
+ that.
452
+ 2. True mutual information can't be negative. If its estimate turns out
453
+ to be negative, it is replaced by zero.
454
+
455
+ References
456
+ ----------
457
+ .. [1] `Mutual Information
458
+ <https://en.wikipedia.org/wiki/Mutual_information>`_
459
+ on Wikipedia.
460
+ .. [2] A. Kraskov, H. Stogbauer and P. Grassberger, "Estimating mutual
461
+ information". Phys. Rev. E 69, 2004.
462
+ .. [3] B. C. Ross "Mutual Information between Discrete and Continuous
463
+ Data Sets". PLoS ONE 9(2), 2014.
464
+ .. [4] L. F. Kozachenko, N. N. Leonenko, "Sample Estimate of the Entropy
465
+ of a Random Vector:, Probl. Peredachi Inf., 23:2 (1987), 9-16
466
+ """
467
+ check_classification_targets(y)
468
+ return _estimate_mi(X, y, discrete_features, True, n_neighbors, copy, random_state)
videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_rfe.py ADDED
@@ -0,0 +1,765 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
2
+ # Vincent Michel <vincent.michel@inria.fr>
3
+ # Gilles Louppe <g.louppe@gmail.com>
4
+ #
5
+ # License: BSD 3 clause
6
+
7
+ """Recursive feature elimination for feature ranking"""
8
+
9
+ import numpy as np
10
+ from numbers import Integral, Real
11
+ from joblib import effective_n_jobs
12
+
13
+
14
+ from ..utils.metaestimators import available_if
15
+ from ..utils.metaestimators import _safe_split
16
+ from ..utils._param_validation import HasMethods, Interval
17
+ from ..utils._tags import _safe_tags
18
+ from ..utils.validation import check_is_fitted
19
+ from ..utils.parallel import delayed, Parallel
20
+ from ..base import BaseEstimator
21
+ from ..base import MetaEstimatorMixin
22
+ from ..base import clone
23
+ from ..base import is_classifier
24
+ from ..model_selection import check_cv
25
+ from ..model_selection._validation import _score
26
+ from ..metrics import check_scoring
27
+ from ._base import SelectorMixin
28
+ from ._base import _get_feature_importances
29
+
30
+
31
+ def _rfe_single_fit(rfe, estimator, X, y, train, test, scorer):
32
+ """
33
+ Return the score for a fit across one fold.
34
+ """
35
+ X_train, y_train = _safe_split(estimator, X, y, train)
36
+ X_test, y_test = _safe_split(estimator, X, y, test, train)
37
+ return rfe._fit(
38
+ X_train,
39
+ y_train,
40
+ lambda estimator, features: _score(
41
+ estimator, X_test[:, features], y_test, scorer
42
+ ),
43
+ ).scores_
44
+
45
+
46
+ def _estimator_has(attr):
47
+ """Check if we can delegate a method to the underlying estimator.
48
+
49
+ First, we check the first fitted estimator if available, otherwise we
50
+ check the unfitted estimator.
51
+ """
52
+ return lambda self: (
53
+ hasattr(self.estimator_, attr)
54
+ if hasattr(self, "estimator_")
55
+ else hasattr(self.estimator, attr)
56
+ )
57
+
58
+
59
+ class RFE(SelectorMixin, MetaEstimatorMixin, BaseEstimator):
60
+ """Feature ranking with recursive feature elimination.
61
+
62
+ Given an external estimator that assigns weights to features (e.g., the
63
+ coefficients of a linear model), the goal of recursive feature elimination
64
+ (RFE) is to select features by recursively considering smaller and smaller
65
+ sets of features. First, the estimator is trained on the initial set of
66
+ features and the importance of each feature is obtained either through
67
+ any specific attribute or callable.
68
+ Then, the least important features are pruned from current set of features.
69
+ That procedure is recursively repeated on the pruned set until the desired
70
+ number of features to select is eventually reached.
71
+
72
+ Read more in the :ref:`User Guide <rfe>`.
73
+
74
+ Parameters
75
+ ----------
76
+ estimator : ``Estimator`` instance
77
+ A supervised learning estimator with a ``fit`` method that provides
78
+ information about feature importance
79
+ (e.g. `coef_`, `feature_importances_`).
80
+
81
+ n_features_to_select : int or float, default=None
82
+ The number of features to select. If `None`, half of the features are
83
+ selected. If integer, the parameter is the absolute number of features
84
+ to select. If float between 0 and 1, it is the fraction of features to
85
+ select.
86
+
87
+ .. versionchanged:: 0.24
88
+ Added float values for fractions.
89
+
90
+ step : int or float, default=1
91
+ If greater than or equal to 1, then ``step`` corresponds to the
92
+ (integer) number of features to remove at each iteration.
93
+ If within (0.0, 1.0), then ``step`` corresponds to the percentage
94
+ (rounded down) of features to remove at each iteration.
95
+
96
+ verbose : int, default=0
97
+ Controls verbosity of output.
98
+
99
+ importance_getter : str or callable, default='auto'
100
+ If 'auto', uses the feature importance either through a `coef_`
101
+ or `feature_importances_` attributes of estimator.
102
+
103
+ Also accepts a string that specifies an attribute name/path
104
+ for extracting feature importance (implemented with `attrgetter`).
105
+ For example, give `regressor_.coef_` in case of
106
+ :class:`~sklearn.compose.TransformedTargetRegressor` or
107
+ `named_steps.clf.feature_importances_` in case of
108
+ class:`~sklearn.pipeline.Pipeline` with its last step named `clf`.
109
+
110
+ If `callable`, overrides the default feature importance getter.
111
+ The callable is passed with the fitted estimator and it should
112
+ return importance for each feature.
113
+
114
+ .. versionadded:: 0.24
115
+
116
+ Attributes
117
+ ----------
118
+ classes_ : ndarray of shape (n_classes,)
119
+ The classes labels. Only available when `estimator` is a classifier.
120
+
121
+ estimator_ : ``Estimator`` instance
122
+ The fitted estimator used to select features.
123
+
124
+ n_features_ : int
125
+ The number of selected features.
126
+
127
+ n_features_in_ : int
128
+ Number of features seen during :term:`fit`. Only defined if the
129
+ underlying estimator exposes such an attribute when fit.
130
+
131
+ .. versionadded:: 0.24
132
+
133
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
134
+ Names of features seen during :term:`fit`. Defined only when `X`
135
+ has feature names that are all strings.
136
+
137
+ .. versionadded:: 1.0
138
+
139
+ ranking_ : ndarray of shape (n_features,)
140
+ The feature ranking, such that ``ranking_[i]`` corresponds to the
141
+ ranking position of the i-th feature. Selected (i.e., estimated
142
+ best) features are assigned rank 1.
143
+
144
+ support_ : ndarray of shape (n_features,)
145
+ The mask of selected features.
146
+
147
+ See Also
148
+ --------
149
+ RFECV : Recursive feature elimination with built-in cross-validated
150
+ selection of the best number of features.
151
+ SelectFromModel : Feature selection based on thresholds of importance
152
+ weights.
153
+ SequentialFeatureSelector : Sequential cross-validation based feature
154
+ selection. Does not rely on importance weights.
155
+
156
+ Notes
157
+ -----
158
+ Allows NaN/Inf in the input if the underlying estimator does as well.
159
+
160
+ References
161
+ ----------
162
+
163
+ .. [1] Guyon, I., Weston, J., Barnhill, S., & Vapnik, V., "Gene selection
164
+ for cancer classification using support vector machines",
165
+ Mach. Learn., 46(1-3), 389--422, 2002.
166
+
167
+ Examples
168
+ --------
169
+ The following example shows how to retrieve the 5 most informative
170
+ features in the Friedman #1 dataset.
171
+
172
+ >>> from sklearn.datasets import make_friedman1
173
+ >>> from sklearn.feature_selection import RFE
174
+ >>> from sklearn.svm import SVR
175
+ >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
176
+ >>> estimator = SVR(kernel="linear")
177
+ >>> selector = RFE(estimator, n_features_to_select=5, step=1)
178
+ >>> selector = selector.fit(X, y)
179
+ >>> selector.support_
180
+ array([ True, True, True, True, True, False, False, False, False,
181
+ False])
182
+ >>> selector.ranking_
183
+ array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5])
184
+ """
185
+
186
+ _parameter_constraints: dict = {
187
+ "estimator": [HasMethods(["fit"])],
188
+ "n_features_to_select": [
189
+ None,
190
+ Interval(Real, 0, 1, closed="right"),
191
+ Interval(Integral, 0, None, closed="neither"),
192
+ ],
193
+ "step": [
194
+ Interval(Integral, 0, None, closed="neither"),
195
+ Interval(Real, 0, 1, closed="neither"),
196
+ ],
197
+ "verbose": ["verbose"],
198
+ "importance_getter": [str, callable],
199
+ }
200
+
201
+ def __init__(
202
+ self,
203
+ estimator,
204
+ *,
205
+ n_features_to_select=None,
206
+ step=1,
207
+ verbose=0,
208
+ importance_getter="auto",
209
+ ):
210
+ self.estimator = estimator
211
+ self.n_features_to_select = n_features_to_select
212
+ self.step = step
213
+ self.importance_getter = importance_getter
214
+ self.verbose = verbose
215
+
216
+ @property
217
+ def _estimator_type(self):
218
+ return self.estimator._estimator_type
219
+
220
+ @property
221
+ def classes_(self):
222
+ """Classes labels available when `estimator` is a classifier.
223
+
224
+ Returns
225
+ -------
226
+ ndarray of shape (n_classes,)
227
+ """
228
+ return self.estimator_.classes_
229
+
230
+ def fit(self, X, y, **fit_params):
231
+ """Fit the RFE model and then the underlying estimator on the selected features.
232
+
233
+ Parameters
234
+ ----------
235
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
236
+ The training input samples.
237
+
238
+ y : array-like of shape (n_samples,)
239
+ The target values.
240
+
241
+ **fit_params : dict
242
+ Additional parameters passed to the `fit` method of the underlying
243
+ estimator.
244
+
245
+ Returns
246
+ -------
247
+ self : object
248
+ Fitted estimator.
249
+ """
250
+ self._validate_params()
251
+ return self._fit(X, y, **fit_params)
252
+
253
+ def _fit(self, X, y, step_score=None, **fit_params):
254
+ # Parameter step_score controls the calculation of self.scores_
255
+ # step_score is not exposed to users
256
+ # and is used when implementing RFECV
257
+ # self.scores_ will not be calculated when calling _fit through fit
258
+
259
+ tags = self._get_tags()
260
+ X, y = self._validate_data(
261
+ X,
262
+ y,
263
+ accept_sparse="csc",
264
+ ensure_min_features=2,
265
+ force_all_finite=not tags.get("allow_nan", True),
266
+ multi_output=True,
267
+ )
268
+
269
+ # Initialization
270
+ n_features = X.shape[1]
271
+ if self.n_features_to_select is None:
272
+ n_features_to_select = n_features // 2
273
+ elif isinstance(self.n_features_to_select, Integral): # int
274
+ n_features_to_select = self.n_features_to_select
275
+ else: # float
276
+ n_features_to_select = int(n_features * self.n_features_to_select)
277
+
278
+ if 0.0 < self.step < 1.0:
279
+ step = int(max(1, self.step * n_features))
280
+ else:
281
+ step = int(self.step)
282
+
283
+ support_ = np.ones(n_features, dtype=bool)
284
+ ranking_ = np.ones(n_features, dtype=int)
285
+
286
+ if step_score:
287
+ self.scores_ = []
288
+
289
+ # Elimination
290
+ while np.sum(support_) > n_features_to_select:
291
+ # Remaining features
292
+ features = np.arange(n_features)[support_]
293
+
294
+ # Rank the remaining features
295
+ estimator = clone(self.estimator)
296
+ if self.verbose > 0:
297
+ print("Fitting estimator with %d features." % np.sum(support_))
298
+
299
+ estimator.fit(X[:, features], y, **fit_params)
300
+
301
+ # Get importance and rank them
302
+ importances = _get_feature_importances(
303
+ estimator,
304
+ self.importance_getter,
305
+ transform_func="square",
306
+ )
307
+ ranks = np.argsort(importances)
308
+
309
+ # for sparse case ranks is matrix
310
+ ranks = np.ravel(ranks)
311
+
312
+ # Eliminate the worse features
313
+ threshold = min(step, np.sum(support_) - n_features_to_select)
314
+
315
+ # Compute step score on the previous selection iteration
316
+ # because 'estimator' must use features
317
+ # that have not been eliminated yet
318
+ if step_score:
319
+ self.scores_.append(step_score(estimator, features))
320
+ support_[features[ranks][:threshold]] = False
321
+ ranking_[np.logical_not(support_)] += 1
322
+
323
+ # Set final attributes
324
+ features = np.arange(n_features)[support_]
325
+ self.estimator_ = clone(self.estimator)
326
+ self.estimator_.fit(X[:, features], y, **fit_params)
327
+
328
+ # Compute step score when only n_features_to_select features left
329
+ if step_score:
330
+ self.scores_.append(step_score(self.estimator_, features))
331
+ self.n_features_ = support_.sum()
332
+ self.support_ = support_
333
+ self.ranking_ = ranking_
334
+
335
+ return self
336
+
337
+ @available_if(_estimator_has("predict"))
338
+ def predict(self, X):
339
+ """Reduce X to the selected features and predict using the estimator.
340
+
341
+ Parameters
342
+ ----------
343
+ X : array of shape [n_samples, n_features]
344
+ The input samples.
345
+
346
+ Returns
347
+ -------
348
+ y : array of shape [n_samples]
349
+ The predicted target values.
350
+ """
351
+ check_is_fitted(self)
352
+ return self.estimator_.predict(self.transform(X))
353
+
354
+ @available_if(_estimator_has("score"))
355
+ def score(self, X, y, **fit_params):
356
+ """Reduce X to the selected features and return the score of the estimator.
357
+
358
+ Parameters
359
+ ----------
360
+ X : array of shape [n_samples, n_features]
361
+ The input samples.
362
+
363
+ y : array of shape [n_samples]
364
+ The target values.
365
+
366
+ **fit_params : dict
367
+ Parameters to pass to the `score` method of the underlying
368
+ estimator.
369
+
370
+ .. versionadded:: 1.0
371
+
372
+ Returns
373
+ -------
374
+ score : float
375
+ Score of the underlying base estimator computed with the selected
376
+ features returned by `rfe.transform(X)` and `y`.
377
+ """
378
+ check_is_fitted(self)
379
+ return self.estimator_.score(self.transform(X), y, **fit_params)
380
+
381
+ def _get_support_mask(self):
382
+ check_is_fitted(self)
383
+ return self.support_
384
+
385
+ @available_if(_estimator_has("decision_function"))
386
+ def decision_function(self, X):
387
+ """Compute the decision function of ``X``.
388
+
389
+ Parameters
390
+ ----------
391
+ X : {array-like or sparse matrix} of shape (n_samples, n_features)
392
+ The input samples. Internally, it will be converted to
393
+ ``dtype=np.float32`` and if a sparse matrix is provided
394
+ to a sparse ``csr_matrix``.
395
+
396
+ Returns
397
+ -------
398
+ score : array, shape = [n_samples, n_classes] or [n_samples]
399
+ The decision function of the input samples. The order of the
400
+ classes corresponds to that in the attribute :term:`classes_`.
401
+ Regression and binary classification produce an array of shape
402
+ [n_samples].
403
+ """
404
+ check_is_fitted(self)
405
+ return self.estimator_.decision_function(self.transform(X))
406
+
407
+ @available_if(_estimator_has("predict_proba"))
408
+ def predict_proba(self, X):
409
+ """Predict class probabilities for X.
410
+
411
+ Parameters
412
+ ----------
413
+ X : {array-like or sparse matrix} of shape (n_samples, n_features)
414
+ The input samples. Internally, it will be converted to
415
+ ``dtype=np.float32`` and if a sparse matrix is provided
416
+ to a sparse ``csr_matrix``.
417
+
418
+ Returns
419
+ -------
420
+ p : array of shape (n_samples, n_classes)
421
+ The class probabilities of the input samples. The order of the
422
+ classes corresponds to that in the attribute :term:`classes_`.
423
+ """
424
+ check_is_fitted(self)
425
+ return self.estimator_.predict_proba(self.transform(X))
426
+
427
+ @available_if(_estimator_has("predict_log_proba"))
428
+ def predict_log_proba(self, X):
429
+ """Predict class log-probabilities for X.
430
+
431
+ Parameters
432
+ ----------
433
+ X : array of shape [n_samples, n_features]
434
+ The input samples.
435
+
436
+ Returns
437
+ -------
438
+ p : array of shape (n_samples, n_classes)
439
+ The class log-probabilities of the input samples. The order of the
440
+ classes corresponds to that in the attribute :term:`classes_`.
441
+ """
442
+ check_is_fitted(self)
443
+ return self.estimator_.predict_log_proba(self.transform(X))
444
+
445
+ def _more_tags(self):
446
+ return {
447
+ "poor_score": True,
448
+ "allow_nan": _safe_tags(self.estimator, key="allow_nan"),
449
+ "requires_y": True,
450
+ }
451
+
452
+
453
+ class RFECV(RFE):
454
+ """Recursive feature elimination with cross-validation to select features.
455
+
456
+ See glossary entry for :term:`cross-validation estimator`.
457
+
458
+ Read more in the :ref:`User Guide <rfe>`.
459
+
460
+ Parameters
461
+ ----------
462
+ estimator : ``Estimator`` instance
463
+ A supervised learning estimator with a ``fit`` method that provides
464
+ information about feature importance either through a ``coef_``
465
+ attribute or through a ``feature_importances_`` attribute.
466
+
467
+ step : int or float, default=1
468
+ If greater than or equal to 1, then ``step`` corresponds to the
469
+ (integer) number of features to remove at each iteration.
470
+ If within (0.0, 1.0), then ``step`` corresponds to the percentage
471
+ (rounded down) of features to remove at each iteration.
472
+ Note that the last iteration may remove fewer than ``step`` features in
473
+ order to reach ``min_features_to_select``.
474
+
475
+ min_features_to_select : int, default=1
476
+ The minimum number of features to be selected. This number of features
477
+ will always be scored, even if the difference between the original
478
+ feature count and ``min_features_to_select`` isn't divisible by
479
+ ``step``.
480
+
481
+ .. versionadded:: 0.20
482
+
483
+ cv : int, cross-validation generator or an iterable, default=None
484
+ Determines the cross-validation splitting strategy.
485
+ Possible inputs for cv are:
486
+
487
+ - None, to use the default 5-fold cross-validation,
488
+ - integer, to specify the number of folds.
489
+ - :term:`CV splitter`,
490
+ - An iterable yielding (train, test) splits as arrays of indices.
491
+
492
+ For integer/None inputs, if ``y`` is binary or multiclass,
493
+ :class:`~sklearn.model_selection.StratifiedKFold` is used. If the
494
+ estimator is a classifier or if ``y`` is neither binary nor multiclass,
495
+ :class:`~sklearn.model_selection.KFold` is used.
496
+
497
+ Refer :ref:`User Guide <cross_validation>` for the various
498
+ cross-validation strategies that can be used here.
499
+
500
+ .. versionchanged:: 0.22
501
+ ``cv`` default value of None changed from 3-fold to 5-fold.
502
+
503
+ scoring : str, callable or None, default=None
504
+ A string (see model evaluation documentation) or
505
+ a scorer callable object / function with signature
506
+ ``scorer(estimator, X, y)``.
507
+
508
+ verbose : int, default=0
509
+ Controls verbosity of output.
510
+
511
+ n_jobs : int or None, default=None
512
+ Number of cores to run in parallel while fitting across folds.
513
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
514
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
515
+ for more details.
516
+
517
+ .. versionadded:: 0.18
518
+
519
+ importance_getter : str or callable, default='auto'
520
+ If 'auto', uses the feature importance either through a `coef_`
521
+ or `feature_importances_` attributes of estimator.
522
+
523
+ Also accepts a string that specifies an attribute name/path
524
+ for extracting feature importance.
525
+ For example, give `regressor_.coef_` in case of
526
+ :class:`~sklearn.compose.TransformedTargetRegressor` or
527
+ `named_steps.clf.feature_importances_` in case of
528
+ :class:`~sklearn.pipeline.Pipeline` with its last step named `clf`.
529
+
530
+ If `callable`, overrides the default feature importance getter.
531
+ The callable is passed with the fitted estimator and it should
532
+ return importance for each feature.
533
+
534
+ .. versionadded:: 0.24
535
+
536
+ Attributes
537
+ ----------
538
+ classes_ : ndarray of shape (n_classes,)
539
+ The classes labels. Only available when `estimator` is a classifier.
540
+
541
+ estimator_ : ``Estimator`` instance
542
+ The fitted estimator used to select features.
543
+
544
+ cv_results_ : dict of ndarrays
545
+ A dict with keys:
546
+
547
+ split(k)_test_score : ndarray of shape (n_subsets_of_features,)
548
+ The cross-validation scores across (k)th fold.
549
+
550
+ mean_test_score : ndarray of shape (n_subsets_of_features,)
551
+ Mean of scores over the folds.
552
+
553
+ std_test_score : ndarray of shape (n_subsets_of_features,)
554
+ Standard deviation of scores over the folds.
555
+
556
+ .. versionadded:: 1.0
557
+
558
+ n_features_ : int
559
+ The number of selected features with cross-validation.
560
+
561
+ n_features_in_ : int
562
+ Number of features seen during :term:`fit`. Only defined if the
563
+ underlying estimator exposes such an attribute when fit.
564
+
565
+ .. versionadded:: 0.24
566
+
567
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
568
+ Names of features seen during :term:`fit`. Defined only when `X`
569
+ has feature names that are all strings.
570
+
571
+ .. versionadded:: 1.0
572
+
573
+ ranking_ : narray of shape (n_features,)
574
+ The feature ranking, such that `ranking_[i]`
575
+ corresponds to the ranking
576
+ position of the i-th feature.
577
+ Selected (i.e., estimated best)
578
+ features are assigned rank 1.
579
+
580
+ support_ : ndarray of shape (n_features,)
581
+ The mask of selected features.
582
+
583
+ See Also
584
+ --------
585
+ RFE : Recursive feature elimination.
586
+
587
+ Notes
588
+ -----
589
+ The size of all values in ``cv_results_`` is equal to
590
+ ``ceil((n_features - min_features_to_select) / step) + 1``,
591
+ where step is the number of features removed at each iteration.
592
+
593
+ Allows NaN/Inf in the input if the underlying estimator does as well.
594
+
595
+ References
596
+ ----------
597
+
598
+ .. [1] Guyon, I., Weston, J., Barnhill, S., & Vapnik, V., "Gene selection
599
+ for cancer classification using support vector machines",
600
+ Mach. Learn., 46(1-3), 389--422, 2002.
601
+
602
+ Examples
603
+ --------
604
+ The following example shows how to retrieve the a-priori not known 5
605
+ informative features in the Friedman #1 dataset.
606
+
607
+ >>> from sklearn.datasets import make_friedman1
608
+ >>> from sklearn.feature_selection import RFECV
609
+ >>> from sklearn.svm import SVR
610
+ >>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
611
+ >>> estimator = SVR(kernel="linear")
612
+ >>> selector = RFECV(estimator, step=1, cv=5)
613
+ >>> selector = selector.fit(X, y)
614
+ >>> selector.support_
615
+ array([ True, True, True, True, True, False, False, False, False,
616
+ False])
617
+ >>> selector.ranking_
618
+ array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5])
619
+ """
620
+
621
+ _parameter_constraints: dict = {
622
+ **RFE._parameter_constraints,
623
+ "min_features_to_select": [Interval(Integral, 0, None, closed="neither")],
624
+ "cv": ["cv_object"],
625
+ "scoring": [None, str, callable],
626
+ "n_jobs": [None, Integral],
627
+ }
628
+ _parameter_constraints.pop("n_features_to_select")
629
+
630
+ def __init__(
631
+ self,
632
+ estimator,
633
+ *,
634
+ step=1,
635
+ min_features_to_select=1,
636
+ cv=None,
637
+ scoring=None,
638
+ verbose=0,
639
+ n_jobs=None,
640
+ importance_getter="auto",
641
+ ):
642
+ self.estimator = estimator
643
+ self.step = step
644
+ self.importance_getter = importance_getter
645
+ self.cv = cv
646
+ self.scoring = scoring
647
+ self.verbose = verbose
648
+ self.n_jobs = n_jobs
649
+ self.min_features_to_select = min_features_to_select
650
+
651
+ def fit(self, X, y, groups=None):
652
+ """Fit the RFE model and automatically tune the number of selected features.
653
+
654
+ Parameters
655
+ ----------
656
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
657
+ Training vector, where `n_samples` is the number of samples and
658
+ `n_features` is the total number of features.
659
+
660
+ y : array-like of shape (n_samples,)
661
+ Target values (integers for classification, real numbers for
662
+ regression).
663
+
664
+ groups : array-like of shape (n_samples,) or None, default=None
665
+ Group labels for the samples used while splitting the dataset into
666
+ train/test set. Only used in conjunction with a "Group" :term:`cv`
667
+ instance (e.g., :class:`~sklearn.model_selection.GroupKFold`).
668
+
669
+ .. versionadded:: 0.20
670
+
671
+ Returns
672
+ -------
673
+ self : object
674
+ Fitted estimator.
675
+ """
676
+ self._validate_params()
677
+ tags = self._get_tags()
678
+ X, y = self._validate_data(
679
+ X,
680
+ y,
681
+ accept_sparse="csr",
682
+ ensure_min_features=2,
683
+ force_all_finite=not tags.get("allow_nan", True),
684
+ multi_output=True,
685
+ )
686
+
687
+ # Initialization
688
+ cv = check_cv(self.cv, y, classifier=is_classifier(self.estimator))
689
+ scorer = check_scoring(self.estimator, scoring=self.scoring)
690
+ n_features = X.shape[1]
691
+
692
+ if 0.0 < self.step < 1.0:
693
+ step = int(max(1, self.step * n_features))
694
+ else:
695
+ step = int(self.step)
696
+
697
+ # Build an RFE object, which will evaluate and score each possible
698
+ # feature count, down to self.min_features_to_select
699
+ rfe = RFE(
700
+ estimator=self.estimator,
701
+ n_features_to_select=self.min_features_to_select,
702
+ importance_getter=self.importance_getter,
703
+ step=self.step,
704
+ verbose=self.verbose,
705
+ )
706
+
707
+ # Determine the number of subsets of features by fitting across
708
+ # the train folds and choosing the "features_to_select" parameter
709
+ # that gives the least averaged error across all folds.
710
+
711
+ # Note that joblib raises a non-picklable error for bound methods
712
+ # even if n_jobs is set to 1 with the default multiprocessing
713
+ # backend.
714
+ # This branching is done so that to
715
+ # make sure that user code that sets n_jobs to 1
716
+ # and provides bound methods as scorers is not broken with the
717
+ # addition of n_jobs parameter in version 0.18.
718
+
719
+ if effective_n_jobs(self.n_jobs) == 1:
720
+ parallel, func = list, _rfe_single_fit
721
+ else:
722
+ parallel = Parallel(n_jobs=self.n_jobs)
723
+ func = delayed(_rfe_single_fit)
724
+
725
+ scores = parallel(
726
+ func(rfe, self.estimator, X, y, train, test, scorer)
727
+ for train, test in cv.split(X, y, groups)
728
+ )
729
+
730
+ scores = np.array(scores)
731
+ scores_sum = np.sum(scores, axis=0)
732
+ scores_sum_rev = scores_sum[::-1]
733
+ argmax_idx = len(scores_sum) - np.argmax(scores_sum_rev) - 1
734
+ n_features_to_select = max(
735
+ n_features - (argmax_idx * step), self.min_features_to_select
736
+ )
737
+
738
+ # Re-execute an elimination with best_k over the whole set
739
+ rfe = RFE(
740
+ estimator=self.estimator,
741
+ n_features_to_select=n_features_to_select,
742
+ step=self.step,
743
+ importance_getter=self.importance_getter,
744
+ verbose=self.verbose,
745
+ )
746
+
747
+ rfe.fit(X, y)
748
+
749
+ # Set final attributes
750
+ self.support_ = rfe.support_
751
+ self.n_features_ = rfe.n_features_
752
+ self.ranking_ = rfe.ranking_
753
+ self.estimator_ = clone(self.estimator)
754
+ self.estimator_.fit(self._transform(X), y)
755
+
756
+ # reverse to stay consistent with before
757
+ scores_rev = scores[:, ::-1]
758
+ self.cv_results_ = {}
759
+ self.cv_results_["mean_test_score"] = np.mean(scores_rev, axis=0)
760
+ self.cv_results_["std_test_score"] = np.std(scores_rev, axis=0)
761
+
762
+ for i in range(scores.shape[0]):
763
+ self.cv_results_[f"split{i}_test_score"] = scores_rev[i]
764
+
765
+ return self
videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_sequential.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Sequential feature selection
3
+ """
4
+ from numbers import Integral, Real
5
+
6
+ import numpy as np
7
+
8
+ import warnings
9
+
10
+ from ._base import SelectorMixin
11
+ from ..base import BaseEstimator, MetaEstimatorMixin, clone
12
+ from ..utils._param_validation import HasMethods, Hidden, Interval, StrOptions
13
+ from ..utils._tags import _safe_tags
14
+ from ..utils.validation import check_is_fitted
15
+ from ..model_selection import cross_val_score
16
+ from ..metrics import get_scorer_names
17
+
18
+
19
+ class SequentialFeatureSelector(SelectorMixin, MetaEstimatorMixin, BaseEstimator):
20
+ """Transformer that performs Sequential Feature Selection.
21
+
22
+ This Sequential Feature Selector adds (forward selection) or
23
+ removes (backward selection) features to form a feature subset in a
24
+ greedy fashion. At each stage, this estimator chooses the best feature to
25
+ add or remove based on the cross-validation score of an estimator. In
26
+ the case of unsupervised learning, this Sequential Feature Selector
27
+ looks only at the features (X), not the desired outputs (y).
28
+
29
+ Read more in the :ref:`User Guide <sequential_feature_selection>`.
30
+
31
+ .. versionadded:: 0.24
32
+
33
+ Parameters
34
+ ----------
35
+ estimator : estimator instance
36
+ An unfitted estimator.
37
+
38
+ n_features_to_select : "auto", int or float, default='warn'
39
+ If `"auto"`, the behaviour depends on the `tol` parameter:
40
+
41
+ - if `tol` is not `None`, then features are selected until the score
42
+ improvement does not exceed `tol`.
43
+ - otherwise, half of the features are selected.
44
+
45
+ If integer, the parameter is the absolute number of features to select.
46
+ If float between 0 and 1, it is the fraction of features to select.
47
+
48
+ .. versionadded:: 1.1
49
+ The option `"auto"` was added in version 1.1.
50
+
51
+ .. deprecated:: 1.1
52
+ The default changed from `None` to `"warn"` in 1.1 and will become
53
+ `"auto"` in 1.3. `None` and `'warn'` will be removed in 1.3.
54
+ To keep the same behaviour as `None`, set
55
+ `n_features_to_select="auto" and `tol=None`.
56
+
57
+ tol : float, default=None
58
+ If the score is not incremented by at least `tol` between two
59
+ consecutive feature additions or removals, stop adding or removing.
60
+
61
+ `tol` can be negative when removing features using `direction="backward"`.
62
+ It can be useful to reduce the number of features at the cost of a small
63
+ decrease in the score.
64
+
65
+ `tol` is enabled only when `n_features_to_select` is `"auto"`.
66
+
67
+ .. versionadded:: 1.1
68
+
69
+ direction : {'forward', 'backward'}, default='forward'
70
+ Whether to perform forward selection or backward selection.
71
+
72
+ scoring : str or callable, default=None
73
+ A single str (see :ref:`scoring_parameter`) or a callable
74
+ (see :ref:`scoring`) to evaluate the predictions on the test set.
75
+
76
+ NOTE that when using a custom scorer, it should return a single
77
+ value.
78
+
79
+ If None, the estimator's score method is used.
80
+
81
+ cv : int, cross-validation generator or an iterable, default=None
82
+ Determines the cross-validation splitting strategy.
83
+ Possible inputs for cv are:
84
+
85
+ - None, to use the default 5-fold cross validation,
86
+ - integer, to specify the number of folds in a `(Stratified)KFold`,
87
+ - :term:`CV splitter`,
88
+ - An iterable yielding (train, test) splits as arrays of indices.
89
+
90
+ For integer/None inputs, if the estimator is a classifier and ``y`` is
91
+ either binary or multiclass, :class:`StratifiedKFold` is used. In all
92
+ other cases, :class:`KFold` is used. These splitters are instantiated
93
+ with `shuffle=False` so the splits will be the same across calls.
94
+
95
+ Refer :ref:`User Guide <cross_validation>` for the various
96
+ cross-validation strategies that can be used here.
97
+
98
+ n_jobs : int, default=None
99
+ Number of jobs to run in parallel. When evaluating a new feature to
100
+ add or remove, the cross-validation procedure is parallel over the
101
+ folds.
102
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
103
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
104
+ for more details.
105
+
106
+ Attributes
107
+ ----------
108
+ n_features_in_ : int
109
+ Number of features seen during :term:`fit`. Only defined if the
110
+ underlying estimator exposes such an attribute when fit.
111
+
112
+ .. versionadded:: 0.24
113
+
114
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
115
+ Names of features seen during :term:`fit`. Defined only when `X`
116
+ has feature names that are all strings.
117
+
118
+ .. versionadded:: 1.0
119
+
120
+ n_features_to_select_ : int
121
+ The number of features that were selected.
122
+
123
+ support_ : ndarray of shape (n_features,), dtype=bool
124
+ The mask of selected features.
125
+
126
+ See Also
127
+ --------
128
+ GenericUnivariateSelect : Univariate feature selector with configurable
129
+ strategy.
130
+ RFE : Recursive feature elimination based on importance weights.
131
+ RFECV : Recursive feature elimination based on importance weights, with
132
+ automatic selection of the number of features.
133
+ SelectFromModel : Feature selection based on thresholds of importance
134
+ weights.
135
+
136
+ Examples
137
+ --------
138
+ >>> from sklearn.feature_selection import SequentialFeatureSelector
139
+ >>> from sklearn.neighbors import KNeighborsClassifier
140
+ >>> from sklearn.datasets import load_iris
141
+ >>> X, y = load_iris(return_X_y=True)
142
+ >>> knn = KNeighborsClassifier(n_neighbors=3)
143
+ >>> sfs = SequentialFeatureSelector(knn, n_features_to_select=3)
144
+ >>> sfs.fit(X, y)
145
+ SequentialFeatureSelector(estimator=KNeighborsClassifier(n_neighbors=3),
146
+ n_features_to_select=3)
147
+ >>> sfs.get_support()
148
+ array([ True, False, True, True])
149
+ >>> sfs.transform(X).shape
150
+ (150, 3)
151
+ """
152
+
153
+ _parameter_constraints: dict = {
154
+ "estimator": [HasMethods(["fit"])],
155
+ "n_features_to_select": [
156
+ StrOptions({"auto", "warn"}, deprecated={"warn"}),
157
+ Interval(Real, 0, 1, closed="right"),
158
+ Interval(Integral, 0, None, closed="neither"),
159
+ Hidden(None),
160
+ ],
161
+ "tol": [None, Interval(Real, None, None, closed="neither")],
162
+ "direction": [StrOptions({"forward", "backward"})],
163
+ "scoring": [None, StrOptions(set(get_scorer_names())), callable],
164
+ "cv": ["cv_object"],
165
+ "n_jobs": [None, Integral],
166
+ }
167
+
168
+ def __init__(
169
+ self,
170
+ estimator,
171
+ *,
172
+ n_features_to_select="warn",
173
+ tol=None,
174
+ direction="forward",
175
+ scoring=None,
176
+ cv=5,
177
+ n_jobs=None,
178
+ ):
179
+
180
+ self.estimator = estimator
181
+ self.n_features_to_select = n_features_to_select
182
+ self.tol = tol
183
+ self.direction = direction
184
+ self.scoring = scoring
185
+ self.cv = cv
186
+ self.n_jobs = n_jobs
187
+
188
+ def fit(self, X, y=None):
189
+ """Learn the features to select from X.
190
+
191
+ Parameters
192
+ ----------
193
+ X : array-like of shape (n_samples, n_features)
194
+ Training vectors, where `n_samples` is the number of samples and
195
+ `n_features` is the number of predictors.
196
+
197
+ y : array-like of shape (n_samples,), default=None
198
+ Target values. This parameter may be ignored for
199
+ unsupervised learning.
200
+
201
+ Returns
202
+ -------
203
+ self : object
204
+ Returns the instance itself.
205
+ """
206
+ self._validate_params()
207
+
208
+ # FIXME: to be removed in 1.3
209
+ if self.n_features_to_select in ("warn", None):
210
+ # for backwards compatibility
211
+ warnings.warn(
212
+ "Leaving `n_features_to_select` to "
213
+ "None is deprecated in 1.0 and will become 'auto' "
214
+ "in 1.3. To keep the same behaviour as with None "
215
+ "(i.e. select half of the features) and avoid "
216
+ "this warning, you should manually set "
217
+ "`n_features_to_select='auto'` and set tol=None "
218
+ "when creating an instance.",
219
+ FutureWarning,
220
+ )
221
+
222
+ tags = self._get_tags()
223
+ X = self._validate_data(
224
+ X,
225
+ accept_sparse="csc",
226
+ ensure_min_features=2,
227
+ force_all_finite=not tags.get("allow_nan", True),
228
+ )
229
+ n_features = X.shape[1]
230
+
231
+ # FIXME: to be fixed in 1.3
232
+ error_msg = (
233
+ "n_features_to_select must be either 'auto', 'warn', "
234
+ "None, an integer in [1, n_features - 1] "
235
+ "representing the absolute "
236
+ "number of features, or a float in (0, 1] "
237
+ "representing a percentage of features to "
238
+ f"select. Got {self.n_features_to_select}"
239
+ )
240
+ if self.n_features_to_select in ("warn", None):
241
+ if self.tol is not None:
242
+ raise ValueError("tol is only enabled if `n_features_to_select='auto'`")
243
+ self.n_features_to_select_ = n_features // 2
244
+ elif self.n_features_to_select == "auto":
245
+ if self.tol is not None:
246
+ # With auto feature selection, `n_features_to_select_` will be updated
247
+ # to `support_.sum()` after features are selected.
248
+ self.n_features_to_select_ = n_features - 1
249
+ else:
250
+ self.n_features_to_select_ = n_features // 2
251
+ elif isinstance(self.n_features_to_select, Integral):
252
+ if not 0 < self.n_features_to_select < n_features:
253
+ raise ValueError(error_msg)
254
+ self.n_features_to_select_ = self.n_features_to_select
255
+ elif isinstance(self.n_features_to_select, Real):
256
+ self.n_features_to_select_ = int(n_features * self.n_features_to_select)
257
+
258
+ if self.tol is not None and self.tol < 0 and self.direction == "forward":
259
+ raise ValueError("tol must be positive when doing forward selection")
260
+
261
+ cloned_estimator = clone(self.estimator)
262
+
263
+ # the current mask corresponds to the set of features:
264
+ # - that we have already *selected* if we do forward selection
265
+ # - that we have already *excluded* if we do backward selection
266
+ current_mask = np.zeros(shape=n_features, dtype=bool)
267
+ n_iterations = (
268
+ self.n_features_to_select_
269
+ if self.n_features_to_select == "auto" or self.direction == "forward"
270
+ else n_features - self.n_features_to_select_
271
+ )
272
+
273
+ old_score = -np.inf
274
+ is_auto_select = self.tol is not None and self.n_features_to_select == "auto"
275
+ for _ in range(n_iterations):
276
+ new_feature_idx, new_score = self._get_best_new_feature_score(
277
+ cloned_estimator, X, y, current_mask
278
+ )
279
+ if is_auto_select and ((new_score - old_score) < self.tol):
280
+ break
281
+
282
+ old_score = new_score
283
+ current_mask[new_feature_idx] = True
284
+
285
+ if self.direction == "backward":
286
+ current_mask = ~current_mask
287
+
288
+ self.support_ = current_mask
289
+ self.n_features_to_select_ = self.support_.sum()
290
+
291
+ return self
292
+
293
+ def _get_best_new_feature_score(self, estimator, X, y, current_mask):
294
+ # Return the best new feature and its score to add to the current_mask,
295
+ # i.e. return the best new feature and its score to add (resp. remove)
296
+ # when doing forward selection (resp. backward selection).
297
+ # Feature will be added if the current score and past score are greater
298
+ # than tol when n_feature is auto,
299
+ candidate_feature_indices = np.flatnonzero(~current_mask)
300
+ scores = {}
301
+ for feature_idx in candidate_feature_indices:
302
+ candidate_mask = current_mask.copy()
303
+ candidate_mask[feature_idx] = True
304
+ if self.direction == "backward":
305
+ candidate_mask = ~candidate_mask
306
+ X_new = X[:, candidate_mask]
307
+ scores[feature_idx] = cross_val_score(
308
+ estimator,
309
+ X_new,
310
+ y,
311
+ cv=self.cv,
312
+ scoring=self.scoring,
313
+ n_jobs=self.n_jobs,
314
+ ).mean()
315
+ new_feature_idx = max(scores, key=lambda feature_idx: scores[feature_idx])
316
+ return new_feature_idx, scores[new_feature_idx]
317
+
318
+ def _get_support_mask(self):
319
+ check_is_fitted(self)
320
+ return self.support_
321
+
322
+ def _more_tags(self):
323
+ return {
324
+ "allow_nan": _safe_tags(self.estimator, key="allow_nan"),
325
+ }
videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_univariate_selection.py ADDED
@@ -0,0 +1,1052 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Univariate features selection."""
2
+
3
+ # Authors: V. Michel, B. Thirion, G. Varoquaux, A. Gramfort, E. Duchesnay.
4
+ # L. Buitinck, A. Joly
5
+ # License: BSD 3 clause
6
+
7
+
8
+ import numpy as np
9
+ import warnings
10
+
11
+ from numbers import Integral, Real
12
+ from scipy import special, stats
13
+ from scipy.sparse import issparse
14
+
15
+ from ..base import BaseEstimator
16
+ from ..preprocessing import LabelBinarizer
17
+ from ..utils import as_float_array, check_array, check_X_y, safe_sqr, safe_mask
18
+ from ..utils.extmath import safe_sparse_dot, row_norms
19
+ from ..utils.validation import check_is_fitted
20
+ from ..utils._param_validation import Interval, StrOptions
21
+ from ._base import SelectorMixin
22
+
23
+
24
+ def _clean_nans(scores):
25
+ """
26
+ Fixes Issue #1240: NaNs can't be properly compared, so change them to the
27
+ smallest value of scores's dtype. -inf seems to be unreliable.
28
+ """
29
+ # XXX where should this function be called? fit? scoring functions
30
+ # themselves?
31
+ scores = as_float_array(scores, copy=True)
32
+ scores[np.isnan(scores)] = np.finfo(scores.dtype).min
33
+ return scores
34
+
35
+
36
+ ######################################################################
37
+ # Scoring functions
38
+
39
+
40
+ # The following function is a rewriting of scipy.stats.f_oneway
41
+ # Contrary to the scipy.stats.f_oneway implementation it does not
42
+ # copy the data while keeping the inputs unchanged.
43
+ def f_oneway(*args):
44
+ """Perform a 1-way ANOVA.
45
+
46
+ The one-way ANOVA tests the null hypothesis that 2 or more groups have
47
+ the same population mean. The test is applied to samples from two or
48
+ more groups, possibly with differing sizes.
49
+
50
+ Read more in the :ref:`User Guide <univariate_feature_selection>`.
51
+
52
+ Parameters
53
+ ----------
54
+ *args : {array-like, sparse matrix}
55
+ Sample1, sample2... The sample measurements should be given as
56
+ arguments.
57
+
58
+ Returns
59
+ -------
60
+ f_statistic : float
61
+ The computed F-value of the test.
62
+ p_value : float
63
+ The associated p-value from the F-distribution.
64
+
65
+ Notes
66
+ -----
67
+ The ANOVA test has important assumptions that must be satisfied in order
68
+ for the associated p-value to be valid.
69
+
70
+ 1. The samples are independent
71
+ 2. Each sample is from a normally distributed population
72
+ 3. The population standard deviations of the groups are all equal. This
73
+ property is known as homoscedasticity.
74
+
75
+ If these assumptions are not true for a given set of data, it may still be
76
+ possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`_) although
77
+ with some loss of power.
78
+
79
+ The algorithm is from Heiman[2], pp.394-7.
80
+
81
+ See ``scipy.stats.f_oneway`` that should give the same results while
82
+ being less efficient.
83
+
84
+ References
85
+ ----------
86
+ .. [1] Lowry, Richard. "Concepts and Applications of Inferential
87
+ Statistics". Chapter 14.
88
+ http://faculty.vassar.edu/lowry/ch14pt1.html
89
+
90
+ .. [2] Heiman, G.W. Research Methods in Statistics. 2002.
91
+ """
92
+ n_classes = len(args)
93
+ args = [as_float_array(a) for a in args]
94
+ n_samples_per_class = np.array([a.shape[0] for a in args])
95
+ n_samples = np.sum(n_samples_per_class)
96
+ ss_alldata = sum(safe_sqr(a).sum(axis=0) for a in args)
97
+ sums_args = [np.asarray(a.sum(axis=0)) for a in args]
98
+ square_of_sums_alldata = sum(sums_args) ** 2
99
+ square_of_sums_args = [s**2 for s in sums_args]
100
+ sstot = ss_alldata - square_of_sums_alldata / float(n_samples)
101
+ ssbn = 0.0
102
+ for k, _ in enumerate(args):
103
+ ssbn += square_of_sums_args[k] / n_samples_per_class[k]
104
+ ssbn -= square_of_sums_alldata / float(n_samples)
105
+ sswn = sstot - ssbn
106
+ dfbn = n_classes - 1
107
+ dfwn = n_samples - n_classes
108
+ msb = ssbn / float(dfbn)
109
+ msw = sswn / float(dfwn)
110
+ constant_features_idx = np.where(msw == 0.0)[0]
111
+ if np.nonzero(msb)[0].size != msb.size and constant_features_idx.size:
112
+ warnings.warn("Features %s are constant." % constant_features_idx, UserWarning)
113
+ f = msb / msw
114
+ # flatten matrix to vector in sparse case
115
+ f = np.asarray(f).ravel()
116
+ prob = special.fdtrc(dfbn, dfwn, f)
117
+ return f, prob
118
+
119
+
120
+ def f_classif(X, y):
121
+ """Compute the ANOVA F-value for the provided sample.
122
+
123
+ Read more in the :ref:`User Guide <univariate_feature_selection>`.
124
+
125
+ Parameters
126
+ ----------
127
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
128
+ The set of regressors that will be tested sequentially.
129
+
130
+ y : ndarray of shape (n_samples,)
131
+ The target vector.
132
+
133
+ Returns
134
+ -------
135
+ f_statistic : ndarray of shape (n_features,)
136
+ F-statistic for each feature.
137
+
138
+ p_values : ndarray of shape (n_features,)
139
+ P-values associated with the F-statistic.
140
+
141
+ See Also
142
+ --------
143
+ chi2 : Chi-squared stats of non-negative features for classification tasks.
144
+ f_regression : F-value between label/feature for regression tasks.
145
+ """
146
+ X, y = check_X_y(X, y, accept_sparse=["csr", "csc", "coo"])
147
+ args = [X[safe_mask(X, y == k)] for k in np.unique(y)]
148
+ return f_oneway(*args)
149
+
150
+
151
+ def _chisquare(f_obs, f_exp):
152
+ """Fast replacement for scipy.stats.chisquare.
153
+
154
+ Version from https://github.com/scipy/scipy/pull/2525 with additional
155
+ optimizations.
156
+ """
157
+ f_obs = np.asarray(f_obs, dtype=np.float64)
158
+
159
+ k = len(f_obs)
160
+ # Reuse f_obs for chi-squared statistics
161
+ chisq = f_obs
162
+ chisq -= f_exp
163
+ chisq **= 2
164
+ with np.errstate(invalid="ignore"):
165
+ chisq /= f_exp
166
+ chisq = chisq.sum(axis=0)
167
+ return chisq, special.chdtrc(k - 1, chisq)
168
+
169
+
170
+ def chi2(X, y):
171
+ """Compute chi-squared stats between each non-negative feature and class.
172
+
173
+ This score can be used to select the `n_features` features with the
174
+ highest values for the test chi-squared statistic from X, which must
175
+ contain only **non-negative features** such as booleans or frequencies
176
+ (e.g., term counts in document classification), relative to the classes.
177
+
178
+ Recall that the chi-square test measures dependence between stochastic
179
+ variables, so using this function "weeds out" the features that are the
180
+ most likely to be independent of class and therefore irrelevant for
181
+ classification.
182
+
183
+ Read more in the :ref:`User Guide <univariate_feature_selection>`.
184
+
185
+ Parameters
186
+ ----------
187
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
188
+ Sample vectors.
189
+
190
+ y : array-like of shape (n_samples,)
191
+ Target vector (class labels).
192
+
193
+ Returns
194
+ -------
195
+ chi2 : ndarray of shape (n_features,)
196
+ Chi2 statistics for each feature.
197
+
198
+ p_values : ndarray of shape (n_features,)
199
+ P-values for each feature.
200
+
201
+ See Also
202
+ --------
203
+ f_classif : ANOVA F-value between label/feature for classification tasks.
204
+ f_regression : F-value between label/feature for regression tasks.
205
+
206
+ Notes
207
+ -----
208
+ Complexity of this algorithm is O(n_classes * n_features).
209
+ """
210
+
211
+ # XXX: we might want to do some of the following in logspace instead for
212
+ # numerical stability.
213
+ # Converting X to float allows getting better performance for the
214
+ # safe_sparse_dot call made below.
215
+ X = check_array(X, accept_sparse="csr", dtype=(np.float64, np.float32))
216
+ if np.any((X.data if issparse(X) else X) < 0):
217
+ raise ValueError("Input X must be non-negative.")
218
+
219
+ # Use a sparse representation for Y by default to reduce memory usage when
220
+ # y has many unique classes.
221
+ Y = LabelBinarizer(sparse_output=True).fit_transform(y)
222
+ if Y.shape[1] == 1:
223
+ Y = Y.toarray()
224
+ Y = np.append(1 - Y, Y, axis=1)
225
+
226
+ observed = safe_sparse_dot(Y.T, X) # n_classes * n_features
227
+
228
+ if issparse(observed):
229
+ # convert back to a dense array before calling _chisquare
230
+ # XXX: could _chisquare be reimplement to accept sparse matrices for
231
+ # cases where both n_classes and n_features are large (and X is
232
+ # sparse)?
233
+ observed = observed.toarray()
234
+
235
+ feature_count = X.sum(axis=0).reshape(1, -1)
236
+ class_prob = Y.mean(axis=0).reshape(1, -1)
237
+ expected = np.dot(class_prob.T, feature_count)
238
+
239
+ return _chisquare(observed, expected)
240
+
241
+
242
+ def r_regression(X, y, *, center=True, force_finite=True):
243
+ """Compute Pearson's r for each features and the target.
244
+
245
+ Pearson's r is also known as the Pearson correlation coefficient.
246
+
247
+ Linear model for testing the individual effect of each of many regressors.
248
+ This is a scoring function to be used in a feature selection procedure, not
249
+ a free standing feature selection procedure.
250
+
251
+ The cross correlation between each regressor and the target is computed
252
+ as::
253
+
254
+ E[(X[:, i] - mean(X[:, i])) * (y - mean(y))] / (std(X[:, i]) * std(y))
255
+
256
+ For more on usage see the :ref:`User Guide <univariate_feature_selection>`.
257
+
258
+ .. versionadded:: 1.0
259
+
260
+ Parameters
261
+ ----------
262
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
263
+ The data matrix.
264
+
265
+ y : array-like of shape (n_samples,)
266
+ The target vector.
267
+
268
+ center : bool, default=True
269
+ Whether or not to center the data matrix `X` and the target vector `y`.
270
+ By default, `X` and `y` will be centered.
271
+
272
+ force_finite : bool, default=True
273
+ Whether or not to force the Pearson's R correlation to be finite.
274
+ In the particular case where some features in `X` or the target `y`
275
+ are constant, the Pearson's R correlation is not defined. When
276
+ `force_finite=False`, a correlation of `np.nan` is returned to
277
+ acknowledge this case. When `force_finite=True`, this value will be
278
+ forced to a minimal correlation of `0.0`.
279
+
280
+ .. versionadded:: 1.1
281
+
282
+ Returns
283
+ -------
284
+ correlation_coefficient : ndarray of shape (n_features,)
285
+ Pearson's R correlation coefficients of features.
286
+
287
+ See Also
288
+ --------
289
+ f_regression: Univariate linear regression tests returning f-statistic
290
+ and p-values.
291
+ mutual_info_regression: Mutual information for a continuous target.
292
+ f_classif: ANOVA F-value between label/feature for classification tasks.
293
+ chi2: Chi-squared stats of non-negative features for classification tasks.
294
+ """
295
+ X, y = check_X_y(X, y, accept_sparse=["csr", "csc", "coo"], dtype=np.float64)
296
+ n_samples = X.shape[0]
297
+
298
+ # Compute centered values
299
+ # Note that E[(x - mean(x))*(y - mean(y))] = E[x*(y - mean(y))], so we
300
+ # need not center X
301
+ if center:
302
+ y = y - np.mean(y)
303
+ if issparse(X):
304
+ X_means = X.mean(axis=0).getA1()
305
+ else:
306
+ X_means = X.mean(axis=0)
307
+ # Compute the scaled standard deviations via moments
308
+ X_norms = np.sqrt(row_norms(X.T, squared=True) - n_samples * X_means**2)
309
+ else:
310
+ X_norms = row_norms(X.T)
311
+
312
+ correlation_coefficient = safe_sparse_dot(y, X)
313
+ with np.errstate(divide="ignore", invalid="ignore"):
314
+ correlation_coefficient /= X_norms
315
+ correlation_coefficient /= np.linalg.norm(y)
316
+
317
+ if force_finite and not np.isfinite(correlation_coefficient).all():
318
+ # case where the target or some features are constant
319
+ # the correlation coefficient(s) is/are set to the minimum (i.e. 0.0)
320
+ nan_mask = np.isnan(correlation_coefficient)
321
+ correlation_coefficient[nan_mask] = 0.0
322
+ return correlation_coefficient
323
+
324
+
325
+ def f_regression(X, y, *, center=True, force_finite=True):
326
+ """Univariate linear regression tests returning F-statistic and p-values.
327
+
328
+ Quick linear model for testing the effect of a single regressor,
329
+ sequentially for many regressors.
330
+
331
+ This is done in 2 steps:
332
+
333
+ 1. The cross correlation between each regressor and the target is computed
334
+ using :func:`r_regression` as::
335
+
336
+ E[(X[:, i] - mean(X[:, i])) * (y - mean(y))] / (std(X[:, i]) * std(y))
337
+
338
+ 2. It is converted to an F score and then to a p-value.
339
+
340
+ :func:`f_regression` is derived from :func:`r_regression` and will rank
341
+ features in the same order if all the features are positively correlated
342
+ with the target.
343
+
344
+ Note however that contrary to :func:`f_regression`, :func:`r_regression`
345
+ values lie in [-1, 1] and can thus be negative. :func:`f_regression` is
346
+ therefore recommended as a feature selection criterion to identify
347
+ potentially predictive feature for a downstream classifier, irrespective of
348
+ the sign of the association with the target variable.
349
+
350
+ Furthermore :func:`f_regression` returns p-values while
351
+ :func:`r_regression` does not.
352
+
353
+ Read more in the :ref:`User Guide <univariate_feature_selection>`.
354
+
355
+ Parameters
356
+ ----------
357
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
358
+ The data matrix.
359
+
360
+ y : array-like of shape (n_samples,)
361
+ The target vector.
362
+
363
+ center : bool, default=True
364
+ Whether or not to center the data matrix `X` and the target vector `y`.
365
+ By default, `X` and `y` will be centered.
366
+
367
+ force_finite : bool, default=True
368
+ Whether or not to force the F-statistics and associated p-values to
369
+ be finite. There are two cases where the F-statistic is expected to not
370
+ be finite:
371
+
372
+ - when the target `y` or some features in `X` are constant. In this
373
+ case, the Pearson's R correlation is not defined leading to obtain
374
+ `np.nan` values in the F-statistic and p-value. When
375
+ `force_finite=True`, the F-statistic is set to `0.0` and the
376
+ associated p-value is set to `1.0`.
377
+ - when a feature in `X` is perfectly correlated (or
378
+ anti-correlated) with the target `y`. In this case, the F-statistic
379
+ is expected to be `np.inf`. When `force_finite=True`, the F-statistic
380
+ is set to `np.finfo(dtype).max` and the associated p-value is set to
381
+ `0.0`.
382
+
383
+ .. versionadded:: 1.1
384
+
385
+ Returns
386
+ -------
387
+ f_statistic : ndarray of shape (n_features,)
388
+ F-statistic for each feature.
389
+
390
+ p_values : ndarray of shape (n_features,)
391
+ P-values associated with the F-statistic.
392
+
393
+ See Also
394
+ --------
395
+ r_regression: Pearson's R between label/feature for regression tasks.
396
+ f_classif: ANOVA F-value between label/feature for classification tasks.
397
+ chi2: Chi-squared stats of non-negative features for classification tasks.
398
+ SelectKBest: Select features based on the k highest scores.
399
+ SelectFpr: Select features based on a false positive rate test.
400
+ SelectFdr: Select features based on an estimated false discovery rate.
401
+ SelectFwe: Select features based on family-wise error rate.
402
+ SelectPercentile: Select features based on percentile of the highest
403
+ scores.
404
+ """
405
+ correlation_coefficient = r_regression(
406
+ X, y, center=center, force_finite=force_finite
407
+ )
408
+ deg_of_freedom = y.size - (2 if center else 1)
409
+
410
+ corr_coef_squared = correlation_coefficient**2
411
+
412
+ with np.errstate(divide="ignore", invalid="ignore"):
413
+ f_statistic = corr_coef_squared / (1 - corr_coef_squared) * deg_of_freedom
414
+ p_values = stats.f.sf(f_statistic, 1, deg_of_freedom)
415
+
416
+ if force_finite and not np.isfinite(f_statistic).all():
417
+ # case where there is a perfect (anti-)correlation
418
+ # f-statistics can be set to the maximum and p-values to zero
419
+ mask_inf = np.isinf(f_statistic)
420
+ f_statistic[mask_inf] = np.finfo(f_statistic.dtype).max
421
+ # case where the target or some features are constant
422
+ # f-statistics would be minimum and thus p-values large
423
+ mask_nan = np.isnan(f_statistic)
424
+ f_statistic[mask_nan] = 0.0
425
+ p_values[mask_nan] = 1.0
426
+ return f_statistic, p_values
427
+
428
+
429
+ ######################################################################
430
+ # Base classes
431
+
432
+
433
+ class _BaseFilter(SelectorMixin, BaseEstimator):
434
+ """Initialize the univariate feature selection.
435
+
436
+ Parameters
437
+ ----------
438
+ score_func : callable
439
+ Function taking two arrays X and y, and returning a pair of arrays
440
+ (scores, pvalues) or a single array with scores.
441
+ """
442
+
443
+ _parameter_constraints: dict = {"score_func": [callable]}
444
+
445
+ def __init__(self, score_func):
446
+ self.score_func = score_func
447
+
448
+ def fit(self, X, y):
449
+ """Run score function on (X, y) and get the appropriate features.
450
+
451
+ Parameters
452
+ ----------
453
+ X : array-like of shape (n_samples, n_features)
454
+ The training input samples.
455
+
456
+ y : array-like of shape (n_samples,)
457
+ The target values (class labels in classification, real numbers in
458
+ regression).
459
+
460
+ Returns
461
+ -------
462
+ self : object
463
+ Returns the instance itself.
464
+ """
465
+ self._validate_params()
466
+
467
+ X, y = self._validate_data(
468
+ X, y, accept_sparse=["csr", "csc"], multi_output=True
469
+ )
470
+
471
+ self._check_params(X, y)
472
+ score_func_ret = self.score_func(X, y)
473
+ if isinstance(score_func_ret, (list, tuple)):
474
+ self.scores_, self.pvalues_ = score_func_ret
475
+ self.pvalues_ = np.asarray(self.pvalues_)
476
+ else:
477
+ self.scores_ = score_func_ret
478
+ self.pvalues_ = None
479
+
480
+ self.scores_ = np.asarray(self.scores_)
481
+
482
+ return self
483
+
484
+ def _check_params(self, X, y):
485
+ pass
486
+
487
+ def _more_tags(self):
488
+ return {"requires_y": True}
489
+
490
+
491
+ ######################################################################
492
+ # Specific filters
493
+ ######################################################################
494
+ class SelectPercentile(_BaseFilter):
495
+ """Select features according to a percentile of the highest scores.
496
+
497
+ Read more in the :ref:`User Guide <univariate_feature_selection>`.
498
+
499
+ Parameters
500
+ ----------
501
+ score_func : callable, default=f_classif
502
+ Function taking two arrays X and y, and returning a pair of arrays
503
+ (scores, pvalues) or a single array with scores.
504
+ Default is f_classif (see below "See Also"). The default function only
505
+ works with classification tasks.
506
+
507
+ .. versionadded:: 0.18
508
+
509
+ percentile : int, default=10
510
+ Percent of features to keep.
511
+
512
+ Attributes
513
+ ----------
514
+ scores_ : array-like of shape (n_features,)
515
+ Scores of features.
516
+
517
+ pvalues_ : array-like of shape (n_features,)
518
+ p-values of feature scores, None if `score_func` returned only scores.
519
+
520
+ n_features_in_ : int
521
+ Number of features seen during :term:`fit`.
522
+
523
+ .. versionadded:: 0.24
524
+
525
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
526
+ Names of features seen during :term:`fit`. Defined only when `X`
527
+ has feature names that are all strings.
528
+
529
+ .. versionadded:: 1.0
530
+
531
+ See Also
532
+ --------
533
+ f_classif : ANOVA F-value between label/feature for classification tasks.
534
+ mutual_info_classif : Mutual information for a discrete target.
535
+ chi2 : Chi-squared stats of non-negative features for classification tasks.
536
+ f_regression : F-value between label/feature for regression tasks.
537
+ mutual_info_regression : Mutual information for a continuous target.
538
+ SelectKBest : Select features based on the k highest scores.
539
+ SelectFpr : Select features based on a false positive rate test.
540
+ SelectFdr : Select features based on an estimated false discovery rate.
541
+ SelectFwe : Select features based on family-wise error rate.
542
+ GenericUnivariateSelect : Univariate feature selector with configurable
543
+ mode.
544
+
545
+ Notes
546
+ -----
547
+ Ties between features with equal scores will be broken in an unspecified
548
+ way.
549
+
550
+ Examples
551
+ --------
552
+ >>> from sklearn.datasets import load_digits
553
+ >>> from sklearn.feature_selection import SelectPercentile, chi2
554
+ >>> X, y = load_digits(return_X_y=True)
555
+ >>> X.shape
556
+ (1797, 64)
557
+ >>> X_new = SelectPercentile(chi2, percentile=10).fit_transform(X, y)
558
+ >>> X_new.shape
559
+ (1797, 7)
560
+ """
561
+
562
+ _parameter_constraints: dict = {
563
+ **_BaseFilter._parameter_constraints,
564
+ "percentile": [Interval(Real, 0, 100, closed="both")],
565
+ }
566
+
567
+ def __init__(self, score_func=f_classif, *, percentile=10):
568
+ super().__init__(score_func=score_func)
569
+ self.percentile = percentile
570
+
571
+ def _get_support_mask(self):
572
+ check_is_fitted(self)
573
+
574
+ # Cater for NaNs
575
+ if self.percentile == 100:
576
+ return np.ones(len(self.scores_), dtype=bool)
577
+ elif self.percentile == 0:
578
+ return np.zeros(len(self.scores_), dtype=bool)
579
+
580
+ scores = _clean_nans(self.scores_)
581
+ threshold = np.percentile(scores, 100 - self.percentile)
582
+ mask = scores > threshold
583
+ ties = np.where(scores == threshold)[0]
584
+ if len(ties):
585
+ max_feats = int(len(scores) * self.percentile / 100)
586
+ kept_ties = ties[: max_feats - mask.sum()]
587
+ mask[kept_ties] = True
588
+ return mask
589
+
590
+
591
+ class SelectKBest(_BaseFilter):
592
+ """Select features according to the k highest scores.
593
+
594
+ Read more in the :ref:`User Guide <univariate_feature_selection>`.
595
+
596
+ Parameters
597
+ ----------
598
+ score_func : callable, default=f_classif
599
+ Function taking two arrays X and y, and returning a pair of arrays
600
+ (scores, pvalues) or a single array with scores.
601
+ Default is f_classif (see below "See Also"). The default function only
602
+ works with classification tasks.
603
+
604
+ .. versionadded:: 0.18
605
+
606
+ k : int or "all", default=10
607
+ Number of top features to select.
608
+ The "all" option bypasses selection, for use in a parameter search.
609
+
610
+ Attributes
611
+ ----------
612
+ scores_ : array-like of shape (n_features,)
613
+ Scores of features.
614
+
615
+ pvalues_ : array-like of shape (n_features,)
616
+ p-values of feature scores, None if `score_func` returned only scores.
617
+
618
+ n_features_in_ : int
619
+ Number of features seen during :term:`fit`.
620
+
621
+ .. versionadded:: 0.24
622
+
623
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
624
+ Names of features seen during :term:`fit`. Defined only when `X`
625
+ has feature names that are all strings.
626
+
627
+ .. versionadded:: 1.0
628
+
629
+ See Also
630
+ --------
631
+ f_classif: ANOVA F-value between label/feature for classification tasks.
632
+ mutual_info_classif: Mutual information for a discrete target.
633
+ chi2: Chi-squared stats of non-negative features for classification tasks.
634
+ f_regression: F-value between label/feature for regression tasks.
635
+ mutual_info_regression: Mutual information for a continuous target.
636
+ SelectPercentile: Select features based on percentile of the highest
637
+ scores.
638
+ SelectFpr : Select features based on a false positive rate test.
639
+ SelectFdr : Select features based on an estimated false discovery rate.
640
+ SelectFwe : Select features based on family-wise error rate.
641
+ GenericUnivariateSelect : Univariate feature selector with configurable
642
+ mode.
643
+
644
+ Notes
645
+ -----
646
+ Ties between features with equal scores will be broken in an unspecified
647
+ way.
648
+
649
+ Examples
650
+ --------
651
+ >>> from sklearn.datasets import load_digits
652
+ >>> from sklearn.feature_selection import SelectKBest, chi2
653
+ >>> X, y = load_digits(return_X_y=True)
654
+ >>> X.shape
655
+ (1797, 64)
656
+ >>> X_new = SelectKBest(chi2, k=20).fit_transform(X, y)
657
+ >>> X_new.shape
658
+ (1797, 20)
659
+ """
660
+
661
+ _parameter_constraints: dict = {
662
+ **_BaseFilter._parameter_constraints,
663
+ "k": [StrOptions({"all"}), Interval(Integral, 0, None, closed="left")],
664
+ }
665
+
666
+ def __init__(self, score_func=f_classif, *, k=10):
667
+ super().__init__(score_func=score_func)
668
+ self.k = k
669
+
670
+ def _check_params(self, X, y):
671
+ if not isinstance(self.k, str) and self.k > X.shape[1]:
672
+ raise ValueError(
673
+ f"k should be <= n_features = {X.shape[1]}; "
674
+ f"got {self.k}. Use k='all' to return all features."
675
+ )
676
+
677
+ def _get_support_mask(self):
678
+ check_is_fitted(self)
679
+
680
+ if self.k == "all":
681
+ return np.ones(self.scores_.shape, dtype=bool)
682
+ elif self.k == 0:
683
+ return np.zeros(self.scores_.shape, dtype=bool)
684
+ else:
685
+ scores = _clean_nans(self.scores_)
686
+ mask = np.zeros(scores.shape, dtype=bool)
687
+
688
+ # Request a stable sort. Mergesort takes more memory (~40MB per
689
+ # megafeature on x86-64).
690
+ mask[np.argsort(scores, kind="mergesort")[-self.k :]] = 1
691
+ return mask
692
+
693
+
694
+ class SelectFpr(_BaseFilter):
695
+ """Filter: Select the pvalues below alpha based on a FPR test.
696
+
697
+ FPR test stands for False Positive Rate test. It controls the total
698
+ amount of false detections.
699
+
700
+ Read more in the :ref:`User Guide <univariate_feature_selection>`.
701
+
702
+ Parameters
703
+ ----------
704
+ score_func : callable, default=f_classif
705
+ Function taking two arrays X and y, and returning a pair of arrays
706
+ (scores, pvalues).
707
+ Default is f_classif (see below "See Also"). The default function only
708
+ works with classification tasks.
709
+
710
+ alpha : float, default=5e-2
711
+ Features with p-values less than `alpha` are selected.
712
+
713
+ Attributes
714
+ ----------
715
+ scores_ : array-like of shape (n_features,)
716
+ Scores of features.
717
+
718
+ pvalues_ : array-like of shape (n_features,)
719
+ p-values of feature scores.
720
+
721
+ n_features_in_ : int
722
+ Number of features seen during :term:`fit`.
723
+
724
+ .. versionadded:: 0.24
725
+
726
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
727
+ Names of features seen during :term:`fit`. Defined only when `X`
728
+ has feature names that are all strings.
729
+
730
+ .. versionadded:: 1.0
731
+
732
+ See Also
733
+ --------
734
+ f_classif : ANOVA F-value between label/feature for classification tasks.
735
+ chi2 : Chi-squared stats of non-negative features for classification tasks.
736
+ mutual_info_classif: Mutual information for a discrete target.
737
+ f_regression : F-value between label/feature for regression tasks.
738
+ mutual_info_regression : Mutual information for a continuous target.
739
+ SelectPercentile : Select features based on percentile of the highest
740
+ scores.
741
+ SelectKBest : Select features based on the k highest scores.
742
+ SelectFdr : Select features based on an estimated false discovery rate.
743
+ SelectFwe : Select features based on family-wise error rate.
744
+ GenericUnivariateSelect : Univariate feature selector with configurable
745
+ mode.
746
+
747
+ Examples
748
+ --------
749
+ >>> from sklearn.datasets import load_breast_cancer
750
+ >>> from sklearn.feature_selection import SelectFpr, chi2
751
+ >>> X, y = load_breast_cancer(return_X_y=True)
752
+ >>> X.shape
753
+ (569, 30)
754
+ >>> X_new = SelectFpr(chi2, alpha=0.01).fit_transform(X, y)
755
+ >>> X_new.shape
756
+ (569, 16)
757
+ """
758
+
759
+ _parameter_constraints: dict = {
760
+ **_BaseFilter._parameter_constraints,
761
+ "alpha": [Interval(Real, 0, 1, closed="both")],
762
+ }
763
+
764
+ def __init__(self, score_func=f_classif, *, alpha=5e-2):
765
+ super().__init__(score_func=score_func)
766
+ self.alpha = alpha
767
+
768
+ def _get_support_mask(self):
769
+ check_is_fitted(self)
770
+
771
+ return self.pvalues_ < self.alpha
772
+
773
+
774
+ class SelectFdr(_BaseFilter):
775
+ """Filter: Select the p-values for an estimated false discovery rate.
776
+
777
+ This uses the Benjamini-Hochberg procedure. ``alpha`` is an upper bound
778
+ on the expected false discovery rate.
779
+
780
+ Read more in the :ref:`User Guide <univariate_feature_selection>`.
781
+
782
+ Parameters
783
+ ----------
784
+ score_func : callable, default=f_classif
785
+ Function taking two arrays X and y, and returning a pair of arrays
786
+ (scores, pvalues).
787
+ Default is f_classif (see below "See Also"). The default function only
788
+ works with classification tasks.
789
+
790
+ alpha : float, default=5e-2
791
+ The highest uncorrected p-value for features to keep.
792
+
793
+ Attributes
794
+ ----------
795
+ scores_ : array-like of shape (n_features,)
796
+ Scores of features.
797
+
798
+ pvalues_ : array-like of shape (n_features,)
799
+ p-values of feature scores.
800
+
801
+ n_features_in_ : int
802
+ Number of features seen during :term:`fit`.
803
+
804
+ .. versionadded:: 0.24
805
+
806
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
807
+ Names of features seen during :term:`fit`. Defined only when `X`
808
+ has feature names that are all strings.
809
+
810
+ .. versionadded:: 1.0
811
+
812
+ See Also
813
+ --------
814
+ f_classif : ANOVA F-value between label/feature for classification tasks.
815
+ mutual_info_classif : Mutual information for a discrete target.
816
+ chi2 : Chi-squared stats of non-negative features for classification tasks.
817
+ f_regression : F-value between label/feature for regression tasks.
818
+ mutual_info_regression : Mutual information for a continuous target.
819
+ SelectPercentile : Select features based on percentile of the highest
820
+ scores.
821
+ SelectKBest : Select features based on the k highest scores.
822
+ SelectFpr : Select features based on a false positive rate test.
823
+ SelectFwe : Select features based on family-wise error rate.
824
+ GenericUnivariateSelect : Univariate feature selector with configurable
825
+ mode.
826
+
827
+ References
828
+ ----------
829
+ https://en.wikipedia.org/wiki/False_discovery_rate
830
+
831
+ Examples
832
+ --------
833
+ >>> from sklearn.datasets import load_breast_cancer
834
+ >>> from sklearn.feature_selection import SelectFdr, chi2
835
+ >>> X, y = load_breast_cancer(return_X_y=True)
836
+ >>> X.shape
837
+ (569, 30)
838
+ >>> X_new = SelectFdr(chi2, alpha=0.01).fit_transform(X, y)
839
+ >>> X_new.shape
840
+ (569, 16)
841
+ """
842
+
843
+ _parameter_constraints: dict = {
844
+ **_BaseFilter._parameter_constraints,
845
+ "alpha": [Interval(Real, 0, 1, closed="both")],
846
+ }
847
+
848
+ def __init__(self, score_func=f_classif, *, alpha=5e-2):
849
+ super().__init__(score_func=score_func)
850
+ self.alpha = alpha
851
+
852
+ def _get_support_mask(self):
853
+ check_is_fitted(self)
854
+
855
+ n_features = len(self.pvalues_)
856
+ sv = np.sort(self.pvalues_)
857
+ selected = sv[
858
+ sv <= float(self.alpha) / n_features * np.arange(1, n_features + 1)
859
+ ]
860
+ if selected.size == 0:
861
+ return np.zeros_like(self.pvalues_, dtype=bool)
862
+ return self.pvalues_ <= selected.max()
863
+
864
+
865
+ class SelectFwe(_BaseFilter):
866
+ """Filter: Select the p-values corresponding to Family-wise error rate.
867
+
868
+ Read more in the :ref:`User Guide <univariate_feature_selection>`.
869
+
870
+ Parameters
871
+ ----------
872
+ score_func : callable, default=f_classif
873
+ Function taking two arrays X and y, and returning a pair of arrays
874
+ (scores, pvalues).
875
+ Default is f_classif (see below "See Also"). The default function only
876
+ works with classification tasks.
877
+
878
+ alpha : float, default=5e-2
879
+ The highest uncorrected p-value for features to keep.
880
+
881
+ Attributes
882
+ ----------
883
+ scores_ : array-like of shape (n_features,)
884
+ Scores of features.
885
+
886
+ pvalues_ : array-like of shape (n_features,)
887
+ p-values of feature scores.
888
+
889
+ n_features_in_ : int
890
+ Number of features seen during :term:`fit`.
891
+
892
+ .. versionadded:: 0.24
893
+
894
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
895
+ Names of features seen during :term:`fit`. Defined only when `X`
896
+ has feature names that are all strings.
897
+
898
+ .. versionadded:: 1.0
899
+
900
+ See Also
901
+ --------
902
+ f_classif : ANOVA F-value between label/feature for classification tasks.
903
+ chi2 : Chi-squared stats of non-negative features for classification tasks.
904
+ f_regression : F-value between label/feature for regression tasks.
905
+ SelectPercentile : Select features based on percentile of the highest
906
+ scores.
907
+ SelectKBest : Select features based on the k highest scores.
908
+ SelectFpr : Select features based on a false positive rate test.
909
+ SelectFdr : Select features based on an estimated false discovery rate.
910
+ GenericUnivariateSelect : Univariate feature selector with configurable
911
+ mode.
912
+
913
+ Examples
914
+ --------
915
+ >>> from sklearn.datasets import load_breast_cancer
916
+ >>> from sklearn.feature_selection import SelectFwe, chi2
917
+ >>> X, y = load_breast_cancer(return_X_y=True)
918
+ >>> X.shape
919
+ (569, 30)
920
+ >>> X_new = SelectFwe(chi2, alpha=0.01).fit_transform(X, y)
921
+ >>> X_new.shape
922
+ (569, 15)
923
+ """
924
+
925
+ _parameter_constraints: dict = {
926
+ **_BaseFilter._parameter_constraints,
927
+ "alpha": [Interval(Real, 0, 1, closed="both")],
928
+ }
929
+
930
+ def __init__(self, score_func=f_classif, *, alpha=5e-2):
931
+ super().__init__(score_func=score_func)
932
+ self.alpha = alpha
933
+
934
+ def _get_support_mask(self):
935
+ check_is_fitted(self)
936
+
937
+ return self.pvalues_ < self.alpha / len(self.pvalues_)
938
+
939
+
940
+ ######################################################################
941
+ # Generic filter
942
+ ######################################################################
943
+
944
+ # TODO this class should fit on either p-values or scores,
945
+ # depending on the mode.
946
+ class GenericUnivariateSelect(_BaseFilter):
947
+ """Univariate feature selector with configurable strategy.
948
+
949
+ Read more in the :ref:`User Guide <univariate_feature_selection>`.
950
+
951
+ Parameters
952
+ ----------
953
+ score_func : callable, default=f_classif
954
+ Function taking two arrays X and y, and returning a pair of arrays
955
+ (scores, pvalues). For modes 'percentile' or 'kbest' it can return
956
+ a single array scores.
957
+
958
+ mode : {'percentile', 'k_best', 'fpr', 'fdr', 'fwe'}, default='percentile'
959
+ Feature selection mode.
960
+
961
+ param : "all", float or int, default=1e-5
962
+ Parameter of the corresponding mode.
963
+
964
+ Attributes
965
+ ----------
966
+ scores_ : array-like of shape (n_features,)
967
+ Scores of features.
968
+
969
+ pvalues_ : array-like of shape (n_features,)
970
+ p-values of feature scores, None if `score_func` returned scores only.
971
+
972
+ n_features_in_ : int
973
+ Number of features seen during :term:`fit`.
974
+
975
+ .. versionadded:: 0.24
976
+
977
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
978
+ Names of features seen during :term:`fit`. Defined only when `X`
979
+ has feature names that are all strings.
980
+
981
+ .. versionadded:: 1.0
982
+
983
+ See Also
984
+ --------
985
+ f_classif : ANOVA F-value between label/feature for classification tasks.
986
+ mutual_info_classif : Mutual information for a discrete target.
987
+ chi2 : Chi-squared stats of non-negative features for classification tasks.
988
+ f_regression : F-value between label/feature for regression tasks.
989
+ mutual_info_regression : Mutual information for a continuous target.
990
+ SelectPercentile : Select features based on percentile of the highest
991
+ scores.
992
+ SelectKBest : Select features based on the k highest scores.
993
+ SelectFpr : Select features based on a false positive rate test.
994
+ SelectFdr : Select features based on an estimated false discovery rate.
995
+ SelectFwe : Select features based on family-wise error rate.
996
+
997
+ Examples
998
+ --------
999
+ >>> from sklearn.datasets import load_breast_cancer
1000
+ >>> from sklearn.feature_selection import GenericUnivariateSelect, chi2
1001
+ >>> X, y = load_breast_cancer(return_X_y=True)
1002
+ >>> X.shape
1003
+ (569, 30)
1004
+ >>> transformer = GenericUnivariateSelect(chi2, mode='k_best', param=20)
1005
+ >>> X_new = transformer.fit_transform(X, y)
1006
+ >>> X_new.shape
1007
+ (569, 20)
1008
+ """
1009
+
1010
+ _selection_modes: dict = {
1011
+ "percentile": SelectPercentile,
1012
+ "k_best": SelectKBest,
1013
+ "fpr": SelectFpr,
1014
+ "fdr": SelectFdr,
1015
+ "fwe": SelectFwe,
1016
+ }
1017
+
1018
+ _parameter_constraints: dict = {
1019
+ **_BaseFilter._parameter_constraints,
1020
+ "mode": [StrOptions(set(_selection_modes.keys()))],
1021
+ "param": [Interval(Real, 0, None, closed="left"), StrOptions({"all"})],
1022
+ }
1023
+
1024
+ def __init__(self, score_func=f_classif, *, mode="percentile", param=1e-5):
1025
+ super().__init__(score_func=score_func)
1026
+ self.mode = mode
1027
+ self.param = param
1028
+
1029
+ def _make_selector(self):
1030
+ selector = self._selection_modes[self.mode](score_func=self.score_func)
1031
+
1032
+ # Now perform some acrobatics to set the right named parameter in
1033
+ # the selector
1034
+ possible_params = selector._get_param_names()
1035
+ possible_params.remove("score_func")
1036
+ selector.set_params(**{possible_params[0]: self.param})
1037
+
1038
+ return selector
1039
+
1040
+ def _more_tags(self):
1041
+ return {"preserves_dtype": [np.float64, np.float32]}
1042
+
1043
+ def _check_params(self, X, y):
1044
+ self._make_selector()._check_params(X, y)
1045
+
1046
+ def _get_support_mask(self):
1047
+ check_is_fitted(self)
1048
+
1049
+ selector = self._make_selector()
1050
+ selector.pvalues_ = self.pvalues_
1051
+ selector.scores_ = self.scores_
1052
+ return selector._get_support_mask()
videollama2/lib/python3.10/site-packages/sklearn/feature_selection/_variance_threshold.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Author: Lars Buitinck
2
+ # License: 3-clause BSD
3
+ from numbers import Real
4
+
5
+ import numpy as np
6
+ from ..base import BaseEstimator
7
+ from ._base import SelectorMixin
8
+ from ..utils.sparsefuncs import mean_variance_axis, min_max_axis
9
+ from ..utils.validation import check_is_fitted
10
+ from ..utils._param_validation import Interval
11
+
12
+
13
+ class VarianceThreshold(SelectorMixin, BaseEstimator):
14
+ """Feature selector that removes all low-variance features.
15
+
16
+ This feature selection algorithm looks only at the features (X), not the
17
+ desired outputs (y), and can thus be used for unsupervised learning.
18
+
19
+ Read more in the :ref:`User Guide <variance_threshold>`.
20
+
21
+ Parameters
22
+ ----------
23
+ threshold : float, default=0
24
+ Features with a training-set variance lower than this threshold will
25
+ be removed. The default is to keep all features with non-zero variance,
26
+ i.e. remove the features that have the same value in all samples.
27
+
28
+ Attributes
29
+ ----------
30
+ variances_ : array, shape (n_features,)
31
+ Variances of individual features.
32
+
33
+ n_features_in_ : int
34
+ Number of features seen during :term:`fit`.
35
+
36
+ .. versionadded:: 0.24
37
+
38
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
39
+ Names of features seen during :term:`fit`. Defined only when `X`
40
+ has feature names that are all strings.
41
+
42
+ .. versionadded:: 1.0
43
+
44
+ See Also
45
+ --------
46
+ SelectFromModel: Meta-transformer for selecting features based on
47
+ importance weights.
48
+ SelectPercentile : Select features according to a percentile of the highest
49
+ scores.
50
+ SequentialFeatureSelector : Transformer that performs Sequential Feature
51
+ Selection.
52
+
53
+ Notes
54
+ -----
55
+ Allows NaN in the input.
56
+ Raises ValueError if no feature in X meets the variance threshold.
57
+
58
+ Examples
59
+ --------
60
+ The following dataset has integer features, two of which are the same
61
+ in every sample. These are removed with the default setting for threshold::
62
+
63
+ >>> from sklearn.feature_selection import VarianceThreshold
64
+ >>> X = [[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]]
65
+ >>> selector = VarianceThreshold()
66
+ >>> selector.fit_transform(X)
67
+ array([[2, 0],
68
+ [1, 4],
69
+ [1, 1]])
70
+ """
71
+
72
+ _parameter_constraints: dict = {
73
+ "threshold": [Interval(Real, 0, None, closed="left")]
74
+ }
75
+
76
+ def __init__(self, threshold=0.0):
77
+ self.threshold = threshold
78
+
79
+ def fit(self, X, y=None):
80
+ """Learn empirical variances from X.
81
+
82
+ Parameters
83
+ ----------
84
+ X : {array-like, sparse matrix}, shape (n_samples, n_features)
85
+ Data from which to compute variances, where `n_samples` is
86
+ the number of samples and `n_features` is the number of features.
87
+
88
+ y : any, default=None
89
+ Ignored. This parameter exists only for compatibility with
90
+ sklearn.pipeline.Pipeline.
91
+
92
+ Returns
93
+ -------
94
+ self : object
95
+ Returns the instance itself.
96
+ """
97
+ self._validate_params()
98
+ X = self._validate_data(
99
+ X,
100
+ accept_sparse=("csr", "csc"),
101
+ dtype=np.float64,
102
+ force_all_finite="allow-nan",
103
+ )
104
+
105
+ if hasattr(X, "toarray"): # sparse matrix
106
+ _, self.variances_ = mean_variance_axis(X, axis=0)
107
+ if self.threshold == 0:
108
+ mins, maxes = min_max_axis(X, axis=0)
109
+ peak_to_peaks = maxes - mins
110
+ else:
111
+ self.variances_ = np.nanvar(X, axis=0)
112
+ if self.threshold == 0:
113
+ peak_to_peaks = np.ptp(X, axis=0)
114
+
115
+ if self.threshold == 0:
116
+ # Use peak-to-peak to avoid numeric precision issues
117
+ # for constant features
118
+ compare_arr = np.array([self.variances_, peak_to_peaks])
119
+ self.variances_ = np.nanmin(compare_arr, axis=0)
120
+
121
+ if np.all(~np.isfinite(self.variances_) | (self.variances_ <= self.threshold)):
122
+ msg = "No feature in X meets the variance threshold {0:.5f}"
123
+ if X.shape[0] == 1:
124
+ msg += " (X contains only one sample)"
125
+ raise ValueError(msg.format(self.threshold))
126
+
127
+ return self
128
+
129
+ def _get_support_mask(self):
130
+ check_is_fitted(self)
131
+
132
+ return self.variances_ > self.threshold
133
+
134
+ def _more_tags(self):
135
+ return {"allow_nan": True}
videollama2/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_feature_select.py ADDED
@@ -0,0 +1,946 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Todo: cross-check the F-value with stats model
3
+ """
4
+ import itertools
5
+ import warnings
6
+ import numpy as np
7
+ from numpy.testing import assert_allclose
8
+ from scipy import stats, sparse
9
+
10
+ import pytest
11
+
12
+ from sklearn.utils._testing import assert_almost_equal, _convert_container
13
+ from sklearn.utils._testing import assert_array_equal
14
+ from sklearn.utils._testing import assert_array_almost_equal
15
+ from sklearn.utils._testing import ignore_warnings
16
+ from sklearn.utils import safe_mask
17
+
18
+ from sklearn.datasets import make_classification, make_regression
19
+ from sklearn.feature_selection import (
20
+ chi2,
21
+ f_classif,
22
+ f_oneway,
23
+ f_regression,
24
+ GenericUnivariateSelect,
25
+ mutual_info_classif,
26
+ mutual_info_regression,
27
+ r_regression,
28
+ SelectPercentile,
29
+ SelectKBest,
30
+ SelectFpr,
31
+ SelectFdr,
32
+ SelectFwe,
33
+ )
34
+
35
+
36
+ ##############################################################################
37
+ # Test the score functions
38
+
39
+
40
+ def test_f_oneway_vs_scipy_stats():
41
+ # Test that our f_oneway gives the same result as scipy.stats
42
+ rng = np.random.RandomState(0)
43
+ X1 = rng.randn(10, 3)
44
+ X2 = 1 + rng.randn(10, 3)
45
+ f, pv = stats.f_oneway(X1, X2)
46
+ f2, pv2 = f_oneway(X1, X2)
47
+ assert np.allclose(f, f2)
48
+ assert np.allclose(pv, pv2)
49
+
50
+
51
+ def test_f_oneway_ints():
52
+ # Smoke test f_oneway on integers: that it does raise casting errors
53
+ # with recent numpys
54
+ rng = np.random.RandomState(0)
55
+ X = rng.randint(10, size=(10, 10))
56
+ y = np.arange(10)
57
+ fint, pint = f_oneway(X, y)
58
+
59
+ # test that is gives the same result as with float
60
+ f, p = f_oneway(X.astype(float), y)
61
+ assert_array_almost_equal(f, fint, decimal=4)
62
+ assert_array_almost_equal(p, pint, decimal=4)
63
+
64
+
65
+ def test_f_classif():
66
+ # Test whether the F test yields meaningful results
67
+ # on a simple simulated classification problem
68
+ X, y = make_classification(
69
+ n_samples=200,
70
+ n_features=20,
71
+ n_informative=3,
72
+ n_redundant=2,
73
+ n_repeated=0,
74
+ n_classes=8,
75
+ n_clusters_per_class=1,
76
+ flip_y=0.0,
77
+ class_sep=10,
78
+ shuffle=False,
79
+ random_state=0,
80
+ )
81
+
82
+ F, pv = f_classif(X, y)
83
+ F_sparse, pv_sparse = f_classif(sparse.csr_matrix(X), y)
84
+ assert (F > 0).all()
85
+ assert (pv > 0).all()
86
+ assert (pv < 1).all()
87
+ assert (pv[:5] < 0.05).all()
88
+ assert (pv[5:] > 1.0e-4).all()
89
+ assert_array_almost_equal(F_sparse, F)
90
+ assert_array_almost_equal(pv_sparse, pv)
91
+
92
+
93
+ @pytest.mark.parametrize("center", [True, False])
94
+ def test_r_regression(center):
95
+ X, y = make_regression(
96
+ n_samples=2000, n_features=20, n_informative=5, shuffle=False, random_state=0
97
+ )
98
+
99
+ corr_coeffs = r_regression(X, y, center=center)
100
+ assert (-1 < corr_coeffs).all()
101
+ assert (corr_coeffs < 1).all()
102
+
103
+ sparse_X = _convert_container(X, "sparse")
104
+
105
+ sparse_corr_coeffs = r_regression(sparse_X, y, center=center)
106
+ assert_allclose(sparse_corr_coeffs, corr_coeffs)
107
+
108
+ # Testing against numpy for reference
109
+ Z = np.hstack((X, y[:, np.newaxis]))
110
+ correlation_matrix = np.corrcoef(Z, rowvar=False)
111
+ np_corr_coeffs = correlation_matrix[:-1, -1]
112
+ assert_array_almost_equal(np_corr_coeffs, corr_coeffs, decimal=3)
113
+
114
+
115
+ def test_f_regression():
116
+ # Test whether the F test yields meaningful results
117
+ # on a simple simulated regression problem
118
+ X, y = make_regression(
119
+ n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0
120
+ )
121
+
122
+ F, pv = f_regression(X, y)
123
+ assert (F > 0).all()
124
+ assert (pv > 0).all()
125
+ assert (pv < 1).all()
126
+ assert (pv[:5] < 0.05).all()
127
+ assert (pv[5:] > 1.0e-4).all()
128
+
129
+ # with centering, compare with sparse
130
+ F, pv = f_regression(X, y, center=True)
131
+ F_sparse, pv_sparse = f_regression(sparse.csr_matrix(X), y, center=True)
132
+ assert_allclose(F_sparse, F)
133
+ assert_allclose(pv_sparse, pv)
134
+
135
+ # again without centering, compare with sparse
136
+ F, pv = f_regression(X, y, center=False)
137
+ F_sparse, pv_sparse = f_regression(sparse.csr_matrix(X), y, center=False)
138
+ assert_allclose(F_sparse, F)
139
+ assert_allclose(pv_sparse, pv)
140
+
141
+
142
+ def test_f_regression_input_dtype():
143
+ # Test whether f_regression returns the same value
144
+ # for any numeric data_type
145
+ rng = np.random.RandomState(0)
146
+ X = rng.rand(10, 20)
147
+ y = np.arange(10).astype(int)
148
+
149
+ F1, pv1 = f_regression(X, y)
150
+ F2, pv2 = f_regression(X, y.astype(float))
151
+ assert_allclose(F1, F2, 5)
152
+ assert_allclose(pv1, pv2, 5)
153
+
154
+
155
+ def test_f_regression_center():
156
+ # Test whether f_regression preserves dof according to 'center' argument
157
+ # We use two centered variates so we have a simple relationship between
158
+ # F-score with variates centering and F-score without variates centering.
159
+ # Create toy example
160
+ X = np.arange(-5, 6).reshape(-1, 1) # X has zero mean
161
+ n_samples = X.size
162
+ Y = np.ones(n_samples)
163
+ Y[::2] *= -1.0
164
+ Y[0] = 0.0 # have Y mean being null
165
+
166
+ F1, _ = f_regression(X, Y, center=True)
167
+ F2, _ = f_regression(X, Y, center=False)
168
+ assert_allclose(F1 * (n_samples - 1.0) / (n_samples - 2.0), F2)
169
+ assert_almost_equal(F2[0], 0.232558139) # value from statsmodels OLS
170
+
171
+
172
+ @pytest.mark.parametrize(
173
+ "X, y, expected_corr_coef, force_finite",
174
+ [
175
+ (
176
+ # A feature in X is constant - forcing finite
177
+ np.array([[2, 1], [2, 0], [2, 10], [2, 4]]),
178
+ np.array([0, 1, 1, 0]),
179
+ np.array([0.0, 0.32075]),
180
+ True,
181
+ ),
182
+ (
183
+ # The target y is constant - forcing finite
184
+ np.array([[5, 1], [3, 0], [2, 10], [8, 4]]),
185
+ np.array([0, 0, 0, 0]),
186
+ np.array([0.0, 0.0]),
187
+ True,
188
+ ),
189
+ (
190
+ # A feature in X is constant - not forcing finite
191
+ np.array([[2, 1], [2, 0], [2, 10], [2, 4]]),
192
+ np.array([0, 1, 1, 0]),
193
+ np.array([np.nan, 0.32075]),
194
+ False,
195
+ ),
196
+ (
197
+ # The target y is constant - not forcing finite
198
+ np.array([[5, 1], [3, 0], [2, 10], [8, 4]]),
199
+ np.array([0, 0, 0, 0]),
200
+ np.array([np.nan, np.nan]),
201
+ False,
202
+ ),
203
+ ],
204
+ )
205
+ def test_r_regression_force_finite(X, y, expected_corr_coef, force_finite):
206
+ """Check the behaviour of `force_finite` for some corner cases with `r_regression`.
207
+
208
+ Non-regression test for:
209
+ https://github.com/scikit-learn/scikit-learn/issues/15672
210
+ """
211
+ with warnings.catch_warnings():
212
+ warnings.simplefilter("error", RuntimeWarning)
213
+ corr_coef = r_regression(X, y, force_finite=force_finite)
214
+ np.testing.assert_array_almost_equal(corr_coef, expected_corr_coef)
215
+
216
+
217
+ @pytest.mark.parametrize(
218
+ "X, y, expected_f_statistic, expected_p_values, force_finite",
219
+ [
220
+ (
221
+ # A feature in X is constant - forcing finite
222
+ np.array([[2, 1], [2, 0], [2, 10], [2, 4]]),
223
+ np.array([0, 1, 1, 0]),
224
+ np.array([0.0, 0.2293578]),
225
+ np.array([1.0, 0.67924985]),
226
+ True,
227
+ ),
228
+ (
229
+ # The target y is constant - forcing finite
230
+ np.array([[5, 1], [3, 0], [2, 10], [8, 4]]),
231
+ np.array([0, 0, 0, 0]),
232
+ np.array([0.0, 0.0]),
233
+ np.array([1.0, 1.0]),
234
+ True,
235
+ ),
236
+ (
237
+ # Feature in X correlated with y - forcing finite
238
+ np.array([[0, 1], [1, 0], [2, 10], [3, 4]]),
239
+ np.array([0, 1, 2, 3]),
240
+ np.array([np.finfo(np.float64).max, 0.845433]),
241
+ np.array([0.0, 0.454913]),
242
+ True,
243
+ ),
244
+ (
245
+ # Feature in X anti-correlated with y - forcing finite
246
+ np.array([[3, 1], [2, 0], [1, 10], [0, 4]]),
247
+ np.array([0, 1, 2, 3]),
248
+ np.array([np.finfo(np.float64).max, 0.845433]),
249
+ np.array([0.0, 0.454913]),
250
+ True,
251
+ ),
252
+ (
253
+ # A feature in X is constant - not forcing finite
254
+ np.array([[2, 1], [2, 0], [2, 10], [2, 4]]),
255
+ np.array([0, 1, 1, 0]),
256
+ np.array([np.nan, 0.2293578]),
257
+ np.array([np.nan, 0.67924985]),
258
+ False,
259
+ ),
260
+ (
261
+ # The target y is constant - not forcing finite
262
+ np.array([[5, 1], [3, 0], [2, 10], [8, 4]]),
263
+ np.array([0, 0, 0, 0]),
264
+ np.array([np.nan, np.nan]),
265
+ np.array([np.nan, np.nan]),
266
+ False,
267
+ ),
268
+ (
269
+ # Feature in X correlated with y - not forcing finite
270
+ np.array([[0, 1], [1, 0], [2, 10], [3, 4]]),
271
+ np.array([0, 1, 2, 3]),
272
+ np.array([np.inf, 0.845433]),
273
+ np.array([0.0, 0.454913]),
274
+ False,
275
+ ),
276
+ (
277
+ # Feature in X anti-correlated with y - not forcing finite
278
+ np.array([[3, 1], [2, 0], [1, 10], [0, 4]]),
279
+ np.array([0, 1, 2, 3]),
280
+ np.array([np.inf, 0.845433]),
281
+ np.array([0.0, 0.454913]),
282
+ False,
283
+ ),
284
+ ],
285
+ )
286
+ def test_f_regression_corner_case(
287
+ X, y, expected_f_statistic, expected_p_values, force_finite
288
+ ):
289
+ """Check the behaviour of `force_finite` for some corner cases with `f_regression`.
290
+
291
+ Non-regression test for:
292
+ https://github.com/scikit-learn/scikit-learn/issues/15672
293
+ """
294
+ with warnings.catch_warnings():
295
+ warnings.simplefilter("error", RuntimeWarning)
296
+ f_statistic, p_values = f_regression(X, y, force_finite=force_finite)
297
+ np.testing.assert_array_almost_equal(f_statistic, expected_f_statistic)
298
+ np.testing.assert_array_almost_equal(p_values, expected_p_values)
299
+
300
+
301
+ def test_f_classif_multi_class():
302
+ # Test whether the F test yields meaningful results
303
+ # on a simple simulated classification problem
304
+ X, y = make_classification(
305
+ n_samples=200,
306
+ n_features=20,
307
+ n_informative=3,
308
+ n_redundant=2,
309
+ n_repeated=0,
310
+ n_classes=8,
311
+ n_clusters_per_class=1,
312
+ flip_y=0.0,
313
+ class_sep=10,
314
+ shuffle=False,
315
+ random_state=0,
316
+ )
317
+
318
+ F, pv = f_classif(X, y)
319
+ assert (F > 0).all()
320
+ assert (pv > 0).all()
321
+ assert (pv < 1).all()
322
+ assert (pv[:5] < 0.05).all()
323
+ assert (pv[5:] > 1.0e-4).all()
324
+
325
+
326
+ def test_select_percentile_classif():
327
+ # Test whether the relative univariate feature selection
328
+ # gets the correct items in a simple classification problem
329
+ # with the percentile heuristic
330
+ X, y = make_classification(
331
+ n_samples=200,
332
+ n_features=20,
333
+ n_informative=3,
334
+ n_redundant=2,
335
+ n_repeated=0,
336
+ n_classes=8,
337
+ n_clusters_per_class=1,
338
+ flip_y=0.0,
339
+ class_sep=10,
340
+ shuffle=False,
341
+ random_state=0,
342
+ )
343
+
344
+ univariate_filter = SelectPercentile(f_classif, percentile=25)
345
+ X_r = univariate_filter.fit(X, y).transform(X)
346
+ X_r2 = (
347
+ GenericUnivariateSelect(f_classif, mode="percentile", param=25)
348
+ .fit(X, y)
349
+ .transform(X)
350
+ )
351
+ assert_array_equal(X_r, X_r2)
352
+ support = univariate_filter.get_support()
353
+ gtruth = np.zeros(20)
354
+ gtruth[:5] = 1
355
+ assert_array_equal(support, gtruth)
356
+
357
+
358
+ def test_select_percentile_classif_sparse():
359
+ # Test whether the relative univariate feature selection
360
+ # gets the correct items in a simple classification problem
361
+ # with the percentile heuristic
362
+ X, y = make_classification(
363
+ n_samples=200,
364
+ n_features=20,
365
+ n_informative=3,
366
+ n_redundant=2,
367
+ n_repeated=0,
368
+ n_classes=8,
369
+ n_clusters_per_class=1,
370
+ flip_y=0.0,
371
+ class_sep=10,
372
+ shuffle=False,
373
+ random_state=0,
374
+ )
375
+ X = sparse.csr_matrix(X)
376
+ univariate_filter = SelectPercentile(f_classif, percentile=25)
377
+ X_r = univariate_filter.fit(X, y).transform(X)
378
+ X_r2 = (
379
+ GenericUnivariateSelect(f_classif, mode="percentile", param=25)
380
+ .fit(X, y)
381
+ .transform(X)
382
+ )
383
+ assert_array_equal(X_r.toarray(), X_r2.toarray())
384
+ support = univariate_filter.get_support()
385
+ gtruth = np.zeros(20)
386
+ gtruth[:5] = 1
387
+ assert_array_equal(support, gtruth)
388
+
389
+ X_r2inv = univariate_filter.inverse_transform(X_r2)
390
+ assert sparse.issparse(X_r2inv)
391
+ support_mask = safe_mask(X_r2inv, support)
392
+ assert X_r2inv.shape == X.shape
393
+ assert_array_equal(X_r2inv[:, support_mask].toarray(), X_r.toarray())
394
+ # Check other columns are empty
395
+ assert X_r2inv.getnnz() == X_r.getnnz()
396
+
397
+
398
+ ##############################################################################
399
+ # Test univariate selection in classification settings
400
+
401
+
402
+ def test_select_kbest_classif():
403
+ # Test whether the relative univariate feature selection
404
+ # gets the correct items in a simple classification problem
405
+ # with the k best heuristic
406
+ X, y = make_classification(
407
+ n_samples=200,
408
+ n_features=20,
409
+ n_informative=3,
410
+ n_redundant=2,
411
+ n_repeated=0,
412
+ n_classes=8,
413
+ n_clusters_per_class=1,
414
+ flip_y=0.0,
415
+ class_sep=10,
416
+ shuffle=False,
417
+ random_state=0,
418
+ )
419
+
420
+ univariate_filter = SelectKBest(f_classif, k=5)
421
+ X_r = univariate_filter.fit(X, y).transform(X)
422
+ X_r2 = (
423
+ GenericUnivariateSelect(f_classif, mode="k_best", param=5)
424
+ .fit(X, y)
425
+ .transform(X)
426
+ )
427
+ assert_array_equal(X_r, X_r2)
428
+ support = univariate_filter.get_support()
429
+ gtruth = np.zeros(20)
430
+ gtruth[:5] = 1
431
+ assert_array_equal(support, gtruth)
432
+
433
+
434
+ def test_select_kbest_all():
435
+ # Test whether k="all" correctly returns all features.
436
+ X, y = make_classification(
437
+ n_samples=20, n_features=10, shuffle=False, random_state=0
438
+ )
439
+
440
+ univariate_filter = SelectKBest(f_classif, k="all")
441
+ X_r = univariate_filter.fit(X, y).transform(X)
442
+ assert_array_equal(X, X_r)
443
+ # Non-regression test for:
444
+ # https://github.com/scikit-learn/scikit-learn/issues/24949
445
+ X_r2 = (
446
+ GenericUnivariateSelect(f_classif, mode="k_best", param="all")
447
+ .fit(X, y)
448
+ .transform(X)
449
+ )
450
+ assert_array_equal(X_r, X_r2)
451
+
452
+
453
+ @pytest.mark.parametrize("dtype_in", [np.float32, np.float64])
454
+ def test_select_kbest_zero(dtype_in):
455
+ # Test whether k=0 correctly returns no features.
456
+ X, y = make_classification(
457
+ n_samples=20, n_features=10, shuffle=False, random_state=0
458
+ )
459
+ X = X.astype(dtype_in)
460
+
461
+ univariate_filter = SelectKBest(f_classif, k=0)
462
+ univariate_filter.fit(X, y)
463
+ support = univariate_filter.get_support()
464
+ gtruth = np.zeros(10, dtype=bool)
465
+ assert_array_equal(support, gtruth)
466
+ with pytest.warns(UserWarning, match="No features were selected"):
467
+ X_selected = univariate_filter.transform(X)
468
+ assert X_selected.shape == (20, 0)
469
+ assert X_selected.dtype == dtype_in
470
+
471
+
472
+ def test_select_heuristics_classif():
473
+ # Test whether the relative univariate feature selection
474
+ # gets the correct items in a simple classification problem
475
+ # with the fdr, fwe and fpr heuristics
476
+ X, y = make_classification(
477
+ n_samples=200,
478
+ n_features=20,
479
+ n_informative=3,
480
+ n_redundant=2,
481
+ n_repeated=0,
482
+ n_classes=8,
483
+ n_clusters_per_class=1,
484
+ flip_y=0.0,
485
+ class_sep=10,
486
+ shuffle=False,
487
+ random_state=0,
488
+ )
489
+
490
+ univariate_filter = SelectFwe(f_classif, alpha=0.01)
491
+ X_r = univariate_filter.fit(X, y).transform(X)
492
+ gtruth = np.zeros(20)
493
+ gtruth[:5] = 1
494
+ for mode in ["fdr", "fpr", "fwe"]:
495
+ X_r2 = (
496
+ GenericUnivariateSelect(f_classif, mode=mode, param=0.01)
497
+ .fit(X, y)
498
+ .transform(X)
499
+ )
500
+ assert_array_equal(X_r, X_r2)
501
+ support = univariate_filter.get_support()
502
+ assert_allclose(support, gtruth)
503
+
504
+
505
+ ##############################################################################
506
+ # Test univariate selection in regression settings
507
+
508
+
509
+ def assert_best_scores_kept(score_filter):
510
+ scores = score_filter.scores_
511
+ support = score_filter.get_support()
512
+ assert_allclose(np.sort(scores[support]), np.sort(scores)[-support.sum() :])
513
+
514
+
515
+ def test_select_percentile_regression():
516
+ # Test whether the relative univariate feature selection
517
+ # gets the correct items in a simple regression problem
518
+ # with the percentile heuristic
519
+ X, y = make_regression(
520
+ n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0
521
+ )
522
+
523
+ univariate_filter = SelectPercentile(f_regression, percentile=25)
524
+ X_r = univariate_filter.fit(X, y).transform(X)
525
+ assert_best_scores_kept(univariate_filter)
526
+ X_r2 = (
527
+ GenericUnivariateSelect(f_regression, mode="percentile", param=25)
528
+ .fit(X, y)
529
+ .transform(X)
530
+ )
531
+ assert_array_equal(X_r, X_r2)
532
+ support = univariate_filter.get_support()
533
+ gtruth = np.zeros(20)
534
+ gtruth[:5] = 1
535
+ assert_array_equal(support, gtruth)
536
+ X_2 = X.copy()
537
+ X_2[:, np.logical_not(support)] = 0
538
+ assert_array_equal(X_2, univariate_filter.inverse_transform(X_r))
539
+ # Check inverse_transform respects dtype
540
+ assert_array_equal(
541
+ X_2.astype(bool), univariate_filter.inverse_transform(X_r.astype(bool))
542
+ )
543
+
544
+
545
+ def test_select_percentile_regression_full():
546
+ # Test whether the relative univariate feature selection
547
+ # selects all features when '100%' is asked.
548
+ X, y = make_regression(
549
+ n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0
550
+ )
551
+
552
+ univariate_filter = SelectPercentile(f_regression, percentile=100)
553
+ X_r = univariate_filter.fit(X, y).transform(X)
554
+ assert_best_scores_kept(univariate_filter)
555
+ X_r2 = (
556
+ GenericUnivariateSelect(f_regression, mode="percentile", param=100)
557
+ .fit(X, y)
558
+ .transform(X)
559
+ )
560
+ assert_array_equal(X_r, X_r2)
561
+ support = univariate_filter.get_support()
562
+ gtruth = np.ones(20)
563
+ assert_array_equal(support, gtruth)
564
+
565
+
566
+ def test_select_kbest_regression():
567
+ # Test whether the relative univariate feature selection
568
+ # gets the correct items in a simple regression problem
569
+ # with the k best heuristic
570
+ X, y = make_regression(
571
+ n_samples=200,
572
+ n_features=20,
573
+ n_informative=5,
574
+ shuffle=False,
575
+ random_state=0,
576
+ noise=10,
577
+ )
578
+
579
+ univariate_filter = SelectKBest(f_regression, k=5)
580
+ X_r = univariate_filter.fit(X, y).transform(X)
581
+ assert_best_scores_kept(univariate_filter)
582
+ X_r2 = (
583
+ GenericUnivariateSelect(f_regression, mode="k_best", param=5)
584
+ .fit(X, y)
585
+ .transform(X)
586
+ )
587
+ assert_array_equal(X_r, X_r2)
588
+ support = univariate_filter.get_support()
589
+ gtruth = np.zeros(20)
590
+ gtruth[:5] = 1
591
+ assert_array_equal(support, gtruth)
592
+
593
+
594
+ def test_select_heuristics_regression():
595
+ # Test whether the relative univariate feature selection
596
+ # gets the correct items in a simple regression problem
597
+ # with the fpr, fdr or fwe heuristics
598
+ X, y = make_regression(
599
+ n_samples=200,
600
+ n_features=20,
601
+ n_informative=5,
602
+ shuffle=False,
603
+ random_state=0,
604
+ noise=10,
605
+ )
606
+
607
+ univariate_filter = SelectFpr(f_regression, alpha=0.01)
608
+ X_r = univariate_filter.fit(X, y).transform(X)
609
+ gtruth = np.zeros(20)
610
+ gtruth[:5] = 1
611
+ for mode in ["fdr", "fpr", "fwe"]:
612
+ X_r2 = (
613
+ GenericUnivariateSelect(f_regression, mode=mode, param=0.01)
614
+ .fit(X, y)
615
+ .transform(X)
616
+ )
617
+ assert_array_equal(X_r, X_r2)
618
+ support = univariate_filter.get_support()
619
+ assert_array_equal(support[:5], np.ones((5,), dtype=bool))
620
+ assert np.sum(support[5:] == 1) < 3
621
+
622
+
623
+ def test_boundary_case_ch2():
624
+ # Test boundary case, and always aim to select 1 feature.
625
+ X = np.array([[10, 20], [20, 20], [20, 30]])
626
+ y = np.array([[1], [0], [0]])
627
+ scores, pvalues = chi2(X, y)
628
+ assert_array_almost_equal(scores, np.array([4.0, 0.71428571]))
629
+ assert_array_almost_equal(pvalues, np.array([0.04550026, 0.39802472]))
630
+
631
+ filter_fdr = SelectFdr(chi2, alpha=0.1)
632
+ filter_fdr.fit(X, y)
633
+ support_fdr = filter_fdr.get_support()
634
+ assert_array_equal(support_fdr, np.array([True, False]))
635
+
636
+ filter_kbest = SelectKBest(chi2, k=1)
637
+ filter_kbest.fit(X, y)
638
+ support_kbest = filter_kbest.get_support()
639
+ assert_array_equal(support_kbest, np.array([True, False]))
640
+
641
+ filter_percentile = SelectPercentile(chi2, percentile=50)
642
+ filter_percentile.fit(X, y)
643
+ support_percentile = filter_percentile.get_support()
644
+ assert_array_equal(support_percentile, np.array([True, False]))
645
+
646
+ filter_fpr = SelectFpr(chi2, alpha=0.1)
647
+ filter_fpr.fit(X, y)
648
+ support_fpr = filter_fpr.get_support()
649
+ assert_array_equal(support_fpr, np.array([True, False]))
650
+
651
+ filter_fwe = SelectFwe(chi2, alpha=0.1)
652
+ filter_fwe.fit(X, y)
653
+ support_fwe = filter_fwe.get_support()
654
+ assert_array_equal(support_fwe, np.array([True, False]))
655
+
656
+
657
+ @pytest.mark.parametrize("alpha", [0.001, 0.01, 0.1])
658
+ @pytest.mark.parametrize("n_informative", [1, 5, 10])
659
+ def test_select_fdr_regression(alpha, n_informative):
660
+ # Test that fdr heuristic actually has low FDR.
661
+ def single_fdr(alpha, n_informative, random_state):
662
+ X, y = make_regression(
663
+ n_samples=150,
664
+ n_features=20,
665
+ n_informative=n_informative,
666
+ shuffle=False,
667
+ random_state=random_state,
668
+ noise=10,
669
+ )
670
+
671
+ with warnings.catch_warnings(record=True):
672
+ # Warnings can be raised when no features are selected
673
+ # (low alpha or very noisy data)
674
+ univariate_filter = SelectFdr(f_regression, alpha=alpha)
675
+ X_r = univariate_filter.fit(X, y).transform(X)
676
+ X_r2 = (
677
+ GenericUnivariateSelect(f_regression, mode="fdr", param=alpha)
678
+ .fit(X, y)
679
+ .transform(X)
680
+ )
681
+
682
+ assert_array_equal(X_r, X_r2)
683
+ support = univariate_filter.get_support()
684
+ num_false_positives = np.sum(support[n_informative:] == 1)
685
+ num_true_positives = np.sum(support[:n_informative] == 1)
686
+
687
+ if num_false_positives == 0:
688
+ return 0.0
689
+ false_discovery_rate = num_false_positives / (
690
+ num_true_positives + num_false_positives
691
+ )
692
+ return false_discovery_rate
693
+
694
+ # As per Benjamini-Hochberg, the expected false discovery rate
695
+ # should be lower than alpha:
696
+ # FDR = E(FP / (TP + FP)) <= alpha
697
+ false_discovery_rate = np.mean(
698
+ [single_fdr(alpha, n_informative, random_state) for random_state in range(100)]
699
+ )
700
+ assert alpha >= false_discovery_rate
701
+
702
+ # Make sure that the empirical false discovery rate increases
703
+ # with alpha:
704
+ if false_discovery_rate != 0:
705
+ assert false_discovery_rate > alpha / 10
706
+
707
+
708
+ def test_select_fwe_regression():
709
+ # Test whether the relative univariate feature selection
710
+ # gets the correct items in a simple regression problem
711
+ # with the fwe heuristic
712
+ X, y = make_regression(
713
+ n_samples=200, n_features=20, n_informative=5, shuffle=False, random_state=0
714
+ )
715
+
716
+ univariate_filter = SelectFwe(f_regression, alpha=0.01)
717
+ X_r = univariate_filter.fit(X, y).transform(X)
718
+ X_r2 = (
719
+ GenericUnivariateSelect(f_regression, mode="fwe", param=0.01)
720
+ .fit(X, y)
721
+ .transform(X)
722
+ )
723
+ assert_array_equal(X_r, X_r2)
724
+ support = univariate_filter.get_support()
725
+ gtruth = np.zeros(20)
726
+ gtruth[:5] = 1
727
+ assert_array_equal(support[:5], np.ones((5,), dtype=bool))
728
+ assert np.sum(support[5:] == 1) < 2
729
+
730
+
731
+ def test_selectkbest_tiebreaking():
732
+ # Test whether SelectKBest actually selects k features in case of ties.
733
+ # Prior to 0.11, SelectKBest would return more features than requested.
734
+ Xs = [[0, 1, 1], [0, 0, 1], [1, 0, 0], [1, 1, 0]]
735
+ y = [1]
736
+ dummy_score = lambda X, y: (X[0], X[0])
737
+ for X in Xs:
738
+ sel = SelectKBest(dummy_score, k=1)
739
+ X1 = ignore_warnings(sel.fit_transform)([X], y)
740
+ assert X1.shape[1] == 1
741
+ assert_best_scores_kept(sel)
742
+
743
+ sel = SelectKBest(dummy_score, k=2)
744
+ X2 = ignore_warnings(sel.fit_transform)([X], y)
745
+ assert X2.shape[1] == 2
746
+ assert_best_scores_kept(sel)
747
+
748
+
749
+ def test_selectpercentile_tiebreaking():
750
+ # Test if SelectPercentile selects the right n_features in case of ties.
751
+ Xs = [[0, 1, 1], [0, 0, 1], [1, 0, 0], [1, 1, 0]]
752
+ y = [1]
753
+ dummy_score = lambda X, y: (X[0], X[0])
754
+ for X in Xs:
755
+ sel = SelectPercentile(dummy_score, percentile=34)
756
+ X1 = ignore_warnings(sel.fit_transform)([X], y)
757
+ assert X1.shape[1] == 1
758
+ assert_best_scores_kept(sel)
759
+
760
+ sel = SelectPercentile(dummy_score, percentile=67)
761
+ X2 = ignore_warnings(sel.fit_transform)([X], y)
762
+ assert X2.shape[1] == 2
763
+ assert_best_scores_kept(sel)
764
+
765
+
766
+ def test_tied_pvalues():
767
+ # Test whether k-best and percentiles work with tied pvalues from chi2.
768
+ # chi2 will return the same p-values for the following features, but it
769
+ # will return different scores.
770
+ X0 = np.array([[10000, 9999, 9998], [1, 1, 1]])
771
+ y = [0, 1]
772
+
773
+ for perm in itertools.permutations((0, 1, 2)):
774
+ X = X0[:, perm]
775
+ Xt = SelectKBest(chi2, k=2).fit_transform(X, y)
776
+ assert Xt.shape == (2, 2)
777
+ assert 9998 not in Xt
778
+
779
+ Xt = SelectPercentile(chi2, percentile=67).fit_transform(X, y)
780
+ assert Xt.shape == (2, 2)
781
+ assert 9998 not in Xt
782
+
783
+
784
+ def test_scorefunc_multilabel():
785
+ # Test whether k-best and percentiles works with multilabels with chi2.
786
+
787
+ X = np.array([[10000, 9999, 0], [100, 9999, 0], [1000, 99, 0]])
788
+ y = [[1, 1], [0, 1], [1, 0]]
789
+
790
+ Xt = SelectKBest(chi2, k=2).fit_transform(X, y)
791
+ assert Xt.shape == (3, 2)
792
+ assert 0 not in Xt
793
+
794
+ Xt = SelectPercentile(chi2, percentile=67).fit_transform(X, y)
795
+ assert Xt.shape == (3, 2)
796
+ assert 0 not in Xt
797
+
798
+
799
+ def test_tied_scores():
800
+ # Test for stable sorting in k-best with tied scores.
801
+ X_train = np.array([[0, 0, 0], [1, 1, 1]])
802
+ y_train = [0, 1]
803
+
804
+ for n_features in [1, 2, 3]:
805
+ sel = SelectKBest(chi2, k=n_features).fit(X_train, y_train)
806
+ X_test = sel.transform([[0, 1, 2]])
807
+ assert_array_equal(X_test[0], np.arange(3)[-n_features:])
808
+
809
+
810
+ def test_nans():
811
+ # Assert that SelectKBest and SelectPercentile can handle NaNs.
812
+ # First feature has zero variance to confuse f_classif (ANOVA) and
813
+ # make it return a NaN.
814
+ X = [[0, 1, 0], [0, -1, -1], [0, 0.5, 0.5]]
815
+ y = [1, 0, 1]
816
+
817
+ for select in (
818
+ SelectKBest(f_classif, k=2),
819
+ SelectPercentile(f_classif, percentile=67),
820
+ ):
821
+ ignore_warnings(select.fit)(X, y)
822
+ assert_array_equal(select.get_support(indices=True), np.array([1, 2]))
823
+
824
+
825
+ def test_invalid_k():
826
+ X = [[0, 1, 0], [0, -1, -1], [0, 0.5, 0.5]]
827
+ y = [1, 0, 1]
828
+
829
+ with pytest.raises(ValueError):
830
+ SelectKBest(k=4).fit(X, y)
831
+ with pytest.raises(ValueError):
832
+ GenericUnivariateSelect(mode="k_best", param=4).fit(X, y)
833
+
834
+
835
+ def test_f_classif_constant_feature():
836
+ # Test that f_classif warns if a feature is constant throughout.
837
+
838
+ X, y = make_classification(n_samples=10, n_features=5)
839
+ X[:, 0] = 2.0
840
+ with pytest.warns(UserWarning):
841
+ f_classif(X, y)
842
+
843
+
844
+ def test_no_feature_selected():
845
+ rng = np.random.RandomState(0)
846
+
847
+ # Generate random uncorrelated data: a strict univariate test should
848
+ # rejects all the features
849
+ X = rng.rand(40, 10)
850
+ y = rng.randint(0, 4, size=40)
851
+ strict_selectors = [
852
+ SelectFwe(alpha=0.01).fit(X, y),
853
+ SelectFdr(alpha=0.01).fit(X, y),
854
+ SelectFpr(alpha=0.01).fit(X, y),
855
+ SelectPercentile(percentile=0).fit(X, y),
856
+ SelectKBest(k=0).fit(X, y),
857
+ ]
858
+ for selector in strict_selectors:
859
+ assert_array_equal(selector.get_support(), np.zeros(10))
860
+ with pytest.warns(UserWarning, match="No features were selected"):
861
+ X_selected = selector.transform(X)
862
+ assert X_selected.shape == (40, 0)
863
+
864
+
865
+ def test_mutual_info_classif():
866
+ X, y = make_classification(
867
+ n_samples=100,
868
+ n_features=5,
869
+ n_informative=1,
870
+ n_redundant=1,
871
+ n_repeated=0,
872
+ n_classes=2,
873
+ n_clusters_per_class=1,
874
+ flip_y=0.0,
875
+ class_sep=10,
876
+ shuffle=False,
877
+ random_state=0,
878
+ )
879
+
880
+ # Test in KBest mode.
881
+ univariate_filter = SelectKBest(mutual_info_classif, k=2)
882
+ X_r = univariate_filter.fit(X, y).transform(X)
883
+ X_r2 = (
884
+ GenericUnivariateSelect(mutual_info_classif, mode="k_best", param=2)
885
+ .fit(X, y)
886
+ .transform(X)
887
+ )
888
+ assert_array_equal(X_r, X_r2)
889
+ support = univariate_filter.get_support()
890
+ gtruth = np.zeros(5)
891
+ gtruth[:2] = 1
892
+ assert_array_equal(support, gtruth)
893
+
894
+ # Test in Percentile mode.
895
+ univariate_filter = SelectPercentile(mutual_info_classif, percentile=40)
896
+ X_r = univariate_filter.fit(X, y).transform(X)
897
+ X_r2 = (
898
+ GenericUnivariateSelect(mutual_info_classif, mode="percentile", param=40)
899
+ .fit(X, y)
900
+ .transform(X)
901
+ )
902
+ assert_array_equal(X_r, X_r2)
903
+ support = univariate_filter.get_support()
904
+ gtruth = np.zeros(5)
905
+ gtruth[:2] = 1
906
+ assert_array_equal(support, gtruth)
907
+
908
+
909
+ def test_mutual_info_regression():
910
+ X, y = make_regression(
911
+ n_samples=100,
912
+ n_features=10,
913
+ n_informative=2,
914
+ shuffle=False,
915
+ random_state=0,
916
+ noise=10,
917
+ )
918
+
919
+ # Test in KBest mode.
920
+ univariate_filter = SelectKBest(mutual_info_regression, k=2)
921
+ X_r = univariate_filter.fit(X, y).transform(X)
922
+ assert_best_scores_kept(univariate_filter)
923
+ X_r2 = (
924
+ GenericUnivariateSelect(mutual_info_regression, mode="k_best", param=2)
925
+ .fit(X, y)
926
+ .transform(X)
927
+ )
928
+ assert_array_equal(X_r, X_r2)
929
+ support = univariate_filter.get_support()
930
+ gtruth = np.zeros(10)
931
+ gtruth[:2] = 1
932
+ assert_array_equal(support, gtruth)
933
+
934
+ # Test in Percentile mode.
935
+ univariate_filter = SelectPercentile(mutual_info_regression, percentile=20)
936
+ X_r = univariate_filter.fit(X, y).transform(X)
937
+ X_r2 = (
938
+ GenericUnivariateSelect(mutual_info_regression, mode="percentile", param=20)
939
+ .fit(X, y)
940
+ .transform(X)
941
+ )
942
+ assert_array_equal(X_r, X_r2)
943
+ support = univariate_filter.get_support()
944
+ gtruth = np.zeros(10)
945
+ gtruth[:2] = 1
946
+ assert_array_equal(support, gtruth)
videollama2/lib/python3.10/site-packages/sklearn/tree/_classes.py ADDED
@@ -0,0 +1,1769 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module gathers tree-based methods, including decision, regression and
3
+ randomized trees. Single and multi-output problems are both handled.
4
+ """
5
+
6
+ # Authors: Gilles Louppe <g.louppe@gmail.com>
7
+ # Peter Prettenhofer <peter.prettenhofer@gmail.com>
8
+ # Brian Holt <bdholt1@gmail.com>
9
+ # Noel Dawe <noel@dawe.me>
10
+ # Satrajit Gosh <satrajit.ghosh@gmail.com>
11
+ # Joly Arnaud <arnaud.v.joly@gmail.com>
12
+ # Fares Hedayati <fares.hedayati@gmail.com>
13
+ # Nelson Liu <nelson@nelsonliu.me>
14
+ #
15
+ # License: BSD 3 clause
16
+
17
+ import numbers
18
+ import warnings
19
+ import copy
20
+ from abc import ABCMeta
21
+ from abc import abstractmethod
22
+ from math import ceil
23
+ from numbers import Integral, Real
24
+
25
+ import numpy as np
26
+ from scipy.sparse import issparse
27
+
28
+ from ..base import BaseEstimator
29
+ from ..base import ClassifierMixin
30
+ from ..base import clone
31
+ from ..base import RegressorMixin
32
+ from ..base import is_classifier
33
+ from ..base import MultiOutputMixin
34
+ from ..utils import Bunch
35
+ from ..utils import check_random_state
36
+ from ..utils.validation import _check_sample_weight
37
+ from ..utils import compute_sample_weight
38
+ from ..utils.multiclass import check_classification_targets
39
+ from ..utils.validation import check_is_fitted
40
+ from ..utils._param_validation import Hidden, Interval, StrOptions
41
+
42
+ from ._criterion import Criterion
43
+ from ._splitter import Splitter
44
+ from ._tree import DepthFirstTreeBuilder
45
+ from ._tree import BestFirstTreeBuilder
46
+ from ._tree import Tree
47
+ from ._tree import _build_pruned_tree_ccp
48
+ from ._tree import ccp_pruning_path
49
+ from . import _tree, _splitter, _criterion
50
+
51
+ __all__ = [
52
+ "DecisionTreeClassifier",
53
+ "DecisionTreeRegressor",
54
+ "ExtraTreeClassifier",
55
+ "ExtraTreeRegressor",
56
+ ]
57
+
58
+
59
+ # =============================================================================
60
+ # Types and constants
61
+ # =============================================================================
62
+
63
+ DTYPE = _tree.DTYPE
64
+ DOUBLE = _tree.DOUBLE
65
+
66
+ CRITERIA_CLF = {
67
+ "gini": _criterion.Gini,
68
+ "log_loss": _criterion.Entropy,
69
+ "entropy": _criterion.Entropy,
70
+ }
71
+ CRITERIA_REG = {
72
+ "squared_error": _criterion.MSE,
73
+ "friedman_mse": _criterion.FriedmanMSE,
74
+ "absolute_error": _criterion.MAE,
75
+ "poisson": _criterion.Poisson,
76
+ }
77
+
78
+ DENSE_SPLITTERS = {"best": _splitter.BestSplitter, "random": _splitter.RandomSplitter}
79
+
80
+ SPARSE_SPLITTERS = {
81
+ "best": _splitter.BestSparseSplitter,
82
+ "random": _splitter.RandomSparseSplitter,
83
+ }
84
+
85
+ # =============================================================================
86
+ # Base decision tree
87
+ # =============================================================================
88
+
89
+
90
+ class BaseDecisionTree(MultiOutputMixin, BaseEstimator, metaclass=ABCMeta):
91
+ """Base class for decision trees.
92
+
93
+ Warning: This class should not be used directly.
94
+ Use derived classes instead.
95
+ """
96
+
97
+ _parameter_constraints: dict = {
98
+ "splitter": [StrOptions({"best", "random"})],
99
+ "max_depth": [Interval(Integral, 1, None, closed="left"), None],
100
+ "min_samples_split": [
101
+ Interval(Integral, 2, None, closed="left"),
102
+ Interval("real_not_int", 0.0, 1.0, closed="right"),
103
+ ],
104
+ "min_samples_leaf": [
105
+ Interval(Integral, 1, None, closed="left"),
106
+ Interval("real_not_int", 0.0, 1.0, closed="neither"),
107
+ ],
108
+ "min_weight_fraction_leaf": [Interval(Real, 0.0, 0.5, closed="both")],
109
+ "max_features": [
110
+ Interval(Integral, 1, None, closed="left"),
111
+ Interval("real_not_int", 0.0, 1.0, closed="right"),
112
+ StrOptions({"auto", "sqrt", "log2"}, deprecated={"auto"}),
113
+ None,
114
+ ],
115
+ "random_state": ["random_state"],
116
+ "max_leaf_nodes": [Interval(Integral, 2, None, closed="left"), None],
117
+ "min_impurity_decrease": [Interval(Real, 0.0, None, closed="left")],
118
+ "ccp_alpha": [Interval(Real, 0.0, None, closed="left")],
119
+ }
120
+
121
+ @abstractmethod
122
+ def __init__(
123
+ self,
124
+ *,
125
+ criterion,
126
+ splitter,
127
+ max_depth,
128
+ min_samples_split,
129
+ min_samples_leaf,
130
+ min_weight_fraction_leaf,
131
+ max_features,
132
+ max_leaf_nodes,
133
+ random_state,
134
+ min_impurity_decrease,
135
+ class_weight=None,
136
+ ccp_alpha=0.0,
137
+ ):
138
+ self.criterion = criterion
139
+ self.splitter = splitter
140
+ self.max_depth = max_depth
141
+ self.min_samples_split = min_samples_split
142
+ self.min_samples_leaf = min_samples_leaf
143
+ self.min_weight_fraction_leaf = min_weight_fraction_leaf
144
+ self.max_features = max_features
145
+ self.max_leaf_nodes = max_leaf_nodes
146
+ self.random_state = random_state
147
+ self.min_impurity_decrease = min_impurity_decrease
148
+ self.class_weight = class_weight
149
+ self.ccp_alpha = ccp_alpha
150
+
151
+ def get_depth(self):
152
+ """Return the depth of the decision tree.
153
+
154
+ The depth of a tree is the maximum distance between the root
155
+ and any leaf.
156
+
157
+ Returns
158
+ -------
159
+ self.tree_.max_depth : int
160
+ The maximum depth of the tree.
161
+ """
162
+ check_is_fitted(self)
163
+ return self.tree_.max_depth
164
+
165
+ def get_n_leaves(self):
166
+ """Return the number of leaves of the decision tree.
167
+
168
+ Returns
169
+ -------
170
+ self.tree_.n_leaves : int
171
+ Number of leaves.
172
+ """
173
+ check_is_fitted(self)
174
+ return self.tree_.n_leaves
175
+
176
+ def fit(self, X, y, sample_weight=None, check_input=True):
177
+ self._validate_params()
178
+ random_state = check_random_state(self.random_state)
179
+
180
+ if check_input:
181
+ # Need to validate separately here.
182
+ # We can't pass multi_output=True because that would allow y to be
183
+ # csr.
184
+ check_X_params = dict(dtype=DTYPE, accept_sparse="csc")
185
+ check_y_params = dict(ensure_2d=False, dtype=None)
186
+ X, y = self._validate_data(
187
+ X, y, validate_separately=(check_X_params, check_y_params)
188
+ )
189
+ if issparse(X):
190
+ X.sort_indices()
191
+
192
+ if X.indices.dtype != np.intc or X.indptr.dtype != np.intc:
193
+ raise ValueError(
194
+ "No support for np.int64 index based sparse matrices"
195
+ )
196
+
197
+ if self.criterion == "poisson":
198
+ if np.any(y < 0):
199
+ raise ValueError(
200
+ "Some value(s) of y are negative which is"
201
+ " not allowed for Poisson regression."
202
+ )
203
+ if np.sum(y) <= 0:
204
+ raise ValueError(
205
+ "Sum of y is not positive which is "
206
+ "necessary for Poisson regression."
207
+ )
208
+
209
+ # Determine output settings
210
+ n_samples, self.n_features_in_ = X.shape
211
+ is_classification = is_classifier(self)
212
+
213
+ y = np.atleast_1d(y)
214
+ expanded_class_weight = None
215
+
216
+ if y.ndim == 1:
217
+ # reshape is necessary to preserve the data contiguity against vs
218
+ # [:, np.newaxis] that does not.
219
+ y = np.reshape(y, (-1, 1))
220
+
221
+ self.n_outputs_ = y.shape[1]
222
+
223
+ if is_classification:
224
+ check_classification_targets(y)
225
+ y = np.copy(y)
226
+
227
+ self.classes_ = []
228
+ self.n_classes_ = []
229
+
230
+ if self.class_weight is not None:
231
+ y_original = np.copy(y)
232
+
233
+ y_encoded = np.zeros(y.shape, dtype=int)
234
+ for k in range(self.n_outputs_):
235
+ classes_k, y_encoded[:, k] = np.unique(y[:, k], return_inverse=True)
236
+ self.classes_.append(classes_k)
237
+ self.n_classes_.append(classes_k.shape[0])
238
+ y = y_encoded
239
+
240
+ if self.class_weight is not None:
241
+ expanded_class_weight = compute_sample_weight(
242
+ self.class_weight, y_original
243
+ )
244
+
245
+ self.n_classes_ = np.array(self.n_classes_, dtype=np.intp)
246
+
247
+ if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous:
248
+ y = np.ascontiguousarray(y, dtype=DOUBLE)
249
+
250
+ max_depth = np.iinfo(np.int32).max if self.max_depth is None else self.max_depth
251
+
252
+ if isinstance(self.min_samples_leaf, numbers.Integral):
253
+ min_samples_leaf = self.min_samples_leaf
254
+ else: # float
255
+ min_samples_leaf = int(ceil(self.min_samples_leaf * n_samples))
256
+
257
+ if isinstance(self.min_samples_split, numbers.Integral):
258
+ min_samples_split = self.min_samples_split
259
+ else: # float
260
+ min_samples_split = int(ceil(self.min_samples_split * n_samples))
261
+ min_samples_split = max(2, min_samples_split)
262
+
263
+ min_samples_split = max(min_samples_split, 2 * min_samples_leaf)
264
+
265
+ if isinstance(self.max_features, str):
266
+ if self.max_features == "auto":
267
+ if is_classification:
268
+ max_features = max(1, int(np.sqrt(self.n_features_in_)))
269
+ warnings.warn(
270
+ "`max_features='auto'` has been deprecated in 1.1 "
271
+ "and will be removed in 1.3. To keep the past behaviour, "
272
+ "explicitly set `max_features='sqrt'`.",
273
+ FutureWarning,
274
+ )
275
+ else:
276
+ max_features = self.n_features_in_
277
+ warnings.warn(
278
+ "`max_features='auto'` has been deprecated in 1.1 "
279
+ "and will be removed in 1.3. To keep the past behaviour, "
280
+ "explicitly set `max_features=1.0'`.",
281
+ FutureWarning,
282
+ )
283
+ elif self.max_features == "sqrt":
284
+ max_features = max(1, int(np.sqrt(self.n_features_in_)))
285
+ elif self.max_features == "log2":
286
+ max_features = max(1, int(np.log2(self.n_features_in_)))
287
+ elif self.max_features is None:
288
+ max_features = self.n_features_in_
289
+ elif isinstance(self.max_features, numbers.Integral):
290
+ max_features = self.max_features
291
+ else: # float
292
+ if self.max_features > 0.0:
293
+ max_features = max(1, int(self.max_features * self.n_features_in_))
294
+ else:
295
+ max_features = 0
296
+
297
+ self.max_features_ = max_features
298
+
299
+ max_leaf_nodes = -1 if self.max_leaf_nodes is None else self.max_leaf_nodes
300
+
301
+ if len(y) != n_samples:
302
+ raise ValueError(
303
+ "Number of labels=%d does not match number of samples=%d"
304
+ % (len(y), n_samples)
305
+ )
306
+
307
+ if sample_weight is not None:
308
+ sample_weight = _check_sample_weight(sample_weight, X, DOUBLE)
309
+
310
+ if expanded_class_weight is not None:
311
+ if sample_weight is not None:
312
+ sample_weight = sample_weight * expanded_class_weight
313
+ else:
314
+ sample_weight = expanded_class_weight
315
+
316
+ # Set min_weight_leaf from min_weight_fraction_leaf
317
+ if sample_weight is None:
318
+ min_weight_leaf = self.min_weight_fraction_leaf * n_samples
319
+ else:
320
+ min_weight_leaf = self.min_weight_fraction_leaf * np.sum(sample_weight)
321
+
322
+ # Build tree
323
+ criterion = self.criterion
324
+ if not isinstance(criterion, Criterion):
325
+ if is_classification:
326
+ criterion = CRITERIA_CLF[self.criterion](
327
+ self.n_outputs_, self.n_classes_
328
+ )
329
+ else:
330
+ criterion = CRITERIA_REG[self.criterion](self.n_outputs_, n_samples)
331
+ else:
332
+ # Make a deepcopy in case the criterion has mutable attributes that
333
+ # might be shared and modified concurrently during parallel fitting
334
+ criterion = copy.deepcopy(criterion)
335
+
336
+ SPLITTERS = SPARSE_SPLITTERS if issparse(X) else DENSE_SPLITTERS
337
+
338
+ splitter = self.splitter
339
+ if not isinstance(self.splitter, Splitter):
340
+ splitter = SPLITTERS[self.splitter](
341
+ criterion,
342
+ self.max_features_,
343
+ min_samples_leaf,
344
+ min_weight_leaf,
345
+ random_state,
346
+ )
347
+
348
+ if is_classifier(self):
349
+ self.tree_ = Tree(self.n_features_in_, self.n_classes_, self.n_outputs_)
350
+ else:
351
+ self.tree_ = Tree(
352
+ self.n_features_in_,
353
+ # TODO: tree shouldn't need this in this case
354
+ np.array([1] * self.n_outputs_, dtype=np.intp),
355
+ self.n_outputs_,
356
+ )
357
+
358
+ # Use BestFirst if max_leaf_nodes given; use DepthFirst otherwise
359
+ if max_leaf_nodes < 0:
360
+ builder = DepthFirstTreeBuilder(
361
+ splitter,
362
+ min_samples_split,
363
+ min_samples_leaf,
364
+ min_weight_leaf,
365
+ max_depth,
366
+ self.min_impurity_decrease,
367
+ )
368
+ else:
369
+ builder = BestFirstTreeBuilder(
370
+ splitter,
371
+ min_samples_split,
372
+ min_samples_leaf,
373
+ min_weight_leaf,
374
+ max_depth,
375
+ max_leaf_nodes,
376
+ self.min_impurity_decrease,
377
+ )
378
+
379
+ builder.build(self.tree_, X, y, sample_weight)
380
+
381
+ if self.n_outputs_ == 1 and is_classifier(self):
382
+ self.n_classes_ = self.n_classes_[0]
383
+ self.classes_ = self.classes_[0]
384
+
385
+ self._prune_tree()
386
+
387
+ return self
388
+
389
+ def _validate_X_predict(self, X, check_input):
390
+ """Validate the training data on predict (probabilities)."""
391
+ if check_input:
392
+ X = self._validate_data(X, dtype=DTYPE, accept_sparse="csr", reset=False)
393
+ if issparse(X) and (
394
+ X.indices.dtype != np.intc or X.indptr.dtype != np.intc
395
+ ):
396
+ raise ValueError("No support for np.int64 index based sparse matrices")
397
+ else:
398
+ # The number of features is checked regardless of `check_input`
399
+ self._check_n_features(X, reset=False)
400
+ return X
401
+
402
+ def predict(self, X, check_input=True):
403
+ """Predict class or regression value for X.
404
+
405
+ For a classification model, the predicted class for each sample in X is
406
+ returned. For a regression model, the predicted value based on X is
407
+ returned.
408
+
409
+ Parameters
410
+ ----------
411
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
412
+ The input samples. Internally, it will be converted to
413
+ ``dtype=np.float32`` and if a sparse matrix is provided
414
+ to a sparse ``csr_matrix``.
415
+
416
+ check_input : bool, default=True
417
+ Allow to bypass several input checking.
418
+ Don't use this parameter unless you know what you're doing.
419
+
420
+ Returns
421
+ -------
422
+ y : array-like of shape (n_samples,) or (n_samples, n_outputs)
423
+ The predicted classes, or the predict values.
424
+ """
425
+ check_is_fitted(self)
426
+ X = self._validate_X_predict(X, check_input)
427
+ proba = self.tree_.predict(X)
428
+ n_samples = X.shape[0]
429
+
430
+ # Classification
431
+ if is_classifier(self):
432
+ if self.n_outputs_ == 1:
433
+ return self.classes_.take(np.argmax(proba, axis=1), axis=0)
434
+
435
+ else:
436
+ class_type = self.classes_[0].dtype
437
+ predictions = np.zeros((n_samples, self.n_outputs_), dtype=class_type)
438
+ for k in range(self.n_outputs_):
439
+ predictions[:, k] = self.classes_[k].take(
440
+ np.argmax(proba[:, k], axis=1), axis=0
441
+ )
442
+
443
+ return predictions
444
+
445
+ # Regression
446
+ else:
447
+ if self.n_outputs_ == 1:
448
+ return proba[:, 0]
449
+
450
+ else:
451
+ return proba[:, :, 0]
452
+
453
+ def apply(self, X, check_input=True):
454
+ """Return the index of the leaf that each sample is predicted as.
455
+
456
+ .. versionadded:: 0.17
457
+
458
+ Parameters
459
+ ----------
460
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
461
+ The input samples. Internally, it will be converted to
462
+ ``dtype=np.float32`` and if a sparse matrix is provided
463
+ to a sparse ``csr_matrix``.
464
+
465
+ check_input : bool, default=True
466
+ Allow to bypass several input checking.
467
+ Don't use this parameter unless you know what you're doing.
468
+
469
+ Returns
470
+ -------
471
+ X_leaves : array-like of shape (n_samples,)
472
+ For each datapoint x in X, return the index of the leaf x
473
+ ends up in. Leaves are numbered within
474
+ ``[0; self.tree_.node_count)``, possibly with gaps in the
475
+ numbering.
476
+ """
477
+ check_is_fitted(self)
478
+ X = self._validate_X_predict(X, check_input)
479
+ return self.tree_.apply(X)
480
+
481
+ def decision_path(self, X, check_input=True):
482
+ """Return the decision path in the tree.
483
+
484
+ .. versionadded:: 0.18
485
+
486
+ Parameters
487
+ ----------
488
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
489
+ The input samples. Internally, it will be converted to
490
+ ``dtype=np.float32`` and if a sparse matrix is provided
491
+ to a sparse ``csr_matrix``.
492
+
493
+ check_input : bool, default=True
494
+ Allow to bypass several input checking.
495
+ Don't use this parameter unless you know what you're doing.
496
+
497
+ Returns
498
+ -------
499
+ indicator : sparse matrix of shape (n_samples, n_nodes)
500
+ Return a node indicator CSR matrix where non zero elements
501
+ indicates that the samples goes through the nodes.
502
+ """
503
+ X = self._validate_X_predict(X, check_input)
504
+ return self.tree_.decision_path(X)
505
+
506
+ def _prune_tree(self):
507
+ """Prune tree using Minimal Cost-Complexity Pruning."""
508
+ check_is_fitted(self)
509
+
510
+ if self.ccp_alpha == 0.0:
511
+ return
512
+
513
+ # build pruned tree
514
+ if is_classifier(self):
515
+ n_classes = np.atleast_1d(self.n_classes_)
516
+ pruned_tree = Tree(self.n_features_in_, n_classes, self.n_outputs_)
517
+ else:
518
+ pruned_tree = Tree(
519
+ self.n_features_in_,
520
+ # TODO: the tree shouldn't need this param
521
+ np.array([1] * self.n_outputs_, dtype=np.intp),
522
+ self.n_outputs_,
523
+ )
524
+ _build_pruned_tree_ccp(pruned_tree, self.tree_, self.ccp_alpha)
525
+
526
+ self.tree_ = pruned_tree
527
+
528
+ def cost_complexity_pruning_path(self, X, y, sample_weight=None):
529
+ """Compute the pruning path during Minimal Cost-Complexity Pruning.
530
+
531
+ See :ref:`minimal_cost_complexity_pruning` for details on the pruning
532
+ process.
533
+
534
+ Parameters
535
+ ----------
536
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
537
+ The training input samples. Internally, it will be converted to
538
+ ``dtype=np.float32`` and if a sparse matrix is provided
539
+ to a sparse ``csc_matrix``.
540
+
541
+ y : array-like of shape (n_samples,) or (n_samples, n_outputs)
542
+ The target values (class labels) as integers or strings.
543
+
544
+ sample_weight : array-like of shape (n_samples,), default=None
545
+ Sample weights. If None, then samples are equally weighted. Splits
546
+ that would create child nodes with net zero or negative weight are
547
+ ignored while searching for a split in each node. Splits are also
548
+ ignored if they would result in any single class carrying a
549
+ negative weight in either child node.
550
+
551
+ Returns
552
+ -------
553
+ ccp_path : :class:`~sklearn.utils.Bunch`
554
+ Dictionary-like object, with the following attributes.
555
+
556
+ ccp_alphas : ndarray
557
+ Effective alphas of subtree during pruning.
558
+
559
+ impurities : ndarray
560
+ Sum of the impurities of the subtree leaves for the
561
+ corresponding alpha value in ``ccp_alphas``.
562
+ """
563
+ est = clone(self).set_params(ccp_alpha=0.0)
564
+ est.fit(X, y, sample_weight=sample_weight)
565
+ return Bunch(**ccp_pruning_path(est.tree_))
566
+
567
+ @property
568
+ def feature_importances_(self):
569
+ """Return the feature importances.
570
+
571
+ The importance of a feature is computed as the (normalized) total
572
+ reduction of the criterion brought by that feature.
573
+ It is also known as the Gini importance.
574
+
575
+ Warning: impurity-based feature importances can be misleading for
576
+ high cardinality features (many unique values). See
577
+ :func:`sklearn.inspection.permutation_importance` as an alternative.
578
+
579
+ Returns
580
+ -------
581
+ feature_importances_ : ndarray of shape (n_features,)
582
+ Normalized total reduction of criteria by feature
583
+ (Gini importance).
584
+ """
585
+ check_is_fitted(self)
586
+
587
+ return self.tree_.compute_feature_importances()
588
+
589
+
590
+ # =============================================================================
591
+ # Public estimators
592
+ # =============================================================================
593
+
594
+
595
+ class DecisionTreeClassifier(ClassifierMixin, BaseDecisionTree):
596
+ """A decision tree classifier.
597
+
598
+ Read more in the :ref:`User Guide <tree>`.
599
+
600
+ Parameters
601
+ ----------
602
+ criterion : {"gini", "entropy", "log_loss"}, default="gini"
603
+ The function to measure the quality of a split. Supported criteria are
604
+ "gini" for the Gini impurity and "log_loss" and "entropy" both for the
605
+ Shannon information gain, see :ref:`tree_mathematical_formulation`.
606
+
607
+ splitter : {"best", "random"}, default="best"
608
+ The strategy used to choose the split at each node. Supported
609
+ strategies are "best" to choose the best split and "random" to choose
610
+ the best random split.
611
+
612
+ max_depth : int, default=None
613
+ The maximum depth of the tree. If None, then nodes are expanded until
614
+ all leaves are pure or until all leaves contain less than
615
+ min_samples_split samples.
616
+
617
+ min_samples_split : int or float, default=2
618
+ The minimum number of samples required to split an internal node:
619
+
620
+ - If int, then consider `min_samples_split` as the minimum number.
621
+ - If float, then `min_samples_split` is a fraction and
622
+ `ceil(min_samples_split * n_samples)` are the minimum
623
+ number of samples for each split.
624
+
625
+ .. versionchanged:: 0.18
626
+ Added float values for fractions.
627
+
628
+ min_samples_leaf : int or float, default=1
629
+ The minimum number of samples required to be at a leaf node.
630
+ A split point at any depth will only be considered if it leaves at
631
+ least ``min_samples_leaf`` training samples in each of the left and
632
+ right branches. This may have the effect of smoothing the model,
633
+ especially in regression.
634
+
635
+ - If int, then consider `min_samples_leaf` as the minimum number.
636
+ - If float, then `min_samples_leaf` is a fraction and
637
+ `ceil(min_samples_leaf * n_samples)` are the minimum
638
+ number of samples for each node.
639
+
640
+ .. versionchanged:: 0.18
641
+ Added float values for fractions.
642
+
643
+ min_weight_fraction_leaf : float, default=0.0
644
+ The minimum weighted fraction of the sum total of weights (of all
645
+ the input samples) required to be at a leaf node. Samples have
646
+ equal weight when sample_weight is not provided.
647
+
648
+ max_features : int, float or {"auto", "sqrt", "log2"}, default=None
649
+ The number of features to consider when looking for the best split:
650
+
651
+ - If int, then consider `max_features` features at each split.
652
+ - If float, then `max_features` is a fraction and
653
+ `max(1, int(max_features * n_features_in_))` features are considered at
654
+ each split.
655
+ - If "auto", then `max_features=sqrt(n_features)`.
656
+ - If "sqrt", then `max_features=sqrt(n_features)`.
657
+ - If "log2", then `max_features=log2(n_features)`.
658
+ - If None, then `max_features=n_features`.
659
+
660
+ .. deprecated:: 1.1
661
+ The `"auto"` option was deprecated in 1.1 and will be removed
662
+ in 1.3.
663
+
664
+ Note: the search for a split does not stop until at least one
665
+ valid partition of the node samples is found, even if it requires to
666
+ effectively inspect more than ``max_features`` features.
667
+
668
+ random_state : int, RandomState instance or None, default=None
669
+ Controls the randomness of the estimator. The features are always
670
+ randomly permuted at each split, even if ``splitter`` is set to
671
+ ``"best"``. When ``max_features < n_features``, the algorithm will
672
+ select ``max_features`` at random at each split before finding the best
673
+ split among them. But the best found split may vary across different
674
+ runs, even if ``max_features=n_features``. That is the case, if the
675
+ improvement of the criterion is identical for several splits and one
676
+ split has to be selected at random. To obtain a deterministic behaviour
677
+ during fitting, ``random_state`` has to be fixed to an integer.
678
+ See :term:`Glossary <random_state>` for details.
679
+
680
+ max_leaf_nodes : int, default=None
681
+ Grow a tree with ``max_leaf_nodes`` in best-first fashion.
682
+ Best nodes are defined as relative reduction in impurity.
683
+ If None then unlimited number of leaf nodes.
684
+
685
+ min_impurity_decrease : float, default=0.0
686
+ A node will be split if this split induces a decrease of the impurity
687
+ greater than or equal to this value.
688
+
689
+ The weighted impurity decrease equation is the following::
690
+
691
+ N_t / N * (impurity - N_t_R / N_t * right_impurity
692
+ - N_t_L / N_t * left_impurity)
693
+
694
+ where ``N`` is the total number of samples, ``N_t`` is the number of
695
+ samples at the current node, ``N_t_L`` is the number of samples in the
696
+ left child, and ``N_t_R`` is the number of samples in the right child.
697
+
698
+ ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
699
+ if ``sample_weight`` is passed.
700
+
701
+ .. versionadded:: 0.19
702
+
703
+ class_weight : dict, list of dict or "balanced", default=None
704
+ Weights associated with classes in the form ``{class_label: weight}``.
705
+ If None, all classes are supposed to have weight one. For
706
+ multi-output problems, a list of dicts can be provided in the same
707
+ order as the columns of y.
708
+
709
+ Note that for multioutput (including multilabel) weights should be
710
+ defined for each class of every column in its own dict. For example,
711
+ for four-class multilabel classification weights should be
712
+ [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of
713
+ [{1:1}, {2:5}, {3:1}, {4:1}].
714
+
715
+ The "balanced" mode uses the values of y to automatically adjust
716
+ weights inversely proportional to class frequencies in the input data
717
+ as ``n_samples / (n_classes * np.bincount(y))``
718
+
719
+ For multi-output, the weights of each column of y will be multiplied.
720
+
721
+ Note that these weights will be multiplied with sample_weight (passed
722
+ through the fit method) if sample_weight is specified.
723
+
724
+ ccp_alpha : non-negative float, default=0.0
725
+ Complexity parameter used for Minimal Cost-Complexity Pruning. The
726
+ subtree with the largest cost complexity that is smaller than
727
+ ``ccp_alpha`` will be chosen. By default, no pruning is performed. See
728
+ :ref:`minimal_cost_complexity_pruning` for details.
729
+
730
+ .. versionadded:: 0.22
731
+
732
+ Attributes
733
+ ----------
734
+ classes_ : ndarray of shape (n_classes,) or list of ndarray
735
+ The classes labels (single output problem),
736
+ or a list of arrays of class labels (multi-output problem).
737
+
738
+ feature_importances_ : ndarray of shape (n_features,)
739
+ The impurity-based feature importances.
740
+ The higher, the more important the feature.
741
+ The importance of a feature is computed as the (normalized)
742
+ total reduction of the criterion brought by that feature. It is also
743
+ known as the Gini importance [4]_.
744
+
745
+ Warning: impurity-based feature importances can be misleading for
746
+ high cardinality features (many unique values). See
747
+ :func:`sklearn.inspection.permutation_importance` as an alternative.
748
+
749
+ max_features_ : int
750
+ The inferred value of max_features.
751
+
752
+ n_classes_ : int or list of int
753
+ The number of classes (for single output problems),
754
+ or a list containing the number of classes for each
755
+ output (for multi-output problems).
756
+
757
+ n_features_in_ : int
758
+ Number of features seen during :term:`fit`.
759
+
760
+ .. versionadded:: 0.24
761
+
762
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
763
+ Names of features seen during :term:`fit`. Defined only when `X`
764
+ has feature names that are all strings.
765
+
766
+ .. versionadded:: 1.0
767
+
768
+ n_outputs_ : int
769
+ The number of outputs when ``fit`` is performed.
770
+
771
+ tree_ : Tree instance
772
+ The underlying Tree object. Please refer to
773
+ ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and
774
+ :ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py`
775
+ for basic usage of these attributes.
776
+
777
+ See Also
778
+ --------
779
+ DecisionTreeRegressor : A decision tree regressor.
780
+
781
+ Notes
782
+ -----
783
+ The default values for the parameters controlling the size of the trees
784
+ (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
785
+ unpruned trees which can potentially be very large on some data sets. To
786
+ reduce memory consumption, the complexity and size of the trees should be
787
+ controlled by setting those parameter values.
788
+
789
+ The :meth:`predict` method operates using the :func:`numpy.argmax`
790
+ function on the outputs of :meth:`predict_proba`. This means that in
791
+ case the highest predicted probabilities are tied, the classifier will
792
+ predict the tied class with the lowest index in :term:`classes_`.
793
+
794
+ References
795
+ ----------
796
+
797
+ .. [1] https://en.wikipedia.org/wiki/Decision_tree_learning
798
+
799
+ .. [2] L. Breiman, J. Friedman, R. Olshen, and C. Stone, "Classification
800
+ and Regression Trees", Wadsworth, Belmont, CA, 1984.
801
+
802
+ .. [3] T. Hastie, R. Tibshirani and J. Friedman. "Elements of Statistical
803
+ Learning", Springer, 2009.
804
+
805
+ .. [4] L. Breiman, and A. Cutler, "Random Forests",
806
+ https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm
807
+
808
+ Examples
809
+ --------
810
+ >>> from sklearn.datasets import load_iris
811
+ >>> from sklearn.model_selection import cross_val_score
812
+ >>> from sklearn.tree import DecisionTreeClassifier
813
+ >>> clf = DecisionTreeClassifier(random_state=0)
814
+ >>> iris = load_iris()
815
+ >>> cross_val_score(clf, iris.data, iris.target, cv=10)
816
+ ... # doctest: +SKIP
817
+ ...
818
+ array([ 1. , 0.93..., 0.86..., 0.93..., 0.93...,
819
+ 0.93..., 0.93..., 1. , 0.93..., 1. ])
820
+ """
821
+
822
+ _parameter_constraints: dict = {
823
+ **BaseDecisionTree._parameter_constraints,
824
+ "criterion": [StrOptions({"gini", "entropy", "log_loss"}), Hidden(Criterion)],
825
+ "class_weight": [dict, list, StrOptions({"balanced"}), None],
826
+ }
827
+
828
+ def __init__(
829
+ self,
830
+ *,
831
+ criterion="gini",
832
+ splitter="best",
833
+ max_depth=None,
834
+ min_samples_split=2,
835
+ min_samples_leaf=1,
836
+ min_weight_fraction_leaf=0.0,
837
+ max_features=None,
838
+ random_state=None,
839
+ max_leaf_nodes=None,
840
+ min_impurity_decrease=0.0,
841
+ class_weight=None,
842
+ ccp_alpha=0.0,
843
+ ):
844
+ super().__init__(
845
+ criterion=criterion,
846
+ splitter=splitter,
847
+ max_depth=max_depth,
848
+ min_samples_split=min_samples_split,
849
+ min_samples_leaf=min_samples_leaf,
850
+ min_weight_fraction_leaf=min_weight_fraction_leaf,
851
+ max_features=max_features,
852
+ max_leaf_nodes=max_leaf_nodes,
853
+ class_weight=class_weight,
854
+ random_state=random_state,
855
+ min_impurity_decrease=min_impurity_decrease,
856
+ ccp_alpha=ccp_alpha,
857
+ )
858
+
859
+ def fit(self, X, y, sample_weight=None, check_input=True):
860
+ """Build a decision tree classifier from the training set (X, y).
861
+
862
+ Parameters
863
+ ----------
864
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
865
+ The training input samples. Internally, it will be converted to
866
+ ``dtype=np.float32`` and if a sparse matrix is provided
867
+ to a sparse ``csc_matrix``.
868
+
869
+ y : array-like of shape (n_samples,) or (n_samples, n_outputs)
870
+ The target values (class labels) as integers or strings.
871
+
872
+ sample_weight : array-like of shape (n_samples,), default=None
873
+ Sample weights. If None, then samples are equally weighted. Splits
874
+ that would create child nodes with net zero or negative weight are
875
+ ignored while searching for a split in each node. Splits are also
876
+ ignored if they would result in any single class carrying a
877
+ negative weight in either child node.
878
+
879
+ check_input : bool, default=True
880
+ Allow to bypass several input checking.
881
+ Don't use this parameter unless you know what you're doing.
882
+
883
+ Returns
884
+ -------
885
+ self : DecisionTreeClassifier
886
+ Fitted estimator.
887
+ """
888
+
889
+ super().fit(
890
+ X,
891
+ y,
892
+ sample_weight=sample_weight,
893
+ check_input=check_input,
894
+ )
895
+ return self
896
+
897
+ def predict_proba(self, X, check_input=True):
898
+ """Predict class probabilities of the input samples X.
899
+
900
+ The predicted class probability is the fraction of samples of the same
901
+ class in a leaf.
902
+
903
+ Parameters
904
+ ----------
905
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
906
+ The input samples. Internally, it will be converted to
907
+ ``dtype=np.float32`` and if a sparse matrix is provided
908
+ to a sparse ``csr_matrix``.
909
+
910
+ check_input : bool, default=True
911
+ Allow to bypass several input checking.
912
+ Don't use this parameter unless you know what you're doing.
913
+
914
+ Returns
915
+ -------
916
+ proba : ndarray of shape (n_samples, n_classes) or list of n_outputs \
917
+ such arrays if n_outputs > 1
918
+ The class probabilities of the input samples. The order of the
919
+ classes corresponds to that in the attribute :term:`classes_`.
920
+ """
921
+ check_is_fitted(self)
922
+ X = self._validate_X_predict(X, check_input)
923
+ proba = self.tree_.predict(X)
924
+
925
+ if self.n_outputs_ == 1:
926
+ proba = proba[:, : self.n_classes_]
927
+ normalizer = proba.sum(axis=1)[:, np.newaxis]
928
+ normalizer[normalizer == 0.0] = 1.0
929
+ proba /= normalizer
930
+
931
+ return proba
932
+
933
+ else:
934
+ all_proba = []
935
+
936
+ for k in range(self.n_outputs_):
937
+ proba_k = proba[:, k, : self.n_classes_[k]]
938
+ normalizer = proba_k.sum(axis=1)[:, np.newaxis]
939
+ normalizer[normalizer == 0.0] = 1.0
940
+ proba_k /= normalizer
941
+ all_proba.append(proba_k)
942
+
943
+ return all_proba
944
+
945
+ def predict_log_proba(self, X):
946
+ """Predict class log-probabilities of the input samples X.
947
+
948
+ Parameters
949
+ ----------
950
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
951
+ The input samples. Internally, it will be converted to
952
+ ``dtype=np.float32`` and if a sparse matrix is provided
953
+ to a sparse ``csr_matrix``.
954
+
955
+ Returns
956
+ -------
957
+ proba : ndarray of shape (n_samples, n_classes) or list of n_outputs \
958
+ such arrays if n_outputs > 1
959
+ The class log-probabilities of the input samples. The order of the
960
+ classes corresponds to that in the attribute :term:`classes_`.
961
+ """
962
+ proba = self.predict_proba(X)
963
+
964
+ if self.n_outputs_ == 1:
965
+ return np.log(proba)
966
+
967
+ else:
968
+ for k in range(self.n_outputs_):
969
+ proba[k] = np.log(proba[k])
970
+
971
+ return proba
972
+
973
+ def _more_tags(self):
974
+ return {"multilabel": True}
975
+
976
+
977
+ class DecisionTreeRegressor(RegressorMixin, BaseDecisionTree):
978
+ """A decision tree regressor.
979
+
980
+ Read more in the :ref:`User Guide <tree>`.
981
+
982
+ Parameters
983
+ ----------
984
+ criterion : {"squared_error", "friedman_mse", "absolute_error", \
985
+ "poisson"}, default="squared_error"
986
+ The function to measure the quality of a split. Supported criteria
987
+ are "squared_error" for the mean squared error, which is equal to
988
+ variance reduction as feature selection criterion and minimizes the L2
989
+ loss using the mean of each terminal node, "friedman_mse", which uses
990
+ mean squared error with Friedman's improvement score for potential
991
+ splits, "absolute_error" for the mean absolute error, which minimizes
992
+ the L1 loss using the median of each terminal node, and "poisson" which
993
+ uses reduction in Poisson deviance to find splits.
994
+
995
+ .. versionadded:: 0.18
996
+ Mean Absolute Error (MAE) criterion.
997
+
998
+ .. versionadded:: 0.24
999
+ Poisson deviance criterion.
1000
+
1001
+ splitter : {"best", "random"}, default="best"
1002
+ The strategy used to choose the split at each node. Supported
1003
+ strategies are "best" to choose the best split and "random" to choose
1004
+ the best random split.
1005
+
1006
+ max_depth : int, default=None
1007
+ The maximum depth of the tree. If None, then nodes are expanded until
1008
+ all leaves are pure or until all leaves contain less than
1009
+ min_samples_split samples.
1010
+
1011
+ min_samples_split : int or float, default=2
1012
+ The minimum number of samples required to split an internal node:
1013
+
1014
+ - If int, then consider `min_samples_split` as the minimum number.
1015
+ - If float, then `min_samples_split` is a fraction and
1016
+ `ceil(min_samples_split * n_samples)` are the minimum
1017
+ number of samples for each split.
1018
+
1019
+ .. versionchanged:: 0.18
1020
+ Added float values for fractions.
1021
+
1022
+ min_samples_leaf : int or float, default=1
1023
+ The minimum number of samples required to be at a leaf node.
1024
+ A split point at any depth will only be considered if it leaves at
1025
+ least ``min_samples_leaf`` training samples in each of the left and
1026
+ right branches. This may have the effect of smoothing the model,
1027
+ especially in regression.
1028
+
1029
+ - If int, then consider `min_samples_leaf` as the minimum number.
1030
+ - If float, then `min_samples_leaf` is a fraction and
1031
+ `ceil(min_samples_leaf * n_samples)` are the minimum
1032
+ number of samples for each node.
1033
+
1034
+ .. versionchanged:: 0.18
1035
+ Added float values for fractions.
1036
+
1037
+ min_weight_fraction_leaf : float, default=0.0
1038
+ The minimum weighted fraction of the sum total of weights (of all
1039
+ the input samples) required to be at a leaf node. Samples have
1040
+ equal weight when sample_weight is not provided.
1041
+
1042
+ max_features : int, float or {"auto", "sqrt", "log2"}, default=None
1043
+ The number of features to consider when looking for the best split:
1044
+
1045
+ - If int, then consider `max_features` features at each split.
1046
+ - If float, then `max_features` is a fraction and
1047
+ `max(1, int(max_features * n_features_in_))` features are considered at each
1048
+ split.
1049
+ - If "auto", then `max_features=n_features`.
1050
+ - If "sqrt", then `max_features=sqrt(n_features)`.
1051
+ - If "log2", then `max_features=log2(n_features)`.
1052
+ - If None, then `max_features=n_features`.
1053
+
1054
+ .. deprecated:: 1.1
1055
+ The `"auto"` option was deprecated in 1.1 and will be removed
1056
+ in 1.3.
1057
+
1058
+ Note: the search for a split does not stop until at least one
1059
+ valid partition of the node samples is found, even if it requires to
1060
+ effectively inspect more than ``max_features`` features.
1061
+
1062
+ random_state : int, RandomState instance or None, default=None
1063
+ Controls the randomness of the estimator. The features are always
1064
+ randomly permuted at each split, even if ``splitter`` is set to
1065
+ ``"best"``. When ``max_features < n_features``, the algorithm will
1066
+ select ``max_features`` at random at each split before finding the best
1067
+ split among them. But the best found split may vary across different
1068
+ runs, even if ``max_features=n_features``. That is the case, if the
1069
+ improvement of the criterion is identical for several splits and one
1070
+ split has to be selected at random. To obtain a deterministic behaviour
1071
+ during fitting, ``random_state`` has to be fixed to an integer.
1072
+ See :term:`Glossary <random_state>` for details.
1073
+
1074
+ max_leaf_nodes : int, default=None
1075
+ Grow a tree with ``max_leaf_nodes`` in best-first fashion.
1076
+ Best nodes are defined as relative reduction in impurity.
1077
+ If None then unlimited number of leaf nodes.
1078
+
1079
+ min_impurity_decrease : float, default=0.0
1080
+ A node will be split if this split induces a decrease of the impurity
1081
+ greater than or equal to this value.
1082
+
1083
+ The weighted impurity decrease equation is the following::
1084
+
1085
+ N_t / N * (impurity - N_t_R / N_t * right_impurity
1086
+ - N_t_L / N_t * left_impurity)
1087
+
1088
+ where ``N`` is the total number of samples, ``N_t`` is the number of
1089
+ samples at the current node, ``N_t_L`` is the number of samples in the
1090
+ left child, and ``N_t_R`` is the number of samples in the right child.
1091
+
1092
+ ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
1093
+ if ``sample_weight`` is passed.
1094
+
1095
+ .. versionadded:: 0.19
1096
+
1097
+ ccp_alpha : non-negative float, default=0.0
1098
+ Complexity parameter used for Minimal Cost-Complexity Pruning. The
1099
+ subtree with the largest cost complexity that is smaller than
1100
+ ``ccp_alpha`` will be chosen. By default, no pruning is performed. See
1101
+ :ref:`minimal_cost_complexity_pruning` for details.
1102
+
1103
+ .. versionadded:: 0.22
1104
+
1105
+ Attributes
1106
+ ----------
1107
+ feature_importances_ : ndarray of shape (n_features,)
1108
+ The feature importances.
1109
+ The higher, the more important the feature.
1110
+ The importance of a feature is computed as the
1111
+ (normalized) total reduction of the criterion brought
1112
+ by that feature. It is also known as the Gini importance [4]_.
1113
+
1114
+ Warning: impurity-based feature importances can be misleading for
1115
+ high cardinality features (many unique values). See
1116
+ :func:`sklearn.inspection.permutation_importance` as an alternative.
1117
+
1118
+ max_features_ : int
1119
+ The inferred value of max_features.
1120
+
1121
+ n_features_in_ : int
1122
+ Number of features seen during :term:`fit`.
1123
+
1124
+ .. versionadded:: 0.24
1125
+
1126
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
1127
+ Names of features seen during :term:`fit`. Defined only when `X`
1128
+ has feature names that are all strings.
1129
+
1130
+ .. versionadded:: 1.0
1131
+
1132
+ n_outputs_ : int
1133
+ The number of outputs when ``fit`` is performed.
1134
+
1135
+ tree_ : Tree instance
1136
+ The underlying Tree object. Please refer to
1137
+ ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and
1138
+ :ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py`
1139
+ for basic usage of these attributes.
1140
+
1141
+ See Also
1142
+ --------
1143
+ DecisionTreeClassifier : A decision tree classifier.
1144
+
1145
+ Notes
1146
+ -----
1147
+ The default values for the parameters controlling the size of the trees
1148
+ (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
1149
+ unpruned trees which can potentially be very large on some data sets. To
1150
+ reduce memory consumption, the complexity and size of the trees should be
1151
+ controlled by setting those parameter values.
1152
+
1153
+ References
1154
+ ----------
1155
+
1156
+ .. [1] https://en.wikipedia.org/wiki/Decision_tree_learning
1157
+
1158
+ .. [2] L. Breiman, J. Friedman, R. Olshen, and C. Stone, "Classification
1159
+ and Regression Trees", Wadsworth, Belmont, CA, 1984.
1160
+
1161
+ .. [3] T. Hastie, R. Tibshirani and J. Friedman. "Elements of Statistical
1162
+ Learning", Springer, 2009.
1163
+
1164
+ .. [4] L. Breiman, and A. Cutler, "Random Forests",
1165
+ https://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm
1166
+
1167
+ Examples
1168
+ --------
1169
+ >>> from sklearn.datasets import load_diabetes
1170
+ >>> from sklearn.model_selection import cross_val_score
1171
+ >>> from sklearn.tree import DecisionTreeRegressor
1172
+ >>> X, y = load_diabetes(return_X_y=True)
1173
+ >>> regressor = DecisionTreeRegressor(random_state=0)
1174
+ >>> cross_val_score(regressor, X, y, cv=10)
1175
+ ... # doctest: +SKIP
1176
+ ...
1177
+ array([-0.39..., -0.46..., 0.02..., 0.06..., -0.50...,
1178
+ 0.16..., 0.11..., -0.73..., -0.30..., -0.00...])
1179
+ """
1180
+
1181
+ _parameter_constraints: dict = {
1182
+ **BaseDecisionTree._parameter_constraints,
1183
+ "criterion": [
1184
+ StrOptions({"squared_error", "friedman_mse", "absolute_error", "poisson"}),
1185
+ Hidden(Criterion),
1186
+ ],
1187
+ }
1188
+
1189
+ def __init__(
1190
+ self,
1191
+ *,
1192
+ criterion="squared_error",
1193
+ splitter="best",
1194
+ max_depth=None,
1195
+ min_samples_split=2,
1196
+ min_samples_leaf=1,
1197
+ min_weight_fraction_leaf=0.0,
1198
+ max_features=None,
1199
+ random_state=None,
1200
+ max_leaf_nodes=None,
1201
+ min_impurity_decrease=0.0,
1202
+ ccp_alpha=0.0,
1203
+ ):
1204
+ super().__init__(
1205
+ criterion=criterion,
1206
+ splitter=splitter,
1207
+ max_depth=max_depth,
1208
+ min_samples_split=min_samples_split,
1209
+ min_samples_leaf=min_samples_leaf,
1210
+ min_weight_fraction_leaf=min_weight_fraction_leaf,
1211
+ max_features=max_features,
1212
+ max_leaf_nodes=max_leaf_nodes,
1213
+ random_state=random_state,
1214
+ min_impurity_decrease=min_impurity_decrease,
1215
+ ccp_alpha=ccp_alpha,
1216
+ )
1217
+
1218
+ def fit(self, X, y, sample_weight=None, check_input=True):
1219
+ """Build a decision tree regressor from the training set (X, y).
1220
+
1221
+ Parameters
1222
+ ----------
1223
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
1224
+ The training input samples. Internally, it will be converted to
1225
+ ``dtype=np.float32`` and if a sparse matrix is provided
1226
+ to a sparse ``csc_matrix``.
1227
+
1228
+ y : array-like of shape (n_samples,) or (n_samples, n_outputs)
1229
+ The target values (real numbers). Use ``dtype=np.float64`` and
1230
+ ``order='C'`` for maximum efficiency.
1231
+
1232
+ sample_weight : array-like of shape (n_samples,), default=None
1233
+ Sample weights. If None, then samples are equally weighted. Splits
1234
+ that would create child nodes with net zero or negative weight are
1235
+ ignored while searching for a split in each node.
1236
+
1237
+ check_input : bool, default=True
1238
+ Allow to bypass several input checking.
1239
+ Don't use this parameter unless you know what you're doing.
1240
+
1241
+ Returns
1242
+ -------
1243
+ self : DecisionTreeRegressor
1244
+ Fitted estimator.
1245
+ """
1246
+
1247
+ super().fit(
1248
+ X,
1249
+ y,
1250
+ sample_weight=sample_weight,
1251
+ check_input=check_input,
1252
+ )
1253
+ return self
1254
+
1255
+ def _compute_partial_dependence_recursion(self, grid, target_features):
1256
+ """Fast partial dependence computation.
1257
+
1258
+ Parameters
1259
+ ----------
1260
+ grid : ndarray of shape (n_samples, n_target_features)
1261
+ The grid points on which the partial dependence should be
1262
+ evaluated.
1263
+ target_features : ndarray of shape (n_target_features)
1264
+ The set of target features for which the partial dependence
1265
+ should be evaluated.
1266
+
1267
+ Returns
1268
+ -------
1269
+ averaged_predictions : ndarray of shape (n_samples,)
1270
+ The value of the partial dependence function on each grid point.
1271
+ """
1272
+ grid = np.asarray(grid, dtype=DTYPE, order="C")
1273
+ averaged_predictions = np.zeros(
1274
+ shape=grid.shape[0], dtype=np.float64, order="C"
1275
+ )
1276
+
1277
+ self.tree_.compute_partial_dependence(
1278
+ grid, target_features, averaged_predictions
1279
+ )
1280
+ return averaged_predictions
1281
+
1282
+
1283
+ class ExtraTreeClassifier(DecisionTreeClassifier):
1284
+ """An extremely randomized tree classifier.
1285
+
1286
+ Extra-trees differ from classic decision trees in the way they are built.
1287
+ When looking for the best split to separate the samples of a node into two
1288
+ groups, random splits are drawn for each of the `max_features` randomly
1289
+ selected features and the best split among those is chosen. When
1290
+ `max_features` is set 1, this amounts to building a totally random
1291
+ decision tree.
1292
+
1293
+ Warning: Extra-trees should only be used within ensemble methods.
1294
+
1295
+ Read more in the :ref:`User Guide <tree>`.
1296
+
1297
+ Parameters
1298
+ ----------
1299
+ criterion : {"gini", "entropy", "log_loss"}, default="gini"
1300
+ The function to measure the quality of a split. Supported criteria are
1301
+ "gini" for the Gini impurity and "log_loss" and "entropy" both for the
1302
+ Shannon information gain, see :ref:`tree_mathematical_formulation`.
1303
+
1304
+ splitter : {"random", "best"}, default="random"
1305
+ The strategy used to choose the split at each node. Supported
1306
+ strategies are "best" to choose the best split and "random" to choose
1307
+ the best random split.
1308
+
1309
+ max_depth : int, default=None
1310
+ The maximum depth of the tree. If None, then nodes are expanded until
1311
+ all leaves are pure or until all leaves contain less than
1312
+ min_samples_split samples.
1313
+
1314
+ min_samples_split : int or float, default=2
1315
+ The minimum number of samples required to split an internal node:
1316
+
1317
+ - If int, then consider `min_samples_split` as the minimum number.
1318
+ - If float, then `min_samples_split` is a fraction and
1319
+ `ceil(min_samples_split * n_samples)` are the minimum
1320
+ number of samples for each split.
1321
+
1322
+ .. versionchanged:: 0.18
1323
+ Added float values for fractions.
1324
+
1325
+ min_samples_leaf : int or float, default=1
1326
+ The minimum number of samples required to be at a leaf node.
1327
+ A split point at any depth will only be considered if it leaves at
1328
+ least ``min_samples_leaf`` training samples in each of the left and
1329
+ right branches. This may have the effect of smoothing the model,
1330
+ especially in regression.
1331
+
1332
+ - If int, then consider `min_samples_leaf` as the minimum number.
1333
+ - If float, then `min_samples_leaf` is a fraction and
1334
+ `ceil(min_samples_leaf * n_samples)` are the minimum
1335
+ number of samples for each node.
1336
+
1337
+ .. versionchanged:: 0.18
1338
+ Added float values for fractions.
1339
+
1340
+ min_weight_fraction_leaf : float, default=0.0
1341
+ The minimum weighted fraction of the sum total of weights (of all
1342
+ the input samples) required to be at a leaf node. Samples have
1343
+ equal weight when sample_weight is not provided.
1344
+
1345
+ max_features : int, float, {"auto", "sqrt", "log2"} or None, default="sqrt"
1346
+ The number of features to consider when looking for the best split:
1347
+
1348
+ - If int, then consider `max_features` features at each split.
1349
+ - If float, then `max_features` is a fraction and
1350
+ `max(1, int(max_features * n_features_in_))` features are considered at
1351
+ each split.
1352
+ - If "auto", then `max_features=sqrt(n_features)`.
1353
+ - If "sqrt", then `max_features=sqrt(n_features)`.
1354
+ - If "log2", then `max_features=log2(n_features)`.
1355
+ - If None, then `max_features=n_features`.
1356
+
1357
+ .. versionchanged:: 1.1
1358
+ The default of `max_features` changed from `"auto"` to `"sqrt"`.
1359
+
1360
+ .. deprecated:: 1.1
1361
+ The `"auto"` option was deprecated in 1.1 and will be removed
1362
+ in 1.3.
1363
+
1364
+ Note: the search for a split does not stop until at least one
1365
+ valid partition of the node samples is found, even if it requires to
1366
+ effectively inspect more than ``max_features`` features.
1367
+
1368
+ random_state : int, RandomState instance or None, default=None
1369
+ Used to pick randomly the `max_features` used at each split.
1370
+ See :term:`Glossary <random_state>` for details.
1371
+
1372
+ max_leaf_nodes : int, default=None
1373
+ Grow a tree with ``max_leaf_nodes`` in best-first fashion.
1374
+ Best nodes are defined as relative reduction in impurity.
1375
+ If None then unlimited number of leaf nodes.
1376
+
1377
+ min_impurity_decrease : float, default=0.0
1378
+ A node will be split if this split induces a decrease of the impurity
1379
+ greater than or equal to this value.
1380
+
1381
+ The weighted impurity decrease equation is the following::
1382
+
1383
+ N_t / N * (impurity - N_t_R / N_t * right_impurity
1384
+ - N_t_L / N_t * left_impurity)
1385
+
1386
+ where ``N`` is the total number of samples, ``N_t`` is the number of
1387
+ samples at the current node, ``N_t_L`` is the number of samples in the
1388
+ left child, and ``N_t_R`` is the number of samples in the right child.
1389
+
1390
+ ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
1391
+ if ``sample_weight`` is passed.
1392
+
1393
+ .. versionadded:: 0.19
1394
+
1395
+ class_weight : dict, list of dict or "balanced", default=None
1396
+ Weights associated with classes in the form ``{class_label: weight}``.
1397
+ If None, all classes are supposed to have weight one. For
1398
+ multi-output problems, a list of dicts can be provided in the same
1399
+ order as the columns of y.
1400
+
1401
+ Note that for multioutput (including multilabel) weights should be
1402
+ defined for each class of every column in its own dict. For example,
1403
+ for four-class multilabel classification weights should be
1404
+ [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of
1405
+ [{1:1}, {2:5}, {3:1}, {4:1}].
1406
+
1407
+ The "balanced" mode uses the values of y to automatically adjust
1408
+ weights inversely proportional to class frequencies in the input data
1409
+ as ``n_samples / (n_classes * np.bincount(y))``
1410
+
1411
+ For multi-output, the weights of each column of y will be multiplied.
1412
+
1413
+ Note that these weights will be multiplied with sample_weight (passed
1414
+ through the fit method) if sample_weight is specified.
1415
+
1416
+ ccp_alpha : non-negative float, default=0.0
1417
+ Complexity parameter used for Minimal Cost-Complexity Pruning. The
1418
+ subtree with the largest cost complexity that is smaller than
1419
+ ``ccp_alpha`` will be chosen. By default, no pruning is performed. See
1420
+ :ref:`minimal_cost_complexity_pruning` for details.
1421
+
1422
+ .. versionadded:: 0.22
1423
+
1424
+ Attributes
1425
+ ----------
1426
+ classes_ : ndarray of shape (n_classes,) or list of ndarray
1427
+ The classes labels (single output problem),
1428
+ or a list of arrays of class labels (multi-output problem).
1429
+
1430
+ max_features_ : int
1431
+ The inferred value of max_features.
1432
+
1433
+ n_classes_ : int or list of int
1434
+ The number of classes (for single output problems),
1435
+ or a list containing the number of classes for each
1436
+ output (for multi-output problems).
1437
+
1438
+ feature_importances_ : ndarray of shape (n_features,)
1439
+ The impurity-based feature importances.
1440
+ The higher, the more important the feature.
1441
+ The importance of a feature is computed as the (normalized)
1442
+ total reduction of the criterion brought by that feature. It is also
1443
+ known as the Gini importance.
1444
+
1445
+ Warning: impurity-based feature importances can be misleading for
1446
+ high cardinality features (many unique values). See
1447
+ :func:`sklearn.inspection.permutation_importance` as an alternative.
1448
+
1449
+ n_features_in_ : int
1450
+ Number of features seen during :term:`fit`.
1451
+
1452
+ .. versionadded:: 0.24
1453
+
1454
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
1455
+ Names of features seen during :term:`fit`. Defined only when `X`
1456
+ has feature names that are all strings.
1457
+
1458
+ .. versionadded:: 1.0
1459
+
1460
+ n_outputs_ : int
1461
+ The number of outputs when ``fit`` is performed.
1462
+
1463
+ tree_ : Tree instance
1464
+ The underlying Tree object. Please refer to
1465
+ ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and
1466
+ :ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py`
1467
+ for basic usage of these attributes.
1468
+
1469
+ See Also
1470
+ --------
1471
+ ExtraTreeRegressor : An extremely randomized tree regressor.
1472
+ sklearn.ensemble.ExtraTreesClassifier : An extra-trees classifier.
1473
+ sklearn.ensemble.ExtraTreesRegressor : An extra-trees regressor.
1474
+ sklearn.ensemble.RandomForestClassifier : A random forest classifier.
1475
+ sklearn.ensemble.RandomForestRegressor : A random forest regressor.
1476
+ sklearn.ensemble.RandomTreesEmbedding : An ensemble of
1477
+ totally random trees.
1478
+
1479
+ Notes
1480
+ -----
1481
+ The default values for the parameters controlling the size of the trees
1482
+ (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
1483
+ unpruned trees which can potentially be very large on some data sets. To
1484
+ reduce memory consumption, the complexity and size of the trees should be
1485
+ controlled by setting those parameter values.
1486
+
1487
+ References
1488
+ ----------
1489
+
1490
+ .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees",
1491
+ Machine Learning, 63(1), 3-42, 2006.
1492
+
1493
+ Examples
1494
+ --------
1495
+ >>> from sklearn.datasets import load_iris
1496
+ >>> from sklearn.model_selection import train_test_split
1497
+ >>> from sklearn.ensemble import BaggingClassifier
1498
+ >>> from sklearn.tree import ExtraTreeClassifier
1499
+ >>> X, y = load_iris(return_X_y=True)
1500
+ >>> X_train, X_test, y_train, y_test = train_test_split(
1501
+ ... X, y, random_state=0)
1502
+ >>> extra_tree = ExtraTreeClassifier(random_state=0)
1503
+ >>> cls = BaggingClassifier(extra_tree, random_state=0).fit(
1504
+ ... X_train, y_train)
1505
+ >>> cls.score(X_test, y_test)
1506
+ 0.8947...
1507
+ """
1508
+
1509
+ def __init__(
1510
+ self,
1511
+ *,
1512
+ criterion="gini",
1513
+ splitter="random",
1514
+ max_depth=None,
1515
+ min_samples_split=2,
1516
+ min_samples_leaf=1,
1517
+ min_weight_fraction_leaf=0.0,
1518
+ max_features="sqrt",
1519
+ random_state=None,
1520
+ max_leaf_nodes=None,
1521
+ min_impurity_decrease=0.0,
1522
+ class_weight=None,
1523
+ ccp_alpha=0.0,
1524
+ ):
1525
+ super().__init__(
1526
+ criterion=criterion,
1527
+ splitter=splitter,
1528
+ max_depth=max_depth,
1529
+ min_samples_split=min_samples_split,
1530
+ min_samples_leaf=min_samples_leaf,
1531
+ min_weight_fraction_leaf=min_weight_fraction_leaf,
1532
+ max_features=max_features,
1533
+ max_leaf_nodes=max_leaf_nodes,
1534
+ class_weight=class_weight,
1535
+ min_impurity_decrease=min_impurity_decrease,
1536
+ random_state=random_state,
1537
+ ccp_alpha=ccp_alpha,
1538
+ )
1539
+
1540
+
1541
+ class ExtraTreeRegressor(DecisionTreeRegressor):
1542
+ """An extremely randomized tree regressor.
1543
+
1544
+ Extra-trees differ from classic decision trees in the way they are built.
1545
+ When looking for the best split to separate the samples of a node into two
1546
+ groups, random splits are drawn for each of the `max_features` randomly
1547
+ selected features and the best split among those is chosen. When
1548
+ `max_features` is set 1, this amounts to building a totally random
1549
+ decision tree.
1550
+
1551
+ Warning: Extra-trees should only be used within ensemble methods.
1552
+
1553
+ Read more in the :ref:`User Guide <tree>`.
1554
+
1555
+ Parameters
1556
+ ----------
1557
+ criterion : {"squared_error", "friedman_mse", "absolute_error", "poisson"}, \
1558
+ default="squared_error"
1559
+ The function to measure the quality of a split. Supported criteria
1560
+ are "squared_error" for the mean squared error, which is equal to
1561
+ variance reduction as feature selection criterion and minimizes the L2
1562
+ loss using the mean of each terminal node, "friedman_mse", which uses
1563
+ mean squared error with Friedman's improvement score for potential
1564
+ splits, "absolute_error" for the mean absolute error, which minimizes
1565
+ the L1 loss using the median of each terminal node, and "poisson" which
1566
+ uses reduction in Poisson deviance to find splits.
1567
+
1568
+ .. versionadded:: 0.18
1569
+ Mean Absolute Error (MAE) criterion.
1570
+
1571
+ .. versionadded:: 0.24
1572
+ Poisson deviance criterion.
1573
+
1574
+ splitter : {"random", "best"}, default="random"
1575
+ The strategy used to choose the split at each node. Supported
1576
+ strategies are "best" to choose the best split and "random" to choose
1577
+ the best random split.
1578
+
1579
+ max_depth : int, default=None
1580
+ The maximum depth of the tree. If None, then nodes are expanded until
1581
+ all leaves are pure or until all leaves contain less than
1582
+ min_samples_split samples.
1583
+
1584
+ min_samples_split : int or float, default=2
1585
+ The minimum number of samples required to split an internal node:
1586
+
1587
+ - If int, then consider `min_samples_split` as the minimum number.
1588
+ - If float, then `min_samples_split` is a fraction and
1589
+ `ceil(min_samples_split * n_samples)` are the minimum
1590
+ number of samples for each split.
1591
+
1592
+ .. versionchanged:: 0.18
1593
+ Added float values for fractions.
1594
+
1595
+ min_samples_leaf : int or float, default=1
1596
+ The minimum number of samples required to be at a leaf node.
1597
+ A split point at any depth will only be considered if it leaves at
1598
+ least ``min_samples_leaf`` training samples in each of the left and
1599
+ right branches. This may have the effect of smoothing the model,
1600
+ especially in regression.
1601
+
1602
+ - If int, then consider `min_samples_leaf` as the minimum number.
1603
+ - If float, then `min_samples_leaf` is a fraction and
1604
+ `ceil(min_samples_leaf * n_samples)` are the minimum
1605
+ number of samples for each node.
1606
+
1607
+ .. versionchanged:: 0.18
1608
+ Added float values for fractions.
1609
+
1610
+ min_weight_fraction_leaf : float, default=0.0
1611
+ The minimum weighted fraction of the sum total of weights (of all
1612
+ the input samples) required to be at a leaf node. Samples have
1613
+ equal weight when sample_weight is not provided.
1614
+
1615
+ max_features : int, float, {"auto", "sqrt", "log2"} or None, default=1.0
1616
+ The number of features to consider when looking for the best split:
1617
+
1618
+ - If int, then consider `max_features` features at each split.
1619
+ - If float, then `max_features` is a fraction and
1620
+ `max(1, int(max_features * n_features_in_))` features are considered at each
1621
+ split.
1622
+ - If "auto", then `max_features=n_features`.
1623
+ - If "sqrt", then `max_features=sqrt(n_features)`.
1624
+ - If "log2", then `max_features=log2(n_features)`.
1625
+ - If None, then `max_features=n_features`.
1626
+
1627
+ .. versionchanged:: 1.1
1628
+ The default of `max_features` changed from `"auto"` to `1.0`.
1629
+
1630
+ .. deprecated:: 1.1
1631
+ The `"auto"` option was deprecated in 1.1 and will be removed
1632
+ in 1.3.
1633
+
1634
+ Note: the search for a split does not stop until at least one
1635
+ valid partition of the node samples is found, even if it requires to
1636
+ effectively inspect more than ``max_features`` features.
1637
+
1638
+ random_state : int, RandomState instance or None, default=None
1639
+ Used to pick randomly the `max_features` used at each split.
1640
+ See :term:`Glossary <random_state>` for details.
1641
+
1642
+ min_impurity_decrease : float, default=0.0
1643
+ A node will be split if this split induces a decrease of the impurity
1644
+ greater than or equal to this value.
1645
+
1646
+ The weighted impurity decrease equation is the following::
1647
+
1648
+ N_t / N * (impurity - N_t_R / N_t * right_impurity
1649
+ - N_t_L / N_t * left_impurity)
1650
+
1651
+ where ``N`` is the total number of samples, ``N_t`` is the number of
1652
+ samples at the current node, ``N_t_L`` is the number of samples in the
1653
+ left child, and ``N_t_R`` is the number of samples in the right child.
1654
+
1655
+ ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
1656
+ if ``sample_weight`` is passed.
1657
+
1658
+ .. versionadded:: 0.19
1659
+
1660
+ max_leaf_nodes : int, default=None
1661
+ Grow a tree with ``max_leaf_nodes`` in best-first fashion.
1662
+ Best nodes are defined as relative reduction in impurity.
1663
+ If None then unlimited number of leaf nodes.
1664
+
1665
+ ccp_alpha : non-negative float, default=0.0
1666
+ Complexity parameter used for Minimal Cost-Complexity Pruning. The
1667
+ subtree with the largest cost complexity that is smaller than
1668
+ ``ccp_alpha`` will be chosen. By default, no pruning is performed. See
1669
+ :ref:`minimal_cost_complexity_pruning` for details.
1670
+
1671
+ .. versionadded:: 0.22
1672
+
1673
+ Attributes
1674
+ ----------
1675
+ max_features_ : int
1676
+ The inferred value of max_features.
1677
+
1678
+ n_features_in_ : int
1679
+ Number of features seen during :term:`fit`.
1680
+
1681
+ .. versionadded:: 0.24
1682
+
1683
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
1684
+ Names of features seen during :term:`fit`. Defined only when `X`
1685
+ has feature names that are all strings.
1686
+
1687
+ .. versionadded:: 1.0
1688
+
1689
+ feature_importances_ : ndarray of shape (n_features,)
1690
+ Return impurity-based feature importances (the higher, the more
1691
+ important the feature).
1692
+
1693
+ Warning: impurity-based feature importances can be misleading for
1694
+ high cardinality features (many unique values). See
1695
+ :func:`sklearn.inspection.permutation_importance` as an alternative.
1696
+
1697
+ n_outputs_ : int
1698
+ The number of outputs when ``fit`` is performed.
1699
+
1700
+ tree_ : Tree instance
1701
+ The underlying Tree object. Please refer to
1702
+ ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and
1703
+ :ref:`sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py`
1704
+ for basic usage of these attributes.
1705
+
1706
+ See Also
1707
+ --------
1708
+ ExtraTreeClassifier : An extremely randomized tree classifier.
1709
+ sklearn.ensemble.ExtraTreesClassifier : An extra-trees classifier.
1710
+ sklearn.ensemble.ExtraTreesRegressor : An extra-trees regressor.
1711
+
1712
+ Notes
1713
+ -----
1714
+ The default values for the parameters controlling the size of the trees
1715
+ (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and
1716
+ unpruned trees which can potentially be very large on some data sets. To
1717
+ reduce memory consumption, the complexity and size of the trees should be
1718
+ controlled by setting those parameter values.
1719
+
1720
+ References
1721
+ ----------
1722
+
1723
+ .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees",
1724
+ Machine Learning, 63(1), 3-42, 2006.
1725
+
1726
+ Examples
1727
+ --------
1728
+ >>> from sklearn.datasets import load_diabetes
1729
+ >>> from sklearn.model_selection import train_test_split
1730
+ >>> from sklearn.ensemble import BaggingRegressor
1731
+ >>> from sklearn.tree import ExtraTreeRegressor
1732
+ >>> X, y = load_diabetes(return_X_y=True)
1733
+ >>> X_train, X_test, y_train, y_test = train_test_split(
1734
+ ... X, y, random_state=0)
1735
+ >>> extra_tree = ExtraTreeRegressor(random_state=0)
1736
+ >>> reg = BaggingRegressor(extra_tree, random_state=0).fit(
1737
+ ... X_train, y_train)
1738
+ >>> reg.score(X_test, y_test)
1739
+ 0.33...
1740
+ """
1741
+
1742
+ def __init__(
1743
+ self,
1744
+ *,
1745
+ criterion="squared_error",
1746
+ splitter="random",
1747
+ max_depth=None,
1748
+ min_samples_split=2,
1749
+ min_samples_leaf=1,
1750
+ min_weight_fraction_leaf=0.0,
1751
+ max_features=1.0,
1752
+ random_state=None,
1753
+ min_impurity_decrease=0.0,
1754
+ max_leaf_nodes=None,
1755
+ ccp_alpha=0.0,
1756
+ ):
1757
+ super().__init__(
1758
+ criterion=criterion,
1759
+ splitter=splitter,
1760
+ max_depth=max_depth,
1761
+ min_samples_split=min_samples_split,
1762
+ min_samples_leaf=min_samples_leaf,
1763
+ min_weight_fraction_leaf=min_weight_fraction_leaf,
1764
+ max_features=max_features,
1765
+ max_leaf_nodes=max_leaf_nodes,
1766
+ min_impurity_decrease=min_impurity_decrease,
1767
+ random_state=random_state,
1768
+ ccp_alpha=ccp_alpha,
1769
+ )
videollama2/lib/python3.10/site-packages/sklearn/tree/_splitter.pxd ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors: Gilles Louppe <g.louppe@gmail.com>
2
+ # Peter Prettenhofer <peter.prettenhofer@gmail.com>
3
+ # Brian Holt <bdholt1@gmail.com>
4
+ # Joel Nothman <joel.nothman@gmail.com>
5
+ # Arnaud Joly <arnaud.v.joly@gmail.com>
6
+ # Jacob Schreiber <jmschreiber91@gmail.com>
7
+ #
8
+ # License: BSD 3 clause
9
+
10
+ # See _splitter.pyx for details.
11
+
12
+ from ._criterion cimport Criterion
13
+
14
+ from ._tree cimport DTYPE_t # Type of X
15
+ from ._tree cimport DOUBLE_t # Type of y, sample_weight
16
+ from ._tree cimport SIZE_t # Type for indices and counters
17
+ from ._tree cimport INT32_t # Signed 32 bit integer
18
+ from ._tree cimport UINT32_t # Unsigned 32 bit integer
19
+
20
+ cdef struct SplitRecord:
21
+ # Data to track sample split
22
+ SIZE_t feature # Which feature to split on.
23
+ SIZE_t pos # Split samples array at the given position,
24
+ # i.e. count of samples below threshold for feature.
25
+ # pos is >= end if the node is a leaf.
26
+ double threshold # Threshold to split at.
27
+ double improvement # Impurity improvement given parent node.
28
+ double impurity_left # Impurity of the left split.
29
+ double impurity_right # Impurity of the right split.
30
+
31
+ cdef class Splitter:
32
+ # The splitter searches in the input space for a feature and a threshold
33
+ # to split the samples samples[start:end].
34
+ #
35
+ # The impurity computations are delegated to a criterion object.
36
+
37
+ # Internal structures
38
+ cdef public Criterion criterion # Impurity criterion
39
+ cdef public SIZE_t max_features # Number of features to test
40
+ cdef public SIZE_t min_samples_leaf # Min samples in a leaf
41
+ cdef public double min_weight_leaf # Minimum weight in a leaf
42
+
43
+ cdef object random_state # Random state
44
+ cdef UINT32_t rand_r_state # sklearn_rand_r random number state
45
+
46
+ cdef SIZE_t[::1] samples # Sample indices in X, y
47
+ cdef SIZE_t n_samples # X.shape[0]
48
+ cdef double weighted_n_samples # Weighted number of samples
49
+ cdef SIZE_t[::1] features # Feature indices in X
50
+ cdef SIZE_t[::1] constant_features # Constant features indices
51
+ cdef SIZE_t n_features # X.shape[1]
52
+ cdef DTYPE_t[::1] feature_values # temp. array holding feature values
53
+
54
+ cdef SIZE_t start # Start position for the current node
55
+ cdef SIZE_t end # End position for the current node
56
+
57
+ cdef const DOUBLE_t[:, ::1] y
58
+ cdef const DOUBLE_t[:] sample_weight
59
+
60
+ # The samples vector `samples` is maintained by the Splitter object such
61
+ # that the samples contained in a node are contiguous. With this setting,
62
+ # `node_split` reorganizes the node samples `samples[start:end]` in two
63
+ # subsets `samples[start:pos]` and `samples[pos:end]`.
64
+
65
+ # The 1-d `features` array of size n_features contains the features
66
+ # indices and allows fast sampling without replacement of features.
67
+
68
+ # The 1-d `constant_features` array of size n_features holds in
69
+ # `constant_features[:n_constant_features]` the feature ids with
70
+ # constant values for all the samples that reached a specific node.
71
+ # The value `n_constant_features` is given by the parent node to its
72
+ # child nodes. The content of the range `[n_constant_features:]` is left
73
+ # undefined, but preallocated for performance reasons
74
+ # This allows optimization with depth-based tree building.
75
+
76
+ # Methods
77
+ cdef int init(
78
+ self,
79
+ object X,
80
+ const DOUBLE_t[:, ::1] y,
81
+ const DOUBLE_t[:] sample_weight
82
+ ) except -1
83
+
84
+ cdef int node_reset(
85
+ self,
86
+ SIZE_t start,
87
+ SIZE_t end,
88
+ double* weighted_n_node_samples
89
+ ) nogil except -1
90
+
91
+ cdef int node_split(
92
+ self,
93
+ double impurity, # Impurity of the node
94
+ SplitRecord* split,
95
+ SIZE_t* n_constant_features
96
+ ) nogil except -1
97
+
98
+ cdef void node_value(self, double* dest) nogil
99
+
100
+ cdef double node_impurity(self) nogil
videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__init__.py ADDED
File without changes
videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (175 Bytes). View file
 
videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_export.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_reingold_tilford.cpython-310.pyc ADDED
Binary file (1.36 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/tree/tests/__pycache__/test_tree.cpython-310.pyc ADDED
Binary file (58.6 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/tree/tests/test_export.py ADDED
@@ -0,0 +1,512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Testing for export functions of decision trees (sklearn.tree.export).
3
+ """
4
+ from re import finditer, search
5
+ from textwrap import dedent
6
+
7
+ from numpy.random import RandomState
8
+ import pytest
9
+
10
+ from sklearn.base import is_classifier
11
+ from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
12
+ from sklearn.ensemble import GradientBoostingClassifier
13
+ from sklearn.tree import export_graphviz, plot_tree, export_text
14
+ from io import StringIO
15
+ from sklearn.exceptions import NotFittedError
16
+
17
+ # toy sample
18
+ X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]
19
+ y = [-1, -1, -1, 1, 1, 1]
20
+ y2 = [[-1, 1], [-1, 1], [-1, 1], [1, 2], [1, 2], [1, 3]]
21
+ w = [1, 1, 1, 0.5, 0.5, 0.5]
22
+ y_degraded = [1, 1, 1, 1, 1, 1]
23
+
24
+
25
+ def test_graphviz_toy():
26
+ # Check correctness of export_graphviz
27
+ clf = DecisionTreeClassifier(
28
+ max_depth=3, min_samples_split=2, criterion="gini", random_state=2
29
+ )
30
+ clf.fit(X, y)
31
+
32
+ # Test export code
33
+ contents1 = export_graphviz(clf, out_file=None)
34
+ contents2 = (
35
+ "digraph Tree {\n"
36
+ 'node [shape=box, fontname="helvetica"] ;\n'
37
+ 'edge [fontname="helvetica"] ;\n'
38
+ '0 [label="x[0] <= 0.0\\ngini = 0.5\\nsamples = 6\\n'
39
+ 'value = [3, 3]"] ;\n'
40
+ '1 [label="gini = 0.0\\nsamples = 3\\nvalue = [3, 0]"] ;\n'
41
+ "0 -> 1 [labeldistance=2.5, labelangle=45, "
42
+ 'headlabel="True"] ;\n'
43
+ '2 [label="gini = 0.0\\nsamples = 3\\nvalue = [0, 3]"] ;\n'
44
+ "0 -> 2 [labeldistance=2.5, labelangle=-45, "
45
+ 'headlabel="False"] ;\n'
46
+ "}"
47
+ )
48
+
49
+ assert contents1 == contents2
50
+
51
+ # Test with feature_names
52
+ contents1 = export_graphviz(
53
+ clf, feature_names=["feature0", "feature1"], out_file=None
54
+ )
55
+ contents2 = (
56
+ "digraph Tree {\n"
57
+ 'node [shape=box, fontname="helvetica"] ;\n'
58
+ 'edge [fontname="helvetica"] ;\n'
59
+ '0 [label="feature0 <= 0.0\\ngini = 0.5\\nsamples = 6\\n'
60
+ 'value = [3, 3]"] ;\n'
61
+ '1 [label="gini = 0.0\\nsamples = 3\\nvalue = [3, 0]"] ;\n'
62
+ "0 -> 1 [labeldistance=2.5, labelangle=45, "
63
+ 'headlabel="True"] ;\n'
64
+ '2 [label="gini = 0.0\\nsamples = 3\\nvalue = [0, 3]"] ;\n'
65
+ "0 -> 2 [labeldistance=2.5, labelangle=-45, "
66
+ 'headlabel="False"] ;\n'
67
+ "}"
68
+ )
69
+
70
+ assert contents1 == contents2
71
+
72
+ # Test with class_names
73
+ contents1 = export_graphviz(clf, class_names=["yes", "no"], out_file=None)
74
+ contents2 = (
75
+ "digraph Tree {\n"
76
+ 'node [shape=box, fontname="helvetica"] ;\n'
77
+ 'edge [fontname="helvetica"] ;\n'
78
+ '0 [label="x[0] <= 0.0\\ngini = 0.5\\nsamples = 6\\n'
79
+ 'value = [3, 3]\\nclass = yes"] ;\n'
80
+ '1 [label="gini = 0.0\\nsamples = 3\\nvalue = [3, 0]\\n'
81
+ 'class = yes"] ;\n'
82
+ "0 -> 1 [labeldistance=2.5, labelangle=45, "
83
+ 'headlabel="True"] ;\n'
84
+ '2 [label="gini = 0.0\\nsamples = 3\\nvalue = [0, 3]\\n'
85
+ 'class = no"] ;\n'
86
+ "0 -> 2 [labeldistance=2.5, labelangle=-45, "
87
+ 'headlabel="False"] ;\n'
88
+ "}"
89
+ )
90
+
91
+ assert contents1 == contents2
92
+
93
+ # Test plot_options
94
+ contents1 = export_graphviz(
95
+ clf,
96
+ filled=True,
97
+ impurity=False,
98
+ proportion=True,
99
+ special_characters=True,
100
+ rounded=True,
101
+ out_file=None,
102
+ fontname="sans",
103
+ )
104
+ contents2 = (
105
+ "digraph Tree {\n"
106
+ 'node [shape=box, style="filled, rounded", color="black", '
107
+ 'fontname="sans"] ;\n'
108
+ 'edge [fontname="sans"] ;\n'
109
+ "0 [label=<x<SUB>0</SUB> &le; 0.0<br/>samples = 100.0%<br/>"
110
+ 'value = [0.5, 0.5]>, fillcolor="#ffffff"] ;\n'
111
+ "1 [label=<samples = 50.0%<br/>value = [1.0, 0.0]>, "
112
+ 'fillcolor="#e58139"] ;\n'
113
+ "0 -> 1 [labeldistance=2.5, labelangle=45, "
114
+ 'headlabel="True"] ;\n'
115
+ "2 [label=<samples = 50.0%<br/>value = [0.0, 1.0]>, "
116
+ 'fillcolor="#399de5"] ;\n'
117
+ "0 -> 2 [labeldistance=2.5, labelangle=-45, "
118
+ 'headlabel="False"] ;\n'
119
+ "}"
120
+ )
121
+
122
+ assert contents1 == contents2
123
+
124
+ # Test max_depth
125
+ contents1 = export_graphviz(clf, max_depth=0, class_names=True, out_file=None)
126
+ contents2 = (
127
+ "digraph Tree {\n"
128
+ 'node [shape=box, fontname="helvetica"] ;\n'
129
+ 'edge [fontname="helvetica"] ;\n'
130
+ '0 [label="x[0] <= 0.0\\ngini = 0.5\\nsamples = 6\\n'
131
+ 'value = [3, 3]\\nclass = y[0]"] ;\n'
132
+ '1 [label="(...)"] ;\n'
133
+ "0 -> 1 ;\n"
134
+ '2 [label="(...)"] ;\n'
135
+ "0 -> 2 ;\n"
136
+ "}"
137
+ )
138
+
139
+ assert contents1 == contents2
140
+
141
+ # Test max_depth with plot_options
142
+ contents1 = export_graphviz(
143
+ clf, max_depth=0, filled=True, out_file=None, node_ids=True
144
+ )
145
+ contents2 = (
146
+ "digraph Tree {\n"
147
+ 'node [shape=box, style="filled", color="black", '
148
+ 'fontname="helvetica"] ;\n'
149
+ 'edge [fontname="helvetica"] ;\n'
150
+ '0 [label="node #0\\nx[0] <= 0.0\\ngini = 0.5\\n'
151
+ 'samples = 6\\nvalue = [3, 3]", fillcolor="#ffffff"] ;\n'
152
+ '1 [label="(...)", fillcolor="#C0C0C0"] ;\n'
153
+ "0 -> 1 ;\n"
154
+ '2 [label="(...)", fillcolor="#C0C0C0"] ;\n'
155
+ "0 -> 2 ;\n"
156
+ "}"
157
+ )
158
+
159
+ assert contents1 == contents2
160
+
161
+ # Test multi-output with weighted samples
162
+ clf = DecisionTreeClassifier(
163
+ max_depth=2, min_samples_split=2, criterion="gini", random_state=2
164
+ )
165
+ clf = clf.fit(X, y2, sample_weight=w)
166
+
167
+ contents1 = export_graphviz(clf, filled=True, impurity=False, out_file=None)
168
+ contents2 = (
169
+ "digraph Tree {\n"
170
+ 'node [shape=box, style="filled", color="black", '
171
+ 'fontname="helvetica"] ;\n'
172
+ 'edge [fontname="helvetica"] ;\n'
173
+ '0 [label="x[0] <= 0.0\\nsamples = 6\\n'
174
+ "value = [[3.0, 1.5, 0.0]\\n"
175
+ '[3.0, 1.0, 0.5]]", fillcolor="#ffffff"] ;\n'
176
+ '1 [label="samples = 3\\nvalue = [[3, 0, 0]\\n'
177
+ '[3, 0, 0]]", fillcolor="#e58139"] ;\n'
178
+ "0 -> 1 [labeldistance=2.5, labelangle=45, "
179
+ 'headlabel="True"] ;\n'
180
+ '2 [label="x[0] <= 1.5\\nsamples = 3\\n'
181
+ "value = [[0.0, 1.5, 0.0]\\n"
182
+ '[0.0, 1.0, 0.5]]", fillcolor="#f1bd97"] ;\n'
183
+ "0 -> 2 [labeldistance=2.5, labelangle=-45, "
184
+ 'headlabel="False"] ;\n'
185
+ '3 [label="samples = 2\\nvalue = [[0, 1, 0]\\n'
186
+ '[0, 1, 0]]", fillcolor="#e58139"] ;\n'
187
+ "2 -> 3 ;\n"
188
+ '4 [label="samples = 1\\nvalue = [[0.0, 0.5, 0.0]\\n'
189
+ '[0.0, 0.0, 0.5]]", fillcolor="#e58139"] ;\n'
190
+ "2 -> 4 ;\n"
191
+ "}"
192
+ )
193
+
194
+ assert contents1 == contents2
195
+
196
+ # Test regression output with plot_options
197
+ clf = DecisionTreeRegressor(
198
+ max_depth=3, min_samples_split=2, criterion="squared_error", random_state=2
199
+ )
200
+ clf.fit(X, y)
201
+
202
+ contents1 = export_graphviz(
203
+ clf,
204
+ filled=True,
205
+ leaves_parallel=True,
206
+ out_file=None,
207
+ rotate=True,
208
+ rounded=True,
209
+ fontname="sans",
210
+ )
211
+ contents2 = (
212
+ "digraph Tree {\n"
213
+ 'node [shape=box, style="filled, rounded", color="black", '
214
+ 'fontname="sans"] ;\n'
215
+ "graph [ranksep=equally, splines=polyline] ;\n"
216
+ 'edge [fontname="sans"] ;\n'
217
+ "rankdir=LR ;\n"
218
+ '0 [label="x[0] <= 0.0\\nsquared_error = 1.0\\nsamples = 6\\n'
219
+ 'value = 0.0", fillcolor="#f2c09c"] ;\n'
220
+ '1 [label="squared_error = 0.0\\nsamples = 3\\'
221
+ 'nvalue = -1.0", '
222
+ 'fillcolor="#ffffff"] ;\n'
223
+ "0 -> 1 [labeldistance=2.5, labelangle=-45, "
224
+ 'headlabel="True"] ;\n'
225
+ '2 [label="squared_error = 0.0\\nsamples = 3\\nvalue = 1.0", '
226
+ 'fillcolor="#e58139"] ;\n'
227
+ "0 -> 2 [labeldistance=2.5, labelangle=45, "
228
+ 'headlabel="False"] ;\n'
229
+ "{rank=same ; 0} ;\n"
230
+ "{rank=same ; 1; 2} ;\n"
231
+ "}"
232
+ )
233
+
234
+ assert contents1 == contents2
235
+
236
+ # Test classifier with degraded learning set
237
+ clf = DecisionTreeClassifier(max_depth=3)
238
+ clf.fit(X, y_degraded)
239
+
240
+ contents1 = export_graphviz(clf, filled=True, out_file=None)
241
+ contents2 = (
242
+ "digraph Tree {\n"
243
+ 'node [shape=box, style="filled", color="black", '
244
+ 'fontname="helvetica"] ;\n'
245
+ 'edge [fontname="helvetica"] ;\n'
246
+ '0 [label="gini = 0.0\\nsamples = 6\\nvalue = 6.0", '
247
+ 'fillcolor="#ffffff"] ;\n'
248
+ "}"
249
+ )
250
+
251
+
252
+ def test_graphviz_errors():
253
+ # Check for errors of export_graphviz
254
+ clf = DecisionTreeClassifier(max_depth=3, min_samples_split=2)
255
+
256
+ # Check not-fitted decision tree error
257
+ out = StringIO()
258
+ with pytest.raises(NotFittedError):
259
+ export_graphviz(clf, out)
260
+
261
+ clf.fit(X, y)
262
+
263
+ # Check if it errors when length of feature_names
264
+ # mismatches with number of features
265
+ message = "Length of feature_names, 1 does not match number of features, 2"
266
+ with pytest.raises(ValueError, match=message):
267
+ export_graphviz(clf, None, feature_names=["a"])
268
+
269
+ message = "Length of feature_names, 3 does not match number of features, 2"
270
+ with pytest.raises(ValueError, match=message):
271
+ export_graphviz(clf, None, feature_names=["a", "b", "c"])
272
+
273
+ # Check error when argument is not an estimator
274
+ message = "is not an estimator instance"
275
+ with pytest.raises(TypeError, match=message):
276
+ export_graphviz(clf.fit(X, y).tree_)
277
+
278
+ # Check class_names error
279
+ out = StringIO()
280
+ with pytest.raises(IndexError):
281
+ export_graphviz(clf, out, class_names=[])
282
+
283
+ # Check precision error
284
+ out = StringIO()
285
+ with pytest.raises(ValueError, match="should be greater or equal"):
286
+ export_graphviz(clf, out, precision=-1)
287
+ with pytest.raises(ValueError, match="should be an integer"):
288
+ export_graphviz(clf, out, precision="1")
289
+
290
+
291
+ def test_friedman_mse_in_graphviz():
292
+ clf = DecisionTreeRegressor(criterion="friedman_mse", random_state=0)
293
+ clf.fit(X, y)
294
+ dot_data = StringIO()
295
+ export_graphviz(clf, out_file=dot_data)
296
+
297
+ clf = GradientBoostingClassifier(n_estimators=2, random_state=0)
298
+ clf.fit(X, y)
299
+ for estimator in clf.estimators_:
300
+ export_graphviz(estimator[0], out_file=dot_data)
301
+
302
+ for finding in finditer(r"\[.*?samples.*?\]", dot_data.getvalue()):
303
+ assert "friedman_mse" in finding.group()
304
+
305
+
306
+ def test_precision():
307
+
308
+ rng_reg = RandomState(2)
309
+ rng_clf = RandomState(8)
310
+ for X, y, clf in zip(
311
+ (rng_reg.random_sample((5, 2)), rng_clf.random_sample((1000, 4))),
312
+ (rng_reg.random_sample((5,)), rng_clf.randint(2, size=(1000,))),
313
+ (
314
+ DecisionTreeRegressor(
315
+ criterion="friedman_mse", random_state=0, max_depth=1
316
+ ),
317
+ DecisionTreeClassifier(max_depth=1, random_state=0),
318
+ ),
319
+ ):
320
+
321
+ clf.fit(X, y)
322
+ for precision in (4, 3):
323
+ dot_data = export_graphviz(
324
+ clf, out_file=None, precision=precision, proportion=True
325
+ )
326
+
327
+ # With the current random state, the impurity and the threshold
328
+ # will have the number of precision set in the export_graphviz
329
+ # function. We will check the number of precision with a strict
330
+ # equality. The value reported will have only 2 precision and
331
+ # therefore, only a less equal comparison will be done.
332
+
333
+ # check value
334
+ for finding in finditer(r"value = \d+\.\d+", dot_data):
335
+ assert len(search(r"\.\d+", finding.group()).group()) <= precision + 1
336
+ # check impurity
337
+ if is_classifier(clf):
338
+ pattern = r"gini = \d+\.\d+"
339
+ else:
340
+ pattern = r"friedman_mse = \d+\.\d+"
341
+
342
+ # check impurity
343
+ for finding in finditer(pattern, dot_data):
344
+ assert len(search(r"\.\d+", finding.group()).group()) == precision + 1
345
+ # check threshold
346
+ for finding in finditer(r"<= \d+\.\d+", dot_data):
347
+ assert len(search(r"\.\d+", finding.group()).group()) == precision + 1
348
+
349
+
350
+ def test_export_text_errors():
351
+ clf = DecisionTreeClassifier(max_depth=2, random_state=0)
352
+ clf.fit(X, y)
353
+
354
+ err_msg = "max_depth bust be >= 0, given -1"
355
+ with pytest.raises(ValueError, match=err_msg):
356
+ export_text(clf, max_depth=-1)
357
+ err_msg = "feature_names must contain 2 elements, got 1"
358
+ with pytest.raises(ValueError, match=err_msg):
359
+ export_text(clf, feature_names=["a"])
360
+ err_msg = "decimals must be >= 0, given -1"
361
+ with pytest.raises(ValueError, match=err_msg):
362
+ export_text(clf, decimals=-1)
363
+ err_msg = "spacing must be > 0, given 0"
364
+ with pytest.raises(ValueError, match=err_msg):
365
+ export_text(clf, spacing=0)
366
+
367
+
368
+ def test_export_text():
369
+ clf = DecisionTreeClassifier(max_depth=2, random_state=0)
370
+ clf.fit(X, y)
371
+
372
+ expected_report = dedent(
373
+ """
374
+ |--- feature_1 <= 0.00
375
+ | |--- class: -1
376
+ |--- feature_1 > 0.00
377
+ | |--- class: 1
378
+ """
379
+ ).lstrip()
380
+
381
+ assert export_text(clf) == expected_report
382
+ # testing that leaves at level 1 are not truncated
383
+ assert export_text(clf, max_depth=0) == expected_report
384
+ # testing that the rest of the tree is truncated
385
+ assert export_text(clf, max_depth=10) == expected_report
386
+
387
+ expected_report = dedent(
388
+ """
389
+ |--- b <= 0.00
390
+ | |--- class: -1
391
+ |--- b > 0.00
392
+ | |--- class: 1
393
+ """
394
+ ).lstrip()
395
+ assert export_text(clf, feature_names=["a", "b"]) == expected_report
396
+
397
+ expected_report = dedent(
398
+ """
399
+ |--- feature_1 <= 0.00
400
+ | |--- weights: [3.00, 0.00] class: -1
401
+ |--- feature_1 > 0.00
402
+ | |--- weights: [0.00, 3.00] class: 1
403
+ """
404
+ ).lstrip()
405
+ assert export_text(clf, show_weights=True) == expected_report
406
+
407
+ expected_report = dedent(
408
+ """
409
+ |- feature_1 <= 0.00
410
+ | |- class: -1
411
+ |- feature_1 > 0.00
412
+ | |- class: 1
413
+ """
414
+ ).lstrip()
415
+ assert export_text(clf, spacing=1) == expected_report
416
+
417
+ X_l = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1], [-1, 1]]
418
+ y_l = [-1, -1, -1, 1, 1, 1, 2]
419
+ clf = DecisionTreeClassifier(max_depth=4, random_state=0)
420
+ clf.fit(X_l, y_l)
421
+ expected_report = dedent(
422
+ """
423
+ |--- feature_1 <= 0.00
424
+ | |--- class: -1
425
+ |--- feature_1 > 0.00
426
+ | |--- truncated branch of depth 2
427
+ """
428
+ ).lstrip()
429
+ assert export_text(clf, max_depth=0) == expected_report
430
+
431
+ X_mo = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]
432
+ y_mo = [[-1, -1], [-1, -1], [-1, -1], [1, 1], [1, 1], [1, 1]]
433
+
434
+ reg = DecisionTreeRegressor(max_depth=2, random_state=0)
435
+ reg.fit(X_mo, y_mo)
436
+
437
+ expected_report = dedent(
438
+ """
439
+ |--- feature_1 <= 0.0
440
+ | |--- value: [-1.0, -1.0]
441
+ |--- feature_1 > 0.0
442
+ | |--- value: [1.0, 1.0]
443
+ """
444
+ ).lstrip()
445
+ assert export_text(reg, decimals=1) == expected_report
446
+ assert export_text(reg, decimals=1, show_weights=True) == expected_report
447
+
448
+ X_single = [[-2], [-1], [-1], [1], [1], [2]]
449
+ reg = DecisionTreeRegressor(max_depth=2, random_state=0)
450
+ reg.fit(X_single, y_mo)
451
+
452
+ expected_report = dedent(
453
+ """
454
+ |--- first <= 0.0
455
+ | |--- value: [-1.0, -1.0]
456
+ |--- first > 0.0
457
+ | |--- value: [1.0, 1.0]
458
+ """
459
+ ).lstrip()
460
+ assert export_text(reg, decimals=1, feature_names=["first"]) == expected_report
461
+ assert (
462
+ export_text(reg, decimals=1, show_weights=True, feature_names=["first"])
463
+ == expected_report
464
+ )
465
+
466
+
467
+ def test_plot_tree_entropy(pyplot):
468
+ # mostly smoke tests
469
+ # Check correctness of export_graphviz for criterion = entropy
470
+ clf = DecisionTreeClassifier(
471
+ max_depth=3, min_samples_split=2, criterion="entropy", random_state=2
472
+ )
473
+ clf.fit(X, y)
474
+
475
+ # Test export code
476
+ feature_names = ["first feat", "sepal_width"]
477
+ nodes = plot_tree(clf, feature_names=feature_names)
478
+ assert len(nodes) == 3
479
+ assert (
480
+ nodes[0].get_text()
481
+ == "first feat <= 0.0\nentropy = 1.0\nsamples = 6\nvalue = [3, 3]"
482
+ )
483
+ assert nodes[1].get_text() == "entropy = 0.0\nsamples = 3\nvalue = [3, 0]"
484
+ assert nodes[2].get_text() == "entropy = 0.0\nsamples = 3\nvalue = [0, 3]"
485
+
486
+
487
+ def test_plot_tree_gini(pyplot):
488
+ # mostly smoke tests
489
+ # Check correctness of export_graphviz for criterion = gini
490
+ clf = DecisionTreeClassifier(
491
+ max_depth=3, min_samples_split=2, criterion="gini", random_state=2
492
+ )
493
+ clf.fit(X, y)
494
+
495
+ # Test export code
496
+ feature_names = ["first feat", "sepal_width"]
497
+ nodes = plot_tree(clf, feature_names=feature_names)
498
+ assert len(nodes) == 3
499
+ assert (
500
+ nodes[0].get_text()
501
+ == "first feat <= 0.0\ngini = 0.5\nsamples = 6\nvalue = [3, 3]"
502
+ )
503
+ assert nodes[1].get_text() == "gini = 0.0\nsamples = 3\nvalue = [3, 0]"
504
+ assert nodes[2].get_text() == "gini = 0.0\nsamples = 3\nvalue = [0, 3]"
505
+
506
+
507
+ def test_not_fitted_tree(pyplot):
508
+
509
+ # Testing if not fitted tree throws the correct error
510
+ clf = DecisionTreeRegressor()
511
+ with pytest.raises(NotFittedError):
512
+ plot_tree(clf)
videollama2/lib/python3.10/site-packages/sklearn/tree/tests/test_tree.py ADDED
@@ -0,0 +1,2430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Testing for the tree module (sklearn.tree).
3
+ """
4
+ import copy
5
+ import pickle
6
+ from itertools import product
7
+ import struct
8
+ import io
9
+ import copyreg
10
+
11
+ import pytest
12
+ import numpy as np
13
+ from numpy.testing import assert_allclose
14
+ from scipy.sparse import csc_matrix
15
+ from scipy.sparse import csr_matrix
16
+ from scipy.sparse import coo_matrix
17
+
18
+ import joblib
19
+ from joblib.numpy_pickle import NumpyPickler
20
+
21
+ from sklearn.random_projection import _sparse_random_matrix
22
+
23
+ from sklearn.dummy import DummyRegressor
24
+
25
+ from sklearn.metrics import accuracy_score
26
+ from sklearn.metrics import mean_squared_error
27
+ from sklearn.metrics import mean_poisson_deviance
28
+
29
+ from sklearn.model_selection import train_test_split
30
+
31
+ from sklearn.utils._testing import assert_array_equal
32
+ from sklearn.utils._testing import assert_array_almost_equal
33
+ from sklearn.utils._testing import assert_almost_equal
34
+ from sklearn.utils._testing import create_memmap_backed_data
35
+ from sklearn.utils._testing import ignore_warnings
36
+ from sklearn.utils._testing import skip_if_32bit
37
+
38
+ from sklearn.utils.estimator_checks import check_sample_weights_invariance
39
+ from sklearn.utils.validation import check_random_state
40
+ from sklearn.utils import _IS_32BIT
41
+
42
+ from sklearn.exceptions import NotFittedError
43
+
44
+ from sklearn.tree import DecisionTreeClassifier
45
+ from sklearn.tree import DecisionTreeRegressor
46
+ from sklearn.tree import ExtraTreeClassifier
47
+ from sklearn.tree import ExtraTreeRegressor
48
+
49
+ from sklearn import tree
50
+ from sklearn.tree._tree import TREE_LEAF, TREE_UNDEFINED
51
+ from sklearn.tree._tree import Tree as CythonTree
52
+ from sklearn.tree._tree import _check_n_classes
53
+ from sklearn.tree._tree import _check_value_ndarray
54
+ from sklearn.tree._tree import _check_node_ndarray
55
+ from sklearn.tree._tree import NODE_DTYPE
56
+
57
+ from sklearn.tree._classes import CRITERIA_CLF
58
+ from sklearn.tree._classes import CRITERIA_REG
59
+ from sklearn import datasets
60
+
61
+ from sklearn.utils import compute_sample_weight
62
+
63
+
64
+ CLF_CRITERIONS = ("gini", "log_loss")
65
+ REG_CRITERIONS = ("squared_error", "absolute_error", "friedman_mse", "poisson")
66
+
67
+ CLF_TREES = {
68
+ "DecisionTreeClassifier": DecisionTreeClassifier,
69
+ "ExtraTreeClassifier": ExtraTreeClassifier,
70
+ }
71
+
72
+ REG_TREES = {
73
+ "DecisionTreeRegressor": DecisionTreeRegressor,
74
+ "ExtraTreeRegressor": ExtraTreeRegressor,
75
+ }
76
+
77
+ ALL_TREES: dict = dict()
78
+ ALL_TREES.update(CLF_TREES)
79
+ ALL_TREES.update(REG_TREES)
80
+
81
+ SPARSE_TREES = [
82
+ "DecisionTreeClassifier",
83
+ "DecisionTreeRegressor",
84
+ "ExtraTreeClassifier",
85
+ "ExtraTreeRegressor",
86
+ ]
87
+
88
+
89
+ X_small = np.array(
90
+ [
91
+ [0, 0, 4, 0, 0, 0, 1, -14, 0, -4, 0, 0, 0, 0],
92
+ [0, 0, 5, 3, 0, -4, 0, 0, 1, -5, 0.2, 0, 4, 1],
93
+ [-1, -1, 0, 0, -4.5, 0, 0, 2.1, 1, 0, 0, -4.5, 0, 1],
94
+ [-1, -1, 0, -1.2, 0, 0, 0, 0, 0, 0, 0.2, 0, 0, 1],
95
+ [-1, -1, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1],
96
+ [-1, -2, 0, 4, -3, 10, 4, 0, -3.2, 0, 4, 3, -4, 1],
97
+ [2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -3, 1],
98
+ [2.11, 0, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1],
99
+ [2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0, 0, -2, 1],
100
+ [2.11, 8, -6, -0.5, 0, 11, 0, 0, -3.2, 6, 0.5, 0, -1, 0],
101
+ [2, 8, 5, 1, 0.5, -4, 10, 0, 1, -5, 3, 0, 2, 0],
102
+ [2, 0, 1, 1, 1, -1, 1, 0, 0, -2, 3, 0, 1, 0],
103
+ [2, 0, 1, 2, 3, -1, 10, 2, 0, -1, 1, 2, 2, 0],
104
+ [1, 1, 0, 2, 2, -1, 1, 2, 0, -5, 1, 2, 3, 0],
105
+ [3, 1, 0, 3, 0, -4, 10, 0, 1, -5, 3, 0, 3, 1],
106
+ [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 0.5, 0, -3, 1],
107
+ [2.11, 8, -6, -0.5, 0, 1, 0, 0, -3.2, 6, 1.5, 1, -1, -1],
108
+ [2.11, 8, -6, -0.5, 0, 10, 0, 0, -3.2, 6, 0.5, 0, -1, -1],
109
+ [2, 0, 5, 1, 0.5, -2, 10, 0, 1, -5, 3, 1, 0, -1],
110
+ [2, 0, 1, 1, 1, -2, 1, 0, 0, -2, 0, 0, 0, 1],
111
+ [2, 1, 1, 1, 2, -1, 10, 2, 0, -1, 0, 2, 1, 1],
112
+ [1, 1, 0, 0, 1, -3, 1, 2, 0, -5, 1, 2, 1, 1],
113
+ [3, 1, 0, 1, 0, -4, 1, 0, 1, -2, 0, 0, 1, 0],
114
+ ]
115
+ )
116
+
117
+ 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]
118
+ y_small_reg = [
119
+ 1.0,
120
+ 2.1,
121
+ 1.2,
122
+ 0.05,
123
+ 10,
124
+ 2.4,
125
+ 3.1,
126
+ 1.01,
127
+ 0.01,
128
+ 2.98,
129
+ 3.1,
130
+ 1.1,
131
+ 0.0,
132
+ 1.2,
133
+ 2,
134
+ 11,
135
+ 0,
136
+ 0,
137
+ 4.5,
138
+ 0.201,
139
+ 1.06,
140
+ 0.9,
141
+ 0,
142
+ ]
143
+
144
+ # toy sample
145
+ X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]
146
+ y = [-1, -1, -1, 1, 1, 1]
147
+ T = [[-1, -1], [2, 2], [3, 2]]
148
+ true_result = [-1, 1, 1]
149
+
150
+ # also load the iris dataset
151
+ # and randomly permute it
152
+ iris = datasets.load_iris()
153
+ rng = np.random.RandomState(1)
154
+ perm = rng.permutation(iris.target.size)
155
+ iris.data = iris.data[perm]
156
+ iris.target = iris.target[perm]
157
+
158
+ # also load the diabetes dataset
159
+ # and randomly permute it
160
+ diabetes = datasets.load_diabetes()
161
+ perm = rng.permutation(diabetes.target.size)
162
+ diabetes.data = diabetes.data[perm]
163
+ diabetes.target = diabetes.target[perm]
164
+
165
+ digits = datasets.load_digits()
166
+ perm = rng.permutation(digits.target.size)
167
+ digits.data = digits.data[perm]
168
+ digits.target = digits.target[perm]
169
+
170
+ random_state = check_random_state(0)
171
+ X_multilabel, y_multilabel = datasets.make_multilabel_classification(
172
+ random_state=0, n_samples=30, n_features=10
173
+ )
174
+
175
+ # NB: despite their names X_sparse_* are numpy arrays (and not sparse matrices)
176
+ X_sparse_pos = random_state.uniform(size=(20, 5))
177
+ X_sparse_pos[X_sparse_pos <= 0.8] = 0.0
178
+ y_random = random_state.randint(0, 4, size=(20,))
179
+ X_sparse_mix = _sparse_random_matrix(20, 10, density=0.25, random_state=0).toarray()
180
+
181
+
182
+ DATASETS = {
183
+ "iris": {"X": iris.data, "y": iris.target},
184
+ "diabetes": {"X": diabetes.data, "y": diabetes.target},
185
+ "digits": {"X": digits.data, "y": digits.target},
186
+ "toy": {"X": X, "y": y},
187
+ "clf_small": {"X": X_small, "y": y_small},
188
+ "reg_small": {"X": X_small, "y": y_small_reg},
189
+ "multilabel": {"X": X_multilabel, "y": y_multilabel},
190
+ "sparse-pos": {"X": X_sparse_pos, "y": y_random},
191
+ "sparse-neg": {"X": -X_sparse_pos, "y": y_random},
192
+ "sparse-mix": {"X": X_sparse_mix, "y": y_random},
193
+ "zeros": {"X": np.zeros((20, 3)), "y": y_random},
194
+ }
195
+
196
+ for name in DATASETS:
197
+ DATASETS[name]["X_sparse"] = csc_matrix(DATASETS[name]["X"])
198
+
199
+
200
+ def assert_tree_equal(d, s, message):
201
+ assert (
202
+ s.node_count == d.node_count
203
+ ), "{0}: inequal number of node ({1} != {2})".format(
204
+ message, s.node_count, d.node_count
205
+ )
206
+
207
+ assert_array_equal(
208
+ d.children_right, s.children_right, message + ": inequal children_right"
209
+ )
210
+ assert_array_equal(
211
+ d.children_left, s.children_left, message + ": inequal children_left"
212
+ )
213
+
214
+ external = d.children_right == TREE_LEAF
215
+ internal = np.logical_not(external)
216
+
217
+ assert_array_equal(
218
+ d.feature[internal], s.feature[internal], message + ": inequal features"
219
+ )
220
+ assert_array_equal(
221
+ d.threshold[internal], s.threshold[internal], message + ": inequal threshold"
222
+ )
223
+ assert_array_equal(
224
+ d.n_node_samples.sum(),
225
+ s.n_node_samples.sum(),
226
+ message + ": inequal sum(n_node_samples)",
227
+ )
228
+ assert_array_equal(
229
+ d.n_node_samples, s.n_node_samples, message + ": inequal n_node_samples"
230
+ )
231
+
232
+ assert_almost_equal(d.impurity, s.impurity, err_msg=message + ": inequal impurity")
233
+
234
+ assert_array_almost_equal(
235
+ d.value[external], s.value[external], err_msg=message + ": inequal value"
236
+ )
237
+
238
+
239
+ def test_classification_toy():
240
+ # Check classification on a toy dataset.
241
+ for name, Tree in CLF_TREES.items():
242
+ clf = Tree(random_state=0)
243
+ clf.fit(X, y)
244
+ assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name))
245
+
246
+ clf = Tree(max_features=1, random_state=1)
247
+ clf.fit(X, y)
248
+ assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name))
249
+
250
+
251
+ def test_weighted_classification_toy():
252
+ # Check classification on a weighted toy dataset.
253
+ for name, Tree in CLF_TREES.items():
254
+ clf = Tree(random_state=0)
255
+
256
+ clf.fit(X, y, sample_weight=np.ones(len(X)))
257
+ assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name))
258
+
259
+ clf.fit(X, y, sample_weight=np.full(len(X), 0.5))
260
+ assert_array_equal(clf.predict(T), true_result, "Failed with {0}".format(name))
261
+
262
+
263
+ @pytest.mark.parametrize("Tree", REG_TREES.values())
264
+ @pytest.mark.parametrize("criterion", REG_CRITERIONS)
265
+ def test_regression_toy(Tree, criterion):
266
+ # Check regression on a toy dataset.
267
+ if criterion == "poisson":
268
+ # make target positive while not touching the original y and
269
+ # true_result
270
+ a = np.abs(np.min(y)) + 1
271
+ y_train = np.array(y) + a
272
+ y_test = np.array(true_result) + a
273
+ else:
274
+ y_train = y
275
+ y_test = true_result
276
+
277
+ reg = Tree(criterion=criterion, random_state=1)
278
+ reg.fit(X, y_train)
279
+ assert_allclose(reg.predict(T), y_test)
280
+
281
+ clf = Tree(criterion=criterion, max_features=1, random_state=1)
282
+ clf.fit(X, y_train)
283
+ assert_allclose(reg.predict(T), y_test)
284
+
285
+
286
+ def test_xor():
287
+ # Check on a XOR problem
288
+ y = np.zeros((10, 10))
289
+ y[:5, :5] = 1
290
+ y[5:, 5:] = 1
291
+
292
+ gridx, gridy = np.indices(y.shape)
293
+
294
+ X = np.vstack([gridx.ravel(), gridy.ravel()]).T
295
+ y = y.ravel()
296
+
297
+ for name, Tree in CLF_TREES.items():
298
+ clf = Tree(random_state=0)
299
+ clf.fit(X, y)
300
+ assert clf.score(X, y) == 1.0, "Failed with {0}".format(name)
301
+
302
+ clf = Tree(random_state=0, max_features=1)
303
+ clf.fit(X, y)
304
+ assert clf.score(X, y) == 1.0, "Failed with {0}".format(name)
305
+
306
+
307
+ def test_iris():
308
+ # Check consistency on dataset iris.
309
+ for (name, Tree), criterion in product(CLF_TREES.items(), CLF_CRITERIONS):
310
+ clf = Tree(criterion=criterion, random_state=0)
311
+ clf.fit(iris.data, iris.target)
312
+ score = accuracy_score(clf.predict(iris.data), iris.target)
313
+ assert score > 0.9, "Failed with {0}, criterion = {1} and score = {2}".format(
314
+ name, criterion, score
315
+ )
316
+
317
+ clf = Tree(criterion=criterion, max_features=2, random_state=0)
318
+ clf.fit(iris.data, iris.target)
319
+ score = accuracy_score(clf.predict(iris.data), iris.target)
320
+ assert score > 0.5, "Failed with {0}, criterion = {1} and score = {2}".format(
321
+ name, criterion, score
322
+ )
323
+
324
+
325
+ @pytest.mark.parametrize("name, Tree", REG_TREES.items())
326
+ @pytest.mark.parametrize("criterion", REG_CRITERIONS)
327
+ def test_diabetes_overfit(name, Tree, criterion):
328
+ # check consistency of overfitted trees on the diabetes dataset
329
+ # since the trees will overfit, we expect an MSE of 0
330
+ reg = Tree(criterion=criterion, random_state=0)
331
+ reg.fit(diabetes.data, diabetes.target)
332
+ score = mean_squared_error(diabetes.target, reg.predict(diabetes.data))
333
+ assert score == pytest.approx(
334
+ 0
335
+ ), f"Failed with {name}, criterion = {criterion} and score = {score}"
336
+
337
+
338
+ @skip_if_32bit
339
+ @pytest.mark.parametrize("name, Tree", REG_TREES.items())
340
+ @pytest.mark.parametrize(
341
+ "criterion, max_depth, metric, max_loss",
342
+ [
343
+ ("squared_error", 15, mean_squared_error, 60),
344
+ ("absolute_error", 20, mean_squared_error, 60),
345
+ ("friedman_mse", 15, mean_squared_error, 60),
346
+ ("poisson", 15, mean_poisson_deviance, 30),
347
+ ],
348
+ )
349
+ def test_diabetes_underfit(name, Tree, criterion, max_depth, metric, max_loss):
350
+ # check consistency of trees when the depth and the number of features are
351
+ # limited
352
+
353
+ reg = Tree(criterion=criterion, max_depth=max_depth, max_features=6, random_state=0)
354
+ reg.fit(diabetes.data, diabetes.target)
355
+ loss = metric(diabetes.target, reg.predict(diabetes.data))
356
+ assert 0 < loss < max_loss
357
+
358
+
359
+ def test_probability():
360
+ # Predict probabilities using DecisionTreeClassifier.
361
+
362
+ for name, Tree in CLF_TREES.items():
363
+ clf = Tree(max_depth=1, max_features=1, random_state=42)
364
+ clf.fit(iris.data, iris.target)
365
+
366
+ prob_predict = clf.predict_proba(iris.data)
367
+ assert_array_almost_equal(
368
+ np.sum(prob_predict, 1),
369
+ np.ones(iris.data.shape[0]),
370
+ err_msg="Failed with {0}".format(name),
371
+ )
372
+ assert_array_equal(
373
+ np.argmax(prob_predict, 1),
374
+ clf.predict(iris.data),
375
+ err_msg="Failed with {0}".format(name),
376
+ )
377
+ assert_almost_equal(
378
+ clf.predict_proba(iris.data),
379
+ np.exp(clf.predict_log_proba(iris.data)),
380
+ 8,
381
+ err_msg="Failed with {0}".format(name),
382
+ )
383
+
384
+
385
+ def test_arrayrepr():
386
+ # Check the array representation.
387
+ # Check resize
388
+ X = np.arange(10000)[:, np.newaxis]
389
+ y = np.arange(10000)
390
+
391
+ for name, Tree in REG_TREES.items():
392
+ reg = Tree(max_depth=None, random_state=0)
393
+ reg.fit(X, y)
394
+
395
+
396
+ def test_pure_set():
397
+ # Check when y is pure.
398
+ X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]
399
+ y = [1, 1, 1, 1, 1, 1]
400
+
401
+ for name, TreeClassifier in CLF_TREES.items():
402
+ clf = TreeClassifier(random_state=0)
403
+ clf.fit(X, y)
404
+ assert_array_equal(clf.predict(X), y, err_msg="Failed with {0}".format(name))
405
+
406
+ for name, TreeRegressor in REG_TREES.items():
407
+ reg = TreeRegressor(random_state=0)
408
+ reg.fit(X, y)
409
+ assert_almost_equal(reg.predict(X), y, err_msg="Failed with {0}".format(name))
410
+
411
+
412
+ def test_numerical_stability():
413
+ # Check numerical stability.
414
+ X = np.array(
415
+ [
416
+ [152.08097839, 140.40744019, 129.75102234, 159.90493774],
417
+ [142.50700378, 135.81935120, 117.82884979, 162.75781250],
418
+ [127.28772736, 140.40744019, 129.75102234, 159.90493774],
419
+ [132.37025452, 143.71923828, 138.35694885, 157.84558105],
420
+ [103.10237122, 143.71928406, 138.35696411, 157.84559631],
421
+ [127.71276855, 143.71923828, 138.35694885, 157.84558105],
422
+ [120.91514587, 140.40744019, 129.75102234, 159.90493774],
423
+ ]
424
+ )
425
+
426
+ y = np.array([1.0, 0.70209277, 0.53896582, 0.0, 0.90914464, 0.48026916, 0.49622521])
427
+
428
+ with np.errstate(all="raise"):
429
+ for name, Tree in REG_TREES.items():
430
+ reg = Tree(random_state=0)
431
+ reg.fit(X, y)
432
+ reg.fit(X, -y)
433
+ reg.fit(-X, y)
434
+ reg.fit(-X, -y)
435
+
436
+
437
+ def test_importances():
438
+ # Check variable importances.
439
+ X, y = datasets.make_classification(
440
+ n_samples=5000,
441
+ n_features=10,
442
+ n_informative=3,
443
+ n_redundant=0,
444
+ n_repeated=0,
445
+ shuffle=False,
446
+ random_state=0,
447
+ )
448
+
449
+ for name, Tree in CLF_TREES.items():
450
+ clf = Tree(random_state=0)
451
+
452
+ clf.fit(X, y)
453
+ importances = clf.feature_importances_
454
+ n_important = np.sum(importances > 0.1)
455
+
456
+ assert importances.shape[0] == 10, "Failed with {0}".format(name)
457
+ assert n_important == 3, "Failed with {0}".format(name)
458
+
459
+ # Check on iris that importances are the same for all builders
460
+ clf = DecisionTreeClassifier(random_state=0)
461
+ clf.fit(iris.data, iris.target)
462
+ clf2 = DecisionTreeClassifier(random_state=0, max_leaf_nodes=len(iris.data))
463
+ clf2.fit(iris.data, iris.target)
464
+
465
+ assert_array_equal(clf.feature_importances_, clf2.feature_importances_)
466
+
467
+
468
+ def test_importances_raises():
469
+ # Check if variable importance before fit raises ValueError.
470
+ clf = DecisionTreeClassifier()
471
+ with pytest.raises(ValueError):
472
+ getattr(clf, "feature_importances_")
473
+
474
+
475
+ def test_importances_gini_equal_squared_error():
476
+ # Check that gini is equivalent to squared_error for binary output variable
477
+
478
+ X, y = datasets.make_classification(
479
+ n_samples=2000,
480
+ n_features=10,
481
+ n_informative=3,
482
+ n_redundant=0,
483
+ n_repeated=0,
484
+ shuffle=False,
485
+ random_state=0,
486
+ )
487
+
488
+ # The gini index and the mean square error (variance) might differ due
489
+ # to numerical instability. Since those instabilities mainly occurs at
490
+ # high tree depth, we restrict this maximal depth.
491
+ clf = DecisionTreeClassifier(criterion="gini", max_depth=5, random_state=0).fit(
492
+ X, y
493
+ )
494
+ reg = DecisionTreeRegressor(
495
+ criterion="squared_error", max_depth=5, random_state=0
496
+ ).fit(X, y)
497
+
498
+ assert_almost_equal(clf.feature_importances_, reg.feature_importances_)
499
+ assert_array_equal(clf.tree_.feature, reg.tree_.feature)
500
+ assert_array_equal(clf.tree_.children_left, reg.tree_.children_left)
501
+ assert_array_equal(clf.tree_.children_right, reg.tree_.children_right)
502
+ assert_array_equal(clf.tree_.n_node_samples, reg.tree_.n_node_samples)
503
+
504
+
505
+ # TODO(1.3): Remove warning filter
506
+ @pytest.mark.filterwarnings("ignore:`max_features='auto'` has been deprecated in 1.1")
507
+ def test_max_features():
508
+ # Check max_features.
509
+ for name, TreeRegressor in REG_TREES.items():
510
+ reg = TreeRegressor(max_features="auto")
511
+ reg.fit(diabetes.data, diabetes.target)
512
+ assert reg.max_features_ == diabetes.data.shape[1]
513
+
514
+ for name, TreeClassifier in CLF_TREES.items():
515
+ clf = TreeClassifier(max_features="auto")
516
+ clf.fit(iris.data, iris.target)
517
+ assert clf.max_features_ == 2
518
+
519
+ for name, TreeEstimator in ALL_TREES.items():
520
+ est = TreeEstimator(max_features="sqrt")
521
+ est.fit(iris.data, iris.target)
522
+ assert est.max_features_ == int(np.sqrt(iris.data.shape[1]))
523
+
524
+ est = TreeEstimator(max_features="log2")
525
+ est.fit(iris.data, iris.target)
526
+ assert est.max_features_ == int(np.log2(iris.data.shape[1]))
527
+
528
+ est = TreeEstimator(max_features=1)
529
+ est.fit(iris.data, iris.target)
530
+ assert est.max_features_ == 1
531
+
532
+ est = TreeEstimator(max_features=3)
533
+ est.fit(iris.data, iris.target)
534
+ assert est.max_features_ == 3
535
+
536
+ est = TreeEstimator(max_features=0.01)
537
+ est.fit(iris.data, iris.target)
538
+ assert est.max_features_ == 1
539
+
540
+ est = TreeEstimator(max_features=0.5)
541
+ est.fit(iris.data, iris.target)
542
+ assert est.max_features_ == int(0.5 * iris.data.shape[1])
543
+
544
+ est = TreeEstimator(max_features=1.0)
545
+ est.fit(iris.data, iris.target)
546
+ assert est.max_features_ == iris.data.shape[1]
547
+
548
+ est = TreeEstimator(max_features=None)
549
+ est.fit(iris.data, iris.target)
550
+ assert est.max_features_ == iris.data.shape[1]
551
+
552
+
553
+ def test_error():
554
+ # Test that it gives proper exception on deficient input.
555
+ for name, TreeEstimator in CLF_TREES.items():
556
+ # predict before fit
557
+ est = TreeEstimator()
558
+ with pytest.raises(NotFittedError):
559
+ est.predict_proba(X)
560
+
561
+ est.fit(X, y)
562
+ X2 = [[-2, -1, 1]] # wrong feature shape for sample
563
+ with pytest.raises(ValueError):
564
+ est.predict_proba(X2)
565
+
566
+ # Wrong dimensions
567
+ est = TreeEstimator()
568
+ y2 = y[:-1]
569
+ with pytest.raises(ValueError):
570
+ est.fit(X, y2)
571
+
572
+ # Test with arrays that are non-contiguous.
573
+ Xf = np.asfortranarray(X)
574
+ est = TreeEstimator()
575
+ est.fit(Xf, y)
576
+ assert_almost_equal(est.predict(T), true_result)
577
+
578
+ # predict before fitting
579
+ est = TreeEstimator()
580
+ with pytest.raises(NotFittedError):
581
+ est.predict(T)
582
+
583
+ # predict on vector with different dims
584
+ est.fit(X, y)
585
+ t = np.asarray(T)
586
+ with pytest.raises(ValueError):
587
+ est.predict(t[:, 1:])
588
+
589
+ # wrong sample shape
590
+ Xt = np.array(X).T
591
+
592
+ est = TreeEstimator()
593
+ est.fit(np.dot(X, Xt), y)
594
+ with pytest.raises(ValueError):
595
+ est.predict(X)
596
+ with pytest.raises(ValueError):
597
+ est.apply(X)
598
+
599
+ clf = TreeEstimator()
600
+ clf.fit(X, y)
601
+ with pytest.raises(ValueError):
602
+ clf.predict(Xt)
603
+ with pytest.raises(ValueError):
604
+ clf.apply(Xt)
605
+
606
+ # apply before fitting
607
+ est = TreeEstimator()
608
+ with pytest.raises(NotFittedError):
609
+ est.apply(T)
610
+
611
+ # non positive target for Poisson splitting Criterion
612
+ est = DecisionTreeRegressor(criterion="poisson")
613
+ with pytest.raises(ValueError, match="y is not positive.*Poisson"):
614
+ est.fit([[0, 1, 2]], [0, 0, 0])
615
+ with pytest.raises(ValueError, match="Some.*y are negative.*Poisson"):
616
+ est.fit([[0, 1, 2]], [5, -0.1, 2])
617
+
618
+
619
+ def test_min_samples_split():
620
+ """Test min_samples_split parameter"""
621
+ X = np.asfortranarray(iris.data, dtype=tree._tree.DTYPE)
622
+ y = iris.target
623
+
624
+ # test both DepthFirstTreeBuilder and BestFirstTreeBuilder
625
+ # by setting max_leaf_nodes
626
+ for max_leaf_nodes, name in product((None, 1000), ALL_TREES.keys()):
627
+ TreeEstimator = ALL_TREES[name]
628
+
629
+ # test for integer parameter
630
+ est = TreeEstimator(
631
+ min_samples_split=10, max_leaf_nodes=max_leaf_nodes, random_state=0
632
+ )
633
+ est.fit(X, y)
634
+ # count samples on nodes, -1 means it is a leaf
635
+ node_samples = est.tree_.n_node_samples[est.tree_.children_left != -1]
636
+
637
+ assert np.min(node_samples) > 9, "Failed with {0}".format(name)
638
+
639
+ # test for float parameter
640
+ est = TreeEstimator(
641
+ min_samples_split=0.2, max_leaf_nodes=max_leaf_nodes, random_state=0
642
+ )
643
+ est.fit(X, y)
644
+ # count samples on nodes, -1 means it is a leaf
645
+ node_samples = est.tree_.n_node_samples[est.tree_.children_left != -1]
646
+
647
+ assert np.min(node_samples) > 9, "Failed with {0}".format(name)
648
+
649
+
650
+ def test_min_samples_leaf():
651
+ # Test if leaves contain more than leaf_count training examples
652
+ X = np.asfortranarray(iris.data, dtype=tree._tree.DTYPE)
653
+ y = iris.target
654
+
655
+ # test both DepthFirstTreeBuilder and BestFirstTreeBuilder
656
+ # by setting max_leaf_nodes
657
+ for max_leaf_nodes, name in product((None, 1000), ALL_TREES.keys()):
658
+ TreeEstimator = ALL_TREES[name]
659
+
660
+ # test integer parameter
661
+ est = TreeEstimator(
662
+ min_samples_leaf=5, max_leaf_nodes=max_leaf_nodes, random_state=0
663
+ )
664
+ est.fit(X, y)
665
+ out = est.tree_.apply(X)
666
+ node_counts = np.bincount(out)
667
+ # drop inner nodes
668
+ leaf_count = node_counts[node_counts != 0]
669
+ assert np.min(leaf_count) > 4, "Failed with {0}".format(name)
670
+
671
+ # test float parameter
672
+ est = TreeEstimator(
673
+ min_samples_leaf=0.1, max_leaf_nodes=max_leaf_nodes, random_state=0
674
+ )
675
+ est.fit(X, y)
676
+ out = est.tree_.apply(X)
677
+ node_counts = np.bincount(out)
678
+ # drop inner nodes
679
+ leaf_count = node_counts[node_counts != 0]
680
+ assert np.min(leaf_count) > 4, "Failed with {0}".format(name)
681
+
682
+
683
+ def check_min_weight_fraction_leaf(name, datasets, sparse=False):
684
+ """Test if leaves contain at least min_weight_fraction_leaf of the
685
+ training set"""
686
+ if sparse:
687
+ X = DATASETS[datasets]["X_sparse"].astype(np.float32)
688
+ else:
689
+ X = DATASETS[datasets]["X"].astype(np.float32)
690
+ y = DATASETS[datasets]["y"]
691
+
692
+ weights = rng.rand(X.shape[0])
693
+ total_weight = np.sum(weights)
694
+
695
+ TreeEstimator = ALL_TREES[name]
696
+
697
+ # test both DepthFirstTreeBuilder and BestFirstTreeBuilder
698
+ # by setting max_leaf_nodes
699
+ for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 6)):
700
+ est = TreeEstimator(
701
+ min_weight_fraction_leaf=frac, max_leaf_nodes=max_leaf_nodes, random_state=0
702
+ )
703
+ est.fit(X, y, sample_weight=weights)
704
+
705
+ if sparse:
706
+ out = est.tree_.apply(X.tocsr())
707
+
708
+ else:
709
+ out = est.tree_.apply(X)
710
+
711
+ node_weights = np.bincount(out, weights=weights)
712
+ # drop inner nodes
713
+ leaf_weights = node_weights[node_weights != 0]
714
+ assert (
715
+ np.min(leaf_weights) >= total_weight * est.min_weight_fraction_leaf
716
+ ), "Failed with {0} min_weight_fraction_leaf={1}".format(
717
+ name, est.min_weight_fraction_leaf
718
+ )
719
+
720
+ # test case with no weights passed in
721
+ total_weight = X.shape[0]
722
+
723
+ for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 6)):
724
+ est = TreeEstimator(
725
+ min_weight_fraction_leaf=frac, max_leaf_nodes=max_leaf_nodes, random_state=0
726
+ )
727
+ est.fit(X, y)
728
+
729
+ if sparse:
730
+ out = est.tree_.apply(X.tocsr())
731
+ else:
732
+ out = est.tree_.apply(X)
733
+
734
+ node_weights = np.bincount(out)
735
+ # drop inner nodes
736
+ leaf_weights = node_weights[node_weights != 0]
737
+ assert (
738
+ np.min(leaf_weights) >= total_weight * est.min_weight_fraction_leaf
739
+ ), "Failed with {0} min_weight_fraction_leaf={1}".format(
740
+ name, est.min_weight_fraction_leaf
741
+ )
742
+
743
+
744
+ @pytest.mark.parametrize("name", ALL_TREES)
745
+ def test_min_weight_fraction_leaf_on_dense_input(name):
746
+ check_min_weight_fraction_leaf(name, "iris")
747
+
748
+
749
+ @pytest.mark.parametrize("name", SPARSE_TREES)
750
+ def test_min_weight_fraction_leaf_on_sparse_input(name):
751
+ check_min_weight_fraction_leaf(name, "multilabel", True)
752
+
753
+
754
+ def check_min_weight_fraction_leaf_with_min_samples_leaf(name, datasets, sparse=False):
755
+ """Test the interaction between min_weight_fraction_leaf and
756
+ min_samples_leaf when sample_weights is not provided in fit."""
757
+ if sparse:
758
+ X = DATASETS[datasets]["X_sparse"].astype(np.float32)
759
+ else:
760
+ X = DATASETS[datasets]["X"].astype(np.float32)
761
+ y = DATASETS[datasets]["y"]
762
+
763
+ total_weight = X.shape[0]
764
+ TreeEstimator = ALL_TREES[name]
765
+ for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 3)):
766
+ # test integer min_samples_leaf
767
+ est = TreeEstimator(
768
+ min_weight_fraction_leaf=frac,
769
+ max_leaf_nodes=max_leaf_nodes,
770
+ min_samples_leaf=5,
771
+ random_state=0,
772
+ )
773
+ est.fit(X, y)
774
+
775
+ if sparse:
776
+ out = est.tree_.apply(X.tocsr())
777
+ else:
778
+ out = est.tree_.apply(X)
779
+
780
+ node_weights = np.bincount(out)
781
+ # drop inner nodes
782
+ leaf_weights = node_weights[node_weights != 0]
783
+ assert np.min(leaf_weights) >= max(
784
+ (total_weight * est.min_weight_fraction_leaf), 5
785
+ ), "Failed with {0} min_weight_fraction_leaf={1}, min_samples_leaf={2}".format(
786
+ name, est.min_weight_fraction_leaf, est.min_samples_leaf
787
+ )
788
+ for max_leaf_nodes, frac in product((None, 1000), np.linspace(0, 0.5, 3)):
789
+ # test float min_samples_leaf
790
+ est = TreeEstimator(
791
+ min_weight_fraction_leaf=frac,
792
+ max_leaf_nodes=max_leaf_nodes,
793
+ min_samples_leaf=0.1,
794
+ random_state=0,
795
+ )
796
+ est.fit(X, y)
797
+
798
+ if sparse:
799
+ out = est.tree_.apply(X.tocsr())
800
+ else:
801
+ out = est.tree_.apply(X)
802
+
803
+ node_weights = np.bincount(out)
804
+ # drop inner nodes
805
+ leaf_weights = node_weights[node_weights != 0]
806
+ assert np.min(leaf_weights) >= max(
807
+ (total_weight * est.min_weight_fraction_leaf),
808
+ (total_weight * est.min_samples_leaf),
809
+ ), "Failed with {0} min_weight_fraction_leaf={1}, min_samples_leaf={2}".format(
810
+ name, est.min_weight_fraction_leaf, est.min_samples_leaf
811
+ )
812
+
813
+
814
+ @pytest.mark.parametrize("name", ALL_TREES)
815
+ def test_min_weight_fraction_leaf_with_min_samples_leaf_on_dense_input(name):
816
+ check_min_weight_fraction_leaf_with_min_samples_leaf(name, "iris")
817
+
818
+
819
+ @pytest.mark.parametrize("name", SPARSE_TREES)
820
+ def test_min_weight_fraction_leaf_with_min_samples_leaf_on_sparse_input(name):
821
+ check_min_weight_fraction_leaf_with_min_samples_leaf(name, "multilabel", True)
822
+
823
+
824
+ def test_min_impurity_decrease():
825
+ # test if min_impurity_decrease ensure that a split is made only if
826
+ # if the impurity decrease is at least that value
827
+ X, y = datasets.make_classification(n_samples=10000, random_state=42)
828
+
829
+ # test both DepthFirstTreeBuilder and BestFirstTreeBuilder
830
+ # by setting max_leaf_nodes
831
+ for max_leaf_nodes, name in product((None, 1000), ALL_TREES.keys()):
832
+ TreeEstimator = ALL_TREES[name]
833
+
834
+ # Check default value of min_impurity_decrease, 1e-7
835
+ est1 = TreeEstimator(max_leaf_nodes=max_leaf_nodes, random_state=0)
836
+ # Check with explicit value of 0.05
837
+ est2 = TreeEstimator(
838
+ max_leaf_nodes=max_leaf_nodes, min_impurity_decrease=0.05, random_state=0
839
+ )
840
+ # Check with a much lower value of 0.0001
841
+ est3 = TreeEstimator(
842
+ max_leaf_nodes=max_leaf_nodes, min_impurity_decrease=0.0001, random_state=0
843
+ )
844
+ # Check with a much lower value of 0.1
845
+ est4 = TreeEstimator(
846
+ max_leaf_nodes=max_leaf_nodes, min_impurity_decrease=0.1, random_state=0
847
+ )
848
+
849
+ for est, expected_decrease in (
850
+ (est1, 1e-7),
851
+ (est2, 0.05),
852
+ (est3, 0.0001),
853
+ (est4, 0.1),
854
+ ):
855
+ assert (
856
+ est.min_impurity_decrease <= expected_decrease
857
+ ), "Failed, min_impurity_decrease = {0} > {1}".format(
858
+ est.min_impurity_decrease, expected_decrease
859
+ )
860
+ est.fit(X, y)
861
+ for node in range(est.tree_.node_count):
862
+ # If current node is a not leaf node, check if the split was
863
+ # justified w.r.t the min_impurity_decrease
864
+ if est.tree_.children_left[node] != TREE_LEAF:
865
+ imp_parent = est.tree_.impurity[node]
866
+ wtd_n_node = est.tree_.weighted_n_node_samples[node]
867
+
868
+ left = est.tree_.children_left[node]
869
+ wtd_n_left = est.tree_.weighted_n_node_samples[left]
870
+ imp_left = est.tree_.impurity[left]
871
+ wtd_imp_left = wtd_n_left * imp_left
872
+
873
+ right = est.tree_.children_right[node]
874
+ wtd_n_right = est.tree_.weighted_n_node_samples[right]
875
+ imp_right = est.tree_.impurity[right]
876
+ wtd_imp_right = wtd_n_right * imp_right
877
+
878
+ wtd_avg_left_right_imp = wtd_imp_right + wtd_imp_left
879
+ wtd_avg_left_right_imp /= wtd_n_node
880
+
881
+ fractional_node_weight = (
882
+ est.tree_.weighted_n_node_samples[node] / X.shape[0]
883
+ )
884
+
885
+ actual_decrease = fractional_node_weight * (
886
+ imp_parent - wtd_avg_left_right_imp
887
+ )
888
+
889
+ assert (
890
+ actual_decrease >= expected_decrease
891
+ ), "Failed with {0} expected min_impurity_decrease={1}".format(
892
+ actual_decrease, expected_decrease
893
+ )
894
+
895
+
896
+ def test_pickle():
897
+ """Test pickling preserves Tree properties and performance."""
898
+ for name, TreeEstimator in ALL_TREES.items():
899
+ if "Classifier" in name:
900
+ X, y = iris.data, iris.target
901
+ else:
902
+ X, y = diabetes.data, diabetes.target
903
+
904
+ est = TreeEstimator(random_state=0)
905
+ est.fit(X, y)
906
+ score = est.score(X, y)
907
+
908
+ # test that all class properties are maintained
909
+ attributes = [
910
+ "max_depth",
911
+ "node_count",
912
+ "capacity",
913
+ "n_classes",
914
+ "children_left",
915
+ "children_right",
916
+ "n_leaves",
917
+ "feature",
918
+ "threshold",
919
+ "impurity",
920
+ "n_node_samples",
921
+ "weighted_n_node_samples",
922
+ "value",
923
+ ]
924
+ fitted_attribute = {
925
+ attribute: getattr(est.tree_, attribute) for attribute in attributes
926
+ }
927
+
928
+ serialized_object = pickle.dumps(est)
929
+ est2 = pickle.loads(serialized_object)
930
+ assert type(est2) == est.__class__
931
+
932
+ score2 = est2.score(X, y)
933
+ assert (
934
+ score == score2
935
+ ), "Failed to generate same score after pickling with {0}".format(name)
936
+ for attribute in fitted_attribute:
937
+ assert_array_equal(
938
+ getattr(est2.tree_, attribute),
939
+ fitted_attribute[attribute],
940
+ err_msg=(
941
+ f"Failed to generate same attribute {attribute} after pickling with"
942
+ f" {name}"
943
+ ),
944
+ )
945
+
946
+
947
+ def test_multioutput():
948
+ # Check estimators on multi-output problems.
949
+ X = [
950
+ [-2, -1],
951
+ [-1, -1],
952
+ [-1, -2],
953
+ [1, 1],
954
+ [1, 2],
955
+ [2, 1],
956
+ [-2, 1],
957
+ [-1, 1],
958
+ [-1, 2],
959
+ [2, -1],
960
+ [1, -1],
961
+ [1, -2],
962
+ ]
963
+
964
+ y = [
965
+ [-1, 0],
966
+ [-1, 0],
967
+ [-1, 0],
968
+ [1, 1],
969
+ [1, 1],
970
+ [1, 1],
971
+ [-1, 2],
972
+ [-1, 2],
973
+ [-1, 2],
974
+ [1, 3],
975
+ [1, 3],
976
+ [1, 3],
977
+ ]
978
+
979
+ T = [[-1, -1], [1, 1], [-1, 1], [1, -1]]
980
+ y_true = [[-1, 0], [1, 1], [-1, 2], [1, 3]]
981
+
982
+ # toy classification problem
983
+ for name, TreeClassifier in CLF_TREES.items():
984
+ clf = TreeClassifier(random_state=0)
985
+ y_hat = clf.fit(X, y).predict(T)
986
+ assert_array_equal(y_hat, y_true)
987
+ assert y_hat.shape == (4, 2)
988
+
989
+ proba = clf.predict_proba(T)
990
+ assert len(proba) == 2
991
+ assert proba[0].shape == (4, 2)
992
+ assert proba[1].shape == (4, 4)
993
+
994
+ log_proba = clf.predict_log_proba(T)
995
+ assert len(log_proba) == 2
996
+ assert log_proba[0].shape == (4, 2)
997
+ assert log_proba[1].shape == (4, 4)
998
+
999
+ # toy regression problem
1000
+ for name, TreeRegressor in REG_TREES.items():
1001
+ reg = TreeRegressor(random_state=0)
1002
+ y_hat = reg.fit(X, y).predict(T)
1003
+ assert_almost_equal(y_hat, y_true)
1004
+ assert y_hat.shape == (4, 2)
1005
+
1006
+
1007
+ def test_classes_shape():
1008
+ # Test that n_classes_ and classes_ have proper shape.
1009
+ for name, TreeClassifier in CLF_TREES.items():
1010
+ # Classification, single output
1011
+ clf = TreeClassifier(random_state=0)
1012
+ clf.fit(X, y)
1013
+
1014
+ assert clf.n_classes_ == 2
1015
+ assert_array_equal(clf.classes_, [-1, 1])
1016
+
1017
+ # Classification, multi-output
1018
+ _y = np.vstack((y, np.array(y) * 2)).T
1019
+ clf = TreeClassifier(random_state=0)
1020
+ clf.fit(X, _y)
1021
+ assert len(clf.n_classes_) == 2
1022
+ assert len(clf.classes_) == 2
1023
+ assert_array_equal(clf.n_classes_, [2, 2])
1024
+ assert_array_equal(clf.classes_, [[-1, 1], [-2, 2]])
1025
+
1026
+
1027
+ def test_unbalanced_iris():
1028
+ # Check class rebalancing.
1029
+ unbalanced_X = iris.data[:125]
1030
+ unbalanced_y = iris.target[:125]
1031
+ sample_weight = compute_sample_weight("balanced", unbalanced_y)
1032
+
1033
+ for name, TreeClassifier in CLF_TREES.items():
1034
+ clf = TreeClassifier(random_state=0)
1035
+ clf.fit(unbalanced_X, unbalanced_y, sample_weight=sample_weight)
1036
+ assert_almost_equal(clf.predict(unbalanced_X), unbalanced_y)
1037
+
1038
+
1039
+ def test_memory_layout():
1040
+ # Check that it works no matter the memory layout
1041
+ for (name, TreeEstimator), dtype in product(
1042
+ ALL_TREES.items(), [np.float64, np.float32]
1043
+ ):
1044
+ est = TreeEstimator(random_state=0)
1045
+
1046
+ # Nothing
1047
+ X = np.asarray(iris.data, dtype=dtype)
1048
+ y = iris.target
1049
+ assert_array_equal(est.fit(X, y).predict(X), y)
1050
+
1051
+ # C-order
1052
+ X = np.asarray(iris.data, order="C", dtype=dtype)
1053
+ y = iris.target
1054
+ assert_array_equal(est.fit(X, y).predict(X), y)
1055
+
1056
+ # F-order
1057
+ X = np.asarray(iris.data, order="F", dtype=dtype)
1058
+ y = iris.target
1059
+ assert_array_equal(est.fit(X, y).predict(X), y)
1060
+
1061
+ # Contiguous
1062
+ X = np.ascontiguousarray(iris.data, dtype=dtype)
1063
+ y = iris.target
1064
+ assert_array_equal(est.fit(X, y).predict(X), y)
1065
+
1066
+ # csr matrix
1067
+ X = csr_matrix(iris.data, dtype=dtype)
1068
+ y = iris.target
1069
+ assert_array_equal(est.fit(X, y).predict(X), y)
1070
+
1071
+ # csc_matrix
1072
+ X = csc_matrix(iris.data, dtype=dtype)
1073
+ y = iris.target
1074
+ assert_array_equal(est.fit(X, y).predict(X), y)
1075
+
1076
+ # Strided
1077
+ X = np.asarray(iris.data[::3], dtype=dtype)
1078
+ y = iris.target[::3]
1079
+ assert_array_equal(est.fit(X, y).predict(X), y)
1080
+
1081
+
1082
+ def test_sample_weight():
1083
+ # Check sample weighting.
1084
+ # Test that zero-weighted samples are not taken into account
1085
+ X = np.arange(100)[:, np.newaxis]
1086
+ y = np.ones(100)
1087
+ y[:50] = 0.0
1088
+
1089
+ sample_weight = np.ones(100)
1090
+ sample_weight[y == 0] = 0.0
1091
+
1092
+ clf = DecisionTreeClassifier(random_state=0)
1093
+ clf.fit(X, y, sample_weight=sample_weight)
1094
+ assert_array_equal(clf.predict(X), np.ones(100))
1095
+
1096
+ # Test that low weighted samples are not taken into account at low depth
1097
+ X = np.arange(200)[:, np.newaxis]
1098
+ y = np.zeros(200)
1099
+ y[50:100] = 1
1100
+ y[100:200] = 2
1101
+ X[100:200, 0] = 200
1102
+
1103
+ sample_weight = np.ones(200)
1104
+
1105
+ sample_weight[y == 2] = 0.51 # Samples of class '2' are still weightier
1106
+ clf = DecisionTreeClassifier(max_depth=1, random_state=0)
1107
+ clf.fit(X, y, sample_weight=sample_weight)
1108
+ assert clf.tree_.threshold[0] == 149.5
1109
+
1110
+ sample_weight[y == 2] = 0.5 # Samples of class '2' are no longer weightier
1111
+ clf = DecisionTreeClassifier(max_depth=1, random_state=0)
1112
+ clf.fit(X, y, sample_weight=sample_weight)
1113
+ assert clf.tree_.threshold[0] == 49.5 # Threshold should have moved
1114
+
1115
+ # Test that sample weighting is the same as having duplicates
1116
+ X = iris.data
1117
+ y = iris.target
1118
+
1119
+ duplicates = rng.randint(0, X.shape[0], 100)
1120
+
1121
+ clf = DecisionTreeClassifier(random_state=1)
1122
+ clf.fit(X[duplicates], y[duplicates])
1123
+
1124
+ sample_weight = np.bincount(duplicates, minlength=X.shape[0])
1125
+ clf2 = DecisionTreeClassifier(random_state=1)
1126
+ clf2.fit(X, y, sample_weight=sample_weight)
1127
+
1128
+ internal = clf.tree_.children_left != tree._tree.TREE_LEAF
1129
+ assert_array_almost_equal(
1130
+ clf.tree_.threshold[internal], clf2.tree_.threshold[internal]
1131
+ )
1132
+
1133
+
1134
+ def test_sample_weight_invalid():
1135
+ # Check sample weighting raises errors.
1136
+ X = np.arange(100)[:, np.newaxis]
1137
+ y = np.ones(100)
1138
+ y[:50] = 0.0
1139
+
1140
+ clf = DecisionTreeClassifier(random_state=0)
1141
+
1142
+ sample_weight = np.random.rand(100, 1)
1143
+ with pytest.raises(ValueError):
1144
+ clf.fit(X, y, sample_weight=sample_weight)
1145
+
1146
+ sample_weight = np.array(0)
1147
+ expected_err = r"Singleton.* cannot be considered a valid collection"
1148
+ with pytest.raises(TypeError, match=expected_err):
1149
+ clf.fit(X, y, sample_weight=sample_weight)
1150
+
1151
+
1152
+ def check_class_weights(name):
1153
+ """Check class_weights resemble sample_weights behavior."""
1154
+ TreeClassifier = CLF_TREES[name]
1155
+
1156
+ # Iris is balanced, so no effect expected for using 'balanced' weights
1157
+ clf1 = TreeClassifier(random_state=0)
1158
+ clf1.fit(iris.data, iris.target)
1159
+ clf2 = TreeClassifier(class_weight="balanced", random_state=0)
1160
+ clf2.fit(iris.data, iris.target)
1161
+ assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_)
1162
+
1163
+ # Make a multi-output problem with three copies of Iris
1164
+ iris_multi = np.vstack((iris.target, iris.target, iris.target)).T
1165
+ # Create user-defined weights that should balance over the outputs
1166
+ clf3 = TreeClassifier(
1167
+ class_weight=[
1168
+ {0: 2.0, 1: 2.0, 2: 1.0},
1169
+ {0: 2.0, 1: 1.0, 2: 2.0},
1170
+ {0: 1.0, 1: 2.0, 2: 2.0},
1171
+ ],
1172
+ random_state=0,
1173
+ )
1174
+ clf3.fit(iris.data, iris_multi)
1175
+ assert_almost_equal(clf2.feature_importances_, clf3.feature_importances_)
1176
+ # Check against multi-output "auto" which should also have no effect
1177
+ clf4 = TreeClassifier(class_weight="balanced", random_state=0)
1178
+ clf4.fit(iris.data, iris_multi)
1179
+ assert_almost_equal(clf3.feature_importances_, clf4.feature_importances_)
1180
+
1181
+ # Inflate importance of class 1, check against user-defined weights
1182
+ sample_weight = np.ones(iris.target.shape)
1183
+ sample_weight[iris.target == 1] *= 100
1184
+ class_weight = {0: 1.0, 1: 100.0, 2: 1.0}
1185
+ clf1 = TreeClassifier(random_state=0)
1186
+ clf1.fit(iris.data, iris.target, sample_weight)
1187
+ clf2 = TreeClassifier(class_weight=class_weight, random_state=0)
1188
+ clf2.fit(iris.data, iris.target)
1189
+ assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_)
1190
+
1191
+ # Check that sample_weight and class_weight are multiplicative
1192
+ clf1 = TreeClassifier(random_state=0)
1193
+ clf1.fit(iris.data, iris.target, sample_weight**2)
1194
+ clf2 = TreeClassifier(class_weight=class_weight, random_state=0)
1195
+ clf2.fit(iris.data, iris.target, sample_weight)
1196
+ assert_almost_equal(clf1.feature_importances_, clf2.feature_importances_)
1197
+
1198
+
1199
+ @pytest.mark.parametrize("name", CLF_TREES)
1200
+ def test_class_weights(name):
1201
+ check_class_weights(name)
1202
+
1203
+
1204
+ def check_class_weight_errors(name):
1205
+ # Test if class_weight raises errors and warnings when expected.
1206
+ TreeClassifier = CLF_TREES[name]
1207
+ _y = np.vstack((y, np.array(y) * 2)).T
1208
+
1209
+ # Incorrect length list for multi-output
1210
+ clf = TreeClassifier(class_weight=[{-1: 0.5, 1: 1.0}], random_state=0)
1211
+ err_msg = "number of elements in class_weight should match number of outputs."
1212
+ with pytest.raises(ValueError, match=err_msg):
1213
+ clf.fit(X, _y)
1214
+
1215
+
1216
+ @pytest.mark.parametrize("name", CLF_TREES)
1217
+ def test_class_weight_errors(name):
1218
+ check_class_weight_errors(name)
1219
+
1220
+
1221
+ def test_max_leaf_nodes():
1222
+ # Test greedy trees with max_depth + 1 leafs.
1223
+ X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
1224
+ k = 4
1225
+ for name, TreeEstimator in ALL_TREES.items():
1226
+ est = TreeEstimator(max_depth=None, max_leaf_nodes=k + 1).fit(X, y)
1227
+ assert est.get_n_leaves() == k + 1
1228
+
1229
+
1230
+ def test_max_leaf_nodes_max_depth():
1231
+ # Test precedence of max_leaf_nodes over max_depth.
1232
+ X, y = datasets.make_hastie_10_2(n_samples=100, random_state=1)
1233
+ k = 4
1234
+ for name, TreeEstimator in ALL_TREES.items():
1235
+ est = TreeEstimator(max_depth=1, max_leaf_nodes=k).fit(X, y)
1236
+ assert est.get_depth() == 1
1237
+
1238
+
1239
+ def test_arrays_persist():
1240
+ # Ensure property arrays' memory stays alive when tree disappears
1241
+ # non-regression for #2726
1242
+ for attr in [
1243
+ "n_classes",
1244
+ "value",
1245
+ "children_left",
1246
+ "children_right",
1247
+ "threshold",
1248
+ "impurity",
1249
+ "feature",
1250
+ "n_node_samples",
1251
+ ]:
1252
+ value = getattr(DecisionTreeClassifier().fit([[0], [1]], [0, 1]).tree_, attr)
1253
+ # if pointing to freed memory, contents may be arbitrary
1254
+ assert -3 <= value.flat[0] < 3, "Array points to arbitrary memory"
1255
+
1256
+
1257
+ def test_only_constant_features():
1258
+ random_state = check_random_state(0)
1259
+ X = np.zeros((10, 20))
1260
+ y = random_state.randint(0, 2, (10,))
1261
+ for name, TreeEstimator in ALL_TREES.items():
1262
+ est = TreeEstimator(random_state=0)
1263
+ est.fit(X, y)
1264
+ assert est.tree_.max_depth == 0
1265
+
1266
+
1267
+ def test_behaviour_constant_feature_after_splits():
1268
+ X = np.transpose(
1269
+ np.vstack(([[0, 0, 0, 0, 0, 1, 2, 4, 5, 6, 7]], np.zeros((4, 11))))
1270
+ )
1271
+ y = [0, 0, 0, 1, 1, 2, 2, 2, 3, 3, 3]
1272
+ for name, TreeEstimator in ALL_TREES.items():
1273
+ # do not check extra random trees
1274
+ if "ExtraTree" not in name:
1275
+ est = TreeEstimator(random_state=0, max_features=1)
1276
+ est.fit(X, y)
1277
+ assert est.tree_.max_depth == 2
1278
+ assert est.tree_.node_count == 5
1279
+
1280
+
1281
+ def test_with_only_one_non_constant_features():
1282
+ X = np.hstack([np.array([[1.0], [1.0], [0.0], [0.0]]), np.zeros((4, 1000))])
1283
+
1284
+ y = np.array([0.0, 1.0, 0.0, 1.0])
1285
+ for name, TreeEstimator in CLF_TREES.items():
1286
+ est = TreeEstimator(random_state=0, max_features=1)
1287
+ est.fit(X, y)
1288
+ assert est.tree_.max_depth == 1
1289
+ assert_array_equal(est.predict_proba(X), np.full((4, 2), 0.5))
1290
+
1291
+ for name, TreeEstimator in REG_TREES.items():
1292
+ est = TreeEstimator(random_state=0, max_features=1)
1293
+ est.fit(X, y)
1294
+ assert est.tree_.max_depth == 1
1295
+ assert_array_equal(est.predict(X), np.full((4,), 0.5))
1296
+
1297
+
1298
+ def test_big_input():
1299
+ # Test if the warning for too large inputs is appropriate.
1300
+ X = np.repeat(10**40.0, 4).astype(np.float64).reshape(-1, 1)
1301
+ clf = DecisionTreeClassifier()
1302
+ with pytest.raises(ValueError, match="float32"):
1303
+ clf.fit(X, [0, 1, 0, 1])
1304
+
1305
+
1306
+ def test_realloc():
1307
+ from sklearn.tree._utils import _realloc_test
1308
+
1309
+ with pytest.raises(MemoryError):
1310
+ _realloc_test()
1311
+
1312
+
1313
+ def test_huge_allocations():
1314
+ n_bits = 8 * struct.calcsize("P")
1315
+
1316
+ X = np.random.randn(10, 2)
1317
+ y = np.random.randint(0, 2, 10)
1318
+
1319
+ # Sanity check: we cannot request more memory than the size of the address
1320
+ # space. Currently raises OverflowError.
1321
+ huge = 2 ** (n_bits + 1)
1322
+ clf = DecisionTreeClassifier(splitter="best", max_leaf_nodes=huge)
1323
+ with pytest.raises(Exception):
1324
+ clf.fit(X, y)
1325
+
1326
+ # Non-regression test: MemoryError used to be dropped by Cython
1327
+ # because of missing "except *".
1328
+ huge = 2 ** (n_bits - 1) - 1
1329
+ clf = DecisionTreeClassifier(splitter="best", max_leaf_nodes=huge)
1330
+ with pytest.raises(MemoryError):
1331
+ clf.fit(X, y)
1332
+
1333
+
1334
+ def check_sparse_input(tree, dataset, max_depth=None):
1335
+ TreeEstimator = ALL_TREES[tree]
1336
+ X = DATASETS[dataset]["X"]
1337
+ X_sparse = DATASETS[dataset]["X_sparse"]
1338
+ y = DATASETS[dataset]["y"]
1339
+
1340
+ # Gain testing time
1341
+ if dataset in ["digits", "diabetes"]:
1342
+ n_samples = X.shape[0] // 5
1343
+ X = X[:n_samples]
1344
+ X_sparse = X_sparse[:n_samples]
1345
+ y = y[:n_samples]
1346
+
1347
+ for sparse_format in (csr_matrix, csc_matrix, coo_matrix):
1348
+ X_sparse = sparse_format(X_sparse)
1349
+
1350
+ # Check the default (depth first search)
1351
+ d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y)
1352
+ s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y)
1353
+
1354
+ assert_tree_equal(
1355
+ d.tree_,
1356
+ s.tree_,
1357
+ "{0} with dense and sparse format gave different trees".format(tree),
1358
+ )
1359
+
1360
+ y_pred = d.predict(X)
1361
+ if tree in CLF_TREES:
1362
+ y_proba = d.predict_proba(X)
1363
+ y_log_proba = d.predict_log_proba(X)
1364
+
1365
+ for sparse_matrix in (csr_matrix, csc_matrix, coo_matrix):
1366
+ X_sparse_test = sparse_matrix(X_sparse, dtype=np.float32)
1367
+
1368
+ assert_array_almost_equal(s.predict(X_sparse_test), y_pred)
1369
+
1370
+ if tree in CLF_TREES:
1371
+ assert_array_almost_equal(s.predict_proba(X_sparse_test), y_proba)
1372
+ assert_array_almost_equal(
1373
+ s.predict_log_proba(X_sparse_test), y_log_proba
1374
+ )
1375
+
1376
+
1377
+ @pytest.mark.parametrize("tree_type", SPARSE_TREES)
1378
+ @pytest.mark.parametrize(
1379
+ "dataset",
1380
+ (
1381
+ "clf_small",
1382
+ "toy",
1383
+ "digits",
1384
+ "multilabel",
1385
+ "sparse-pos",
1386
+ "sparse-neg",
1387
+ "sparse-mix",
1388
+ "zeros",
1389
+ ),
1390
+ )
1391
+ def test_sparse_input(tree_type, dataset):
1392
+ max_depth = 3 if dataset == "digits" else None
1393
+ check_sparse_input(tree_type, dataset, max_depth)
1394
+
1395
+
1396
+ @pytest.mark.parametrize("tree_type", sorted(set(SPARSE_TREES).intersection(REG_TREES)))
1397
+ @pytest.mark.parametrize("dataset", ["diabetes", "reg_small"])
1398
+ def test_sparse_input_reg_trees(tree_type, dataset):
1399
+ # Due to numerical instability of MSE and too strict test, we limit the
1400
+ # maximal depth
1401
+ check_sparse_input(tree_type, dataset, 2)
1402
+
1403
+
1404
+ def check_sparse_parameters(tree, dataset):
1405
+ TreeEstimator = ALL_TREES[tree]
1406
+ X = DATASETS[dataset]["X"]
1407
+ X_sparse = DATASETS[dataset]["X_sparse"]
1408
+ y = DATASETS[dataset]["y"]
1409
+
1410
+ # Check max_features
1411
+ d = TreeEstimator(random_state=0, max_features=1, max_depth=2).fit(X, y)
1412
+ s = TreeEstimator(random_state=0, max_features=1, max_depth=2).fit(X_sparse, y)
1413
+ assert_tree_equal(
1414
+ d.tree_,
1415
+ s.tree_,
1416
+ "{0} with dense and sparse format gave different trees".format(tree),
1417
+ )
1418
+ assert_array_almost_equal(s.predict(X), d.predict(X))
1419
+
1420
+ # Check min_samples_split
1421
+ d = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).fit(X, y)
1422
+ s = TreeEstimator(random_state=0, max_features=1, min_samples_split=10).fit(
1423
+ X_sparse, y
1424
+ )
1425
+ assert_tree_equal(
1426
+ d.tree_,
1427
+ s.tree_,
1428
+ "{0} with dense and sparse format gave different trees".format(tree),
1429
+ )
1430
+ assert_array_almost_equal(s.predict(X), d.predict(X))
1431
+
1432
+ # Check min_samples_leaf
1433
+ d = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).fit(X, y)
1434
+ s = TreeEstimator(random_state=0, min_samples_leaf=X_sparse.shape[0] // 2).fit(
1435
+ X_sparse, y
1436
+ )
1437
+ assert_tree_equal(
1438
+ d.tree_,
1439
+ s.tree_,
1440
+ "{0} with dense and sparse format gave different trees".format(tree),
1441
+ )
1442
+ assert_array_almost_equal(s.predict(X), d.predict(X))
1443
+
1444
+ # Check best-first search
1445
+ d = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X, y)
1446
+ s = TreeEstimator(random_state=0, max_leaf_nodes=3).fit(X_sparse, y)
1447
+ assert_tree_equal(
1448
+ d.tree_,
1449
+ s.tree_,
1450
+ "{0} with dense and sparse format gave different trees".format(tree),
1451
+ )
1452
+ assert_array_almost_equal(s.predict(X), d.predict(X))
1453
+
1454
+
1455
+ def check_sparse_criterion(tree, dataset):
1456
+ TreeEstimator = ALL_TREES[tree]
1457
+ X = DATASETS[dataset]["X"]
1458
+ X_sparse = DATASETS[dataset]["X_sparse"]
1459
+ y = DATASETS[dataset]["y"]
1460
+
1461
+ # Check various criterion
1462
+ CRITERIONS = REG_CRITERIONS if tree in REG_TREES else CLF_CRITERIONS
1463
+ for criterion in CRITERIONS:
1464
+ d = TreeEstimator(random_state=0, max_depth=3, criterion=criterion).fit(X, y)
1465
+ s = TreeEstimator(random_state=0, max_depth=3, criterion=criterion).fit(
1466
+ X_sparse, y
1467
+ )
1468
+
1469
+ assert_tree_equal(
1470
+ d.tree_,
1471
+ s.tree_,
1472
+ "{0} with dense and sparse format gave different trees".format(tree),
1473
+ )
1474
+ assert_array_almost_equal(s.predict(X), d.predict(X))
1475
+
1476
+
1477
+ @pytest.mark.parametrize("tree_type", SPARSE_TREES)
1478
+ @pytest.mark.parametrize("dataset", ["sparse-pos", "sparse-neg", "sparse-mix", "zeros"])
1479
+ @pytest.mark.parametrize("check", [check_sparse_parameters, check_sparse_criterion])
1480
+ def test_sparse(tree_type, dataset, check):
1481
+ check(tree_type, dataset)
1482
+
1483
+
1484
+ def check_explicit_sparse_zeros(tree, max_depth=3, n_features=10):
1485
+ TreeEstimator = ALL_TREES[tree]
1486
+
1487
+ # n_samples set n_feature to ease construction of a simultaneous
1488
+ # construction of a csr and csc matrix
1489
+ n_samples = n_features
1490
+ samples = np.arange(n_samples)
1491
+
1492
+ # Generate X, y
1493
+ random_state = check_random_state(0)
1494
+ indices = []
1495
+ data = []
1496
+ offset = 0
1497
+ indptr = [offset]
1498
+ for i in range(n_features):
1499
+ n_nonzero_i = random_state.binomial(n_samples, 0.5)
1500
+ indices_i = random_state.permutation(samples)[:n_nonzero_i]
1501
+ indices.append(indices_i)
1502
+ data_i = random_state.binomial(3, 0.5, size=(n_nonzero_i,)) - 1
1503
+ data.append(data_i)
1504
+ offset += n_nonzero_i
1505
+ indptr.append(offset)
1506
+
1507
+ indices = np.concatenate(indices)
1508
+ data = np.array(np.concatenate(data), dtype=np.float32)
1509
+ X_sparse = csc_matrix((data, indices, indptr), shape=(n_samples, n_features))
1510
+ X = X_sparse.toarray()
1511
+ X_sparse_test = csr_matrix((data, indices, indptr), shape=(n_samples, n_features))
1512
+ X_test = X_sparse_test.toarray()
1513
+ y = random_state.randint(0, 3, size=(n_samples,))
1514
+
1515
+ # Ensure that X_sparse_test owns its data, indices and indptr array
1516
+ X_sparse_test = X_sparse_test.copy()
1517
+
1518
+ # Ensure that we have explicit zeros
1519
+ assert (X_sparse.data == 0.0).sum() > 0
1520
+ assert (X_sparse_test.data == 0.0).sum() > 0
1521
+
1522
+ # Perform the comparison
1523
+ d = TreeEstimator(random_state=0, max_depth=max_depth).fit(X, y)
1524
+ s = TreeEstimator(random_state=0, max_depth=max_depth).fit(X_sparse, y)
1525
+
1526
+ assert_tree_equal(
1527
+ d.tree_,
1528
+ s.tree_,
1529
+ "{0} with dense and sparse format gave different trees".format(tree),
1530
+ )
1531
+
1532
+ Xs = (X_test, X_sparse_test)
1533
+ for X1, X2 in product(Xs, Xs):
1534
+ assert_array_almost_equal(s.tree_.apply(X1), d.tree_.apply(X2))
1535
+ assert_array_almost_equal(s.apply(X1), d.apply(X2))
1536
+ assert_array_almost_equal(s.apply(X1), s.tree_.apply(X1))
1537
+
1538
+ assert_array_almost_equal(
1539
+ s.tree_.decision_path(X1).toarray(), d.tree_.decision_path(X2).toarray()
1540
+ )
1541
+ assert_array_almost_equal(
1542
+ s.decision_path(X1).toarray(), d.decision_path(X2).toarray()
1543
+ )
1544
+ assert_array_almost_equal(
1545
+ s.decision_path(X1).toarray(), s.tree_.decision_path(X1).toarray()
1546
+ )
1547
+
1548
+ assert_array_almost_equal(s.predict(X1), d.predict(X2))
1549
+
1550
+ if tree in CLF_TREES:
1551
+ assert_array_almost_equal(s.predict_proba(X1), d.predict_proba(X2))
1552
+
1553
+
1554
+ @pytest.mark.parametrize("tree_type", SPARSE_TREES)
1555
+ def test_explicit_sparse_zeros(tree_type):
1556
+ check_explicit_sparse_zeros(tree_type)
1557
+
1558
+
1559
+ @ignore_warnings
1560
+ def check_raise_error_on_1d_input(name):
1561
+ TreeEstimator = ALL_TREES[name]
1562
+
1563
+ X = iris.data[:, 0].ravel()
1564
+ X_2d = iris.data[:, 0].reshape((-1, 1))
1565
+ y = iris.target
1566
+
1567
+ with pytest.raises(ValueError):
1568
+ TreeEstimator(random_state=0).fit(X, y)
1569
+
1570
+ est = TreeEstimator(random_state=0)
1571
+ est.fit(X_2d, y)
1572
+ with pytest.raises(ValueError):
1573
+ est.predict([X])
1574
+
1575
+
1576
+ @pytest.mark.parametrize("name", ALL_TREES)
1577
+ def test_1d_input(name):
1578
+ with ignore_warnings():
1579
+ check_raise_error_on_1d_input(name)
1580
+
1581
+
1582
+ def _check_min_weight_leaf_split_level(TreeEstimator, X, y, sample_weight):
1583
+ est = TreeEstimator(random_state=0)
1584
+ est.fit(X, y, sample_weight=sample_weight)
1585
+ assert est.tree_.max_depth == 1
1586
+
1587
+ est = TreeEstimator(random_state=0, min_weight_fraction_leaf=0.4)
1588
+ est.fit(X, y, sample_weight=sample_weight)
1589
+ assert est.tree_.max_depth == 0
1590
+
1591
+
1592
+ def check_min_weight_leaf_split_level(name):
1593
+ TreeEstimator = ALL_TREES[name]
1594
+
1595
+ X = np.array([[0], [0], [0], [0], [1]])
1596
+ y = [0, 0, 0, 0, 1]
1597
+ sample_weight = [0.2, 0.2, 0.2, 0.2, 0.2]
1598
+ _check_min_weight_leaf_split_level(TreeEstimator, X, y, sample_weight)
1599
+
1600
+ _check_min_weight_leaf_split_level(TreeEstimator, csc_matrix(X), y, sample_weight)
1601
+
1602
+
1603
+ @pytest.mark.parametrize("name", ALL_TREES)
1604
+ def test_min_weight_leaf_split_level(name):
1605
+ check_min_weight_leaf_split_level(name)
1606
+
1607
+
1608
+ def check_public_apply(name):
1609
+ X_small32 = X_small.astype(tree._tree.DTYPE, copy=False)
1610
+
1611
+ est = ALL_TREES[name]()
1612
+ est.fit(X_small, y_small)
1613
+ assert_array_equal(est.apply(X_small), est.tree_.apply(X_small32))
1614
+
1615
+
1616
+ def check_public_apply_sparse(name):
1617
+ X_small32 = csr_matrix(X_small.astype(tree._tree.DTYPE, copy=False))
1618
+
1619
+ est = ALL_TREES[name]()
1620
+ est.fit(X_small, y_small)
1621
+ assert_array_equal(est.apply(X_small), est.tree_.apply(X_small32))
1622
+
1623
+
1624
+ @pytest.mark.parametrize("name", ALL_TREES)
1625
+ def test_public_apply_all_trees(name):
1626
+ check_public_apply(name)
1627
+
1628
+
1629
+ @pytest.mark.parametrize("name", SPARSE_TREES)
1630
+ def test_public_apply_sparse_trees(name):
1631
+ check_public_apply_sparse(name)
1632
+
1633
+
1634
+ def test_decision_path_hardcoded():
1635
+ X = iris.data
1636
+ y = iris.target
1637
+ est = DecisionTreeClassifier(random_state=0, max_depth=1).fit(X, y)
1638
+ node_indicator = est.decision_path(X[:2]).toarray()
1639
+ assert_array_equal(node_indicator, [[1, 1, 0], [1, 0, 1]])
1640
+
1641
+
1642
+ def check_decision_path(name):
1643
+ X = iris.data
1644
+ y = iris.target
1645
+ n_samples = X.shape[0]
1646
+
1647
+ TreeEstimator = ALL_TREES[name]
1648
+ est = TreeEstimator(random_state=0, max_depth=2)
1649
+ est.fit(X, y)
1650
+
1651
+ node_indicator_csr = est.decision_path(X)
1652
+ node_indicator = node_indicator_csr.toarray()
1653
+ assert node_indicator.shape == (n_samples, est.tree_.node_count)
1654
+
1655
+ # Assert that leaves index are correct
1656
+ leaves = est.apply(X)
1657
+ leave_indicator = [node_indicator[i, j] for i, j in enumerate(leaves)]
1658
+ assert_array_almost_equal(leave_indicator, np.ones(shape=n_samples))
1659
+
1660
+ # Ensure only one leave node per sample
1661
+ all_leaves = est.tree_.children_left == TREE_LEAF
1662
+ assert_array_almost_equal(
1663
+ np.dot(node_indicator, all_leaves), np.ones(shape=n_samples)
1664
+ )
1665
+
1666
+ # Ensure max depth is consistent with sum of indicator
1667
+ max_depth = node_indicator.sum(axis=1).max()
1668
+ assert est.tree_.max_depth <= max_depth
1669
+
1670
+
1671
+ @pytest.mark.parametrize("name", ALL_TREES)
1672
+ def test_decision_path(name):
1673
+ check_decision_path(name)
1674
+
1675
+
1676
+ def check_no_sparse_y_support(name):
1677
+ X, y = X_multilabel, csr_matrix(y_multilabel)
1678
+ TreeEstimator = ALL_TREES[name]
1679
+ with pytest.raises(TypeError):
1680
+ TreeEstimator(random_state=0).fit(X, y)
1681
+
1682
+
1683
+ @pytest.mark.parametrize("name", ALL_TREES)
1684
+ def test_no_sparse_y_support(name):
1685
+ # Currently we don't support sparse y
1686
+ check_no_sparse_y_support(name)
1687
+
1688
+
1689
+ def test_mae():
1690
+ """Check MAE criterion produces correct results on small toy dataset:
1691
+
1692
+ ------------------
1693
+ | X | y | weight |
1694
+ ------------------
1695
+ | 3 | 3 | 0.1 |
1696
+ | 5 | 3 | 0.3 |
1697
+ | 8 | 4 | 1.0 |
1698
+ | 3 | 6 | 0.6 |
1699
+ | 5 | 7 | 0.3 |
1700
+ ------------------
1701
+ |sum wt:| 2.3 |
1702
+ ------------------
1703
+
1704
+ Because we are dealing with sample weights, we cannot find the median by
1705
+ simply choosing/averaging the centre value(s), instead we consider the
1706
+ median where 50% of the cumulative weight is found (in a y sorted data set)
1707
+ . Therefore with regards to this test data, the cumulative weight is >= 50%
1708
+ when y = 4. Therefore:
1709
+ Median = 4
1710
+
1711
+ For all the samples, we can get the total error by summing:
1712
+ Absolute(Median - y) * weight
1713
+
1714
+ I.e., total error = (Absolute(4 - 3) * 0.1)
1715
+ + (Absolute(4 - 3) * 0.3)
1716
+ + (Absolute(4 - 4) * 1.0)
1717
+ + (Absolute(4 - 6) * 0.6)
1718
+ + (Absolute(4 - 7) * 0.3)
1719
+ = 2.5
1720
+
1721
+ Impurity = Total error / total weight
1722
+ = 2.5 / 2.3
1723
+ = 1.08695652173913
1724
+ ------------------
1725
+
1726
+ From this root node, the next best split is between X values of 3 and 5.
1727
+ Thus, we have left and right child nodes:
1728
+
1729
+ LEFT RIGHT
1730
+ ------------------ ------------------
1731
+ | X | y | weight | | X | y | weight |
1732
+ ------------------ ------------------
1733
+ | 3 | 3 | 0.1 | | 5 | 3 | 0.3 |
1734
+ | 3 | 6 | 0.6 | | 8 | 4 | 1.0 |
1735
+ ------------------ | 5 | 7 | 0.3 |
1736
+ |sum wt:| 0.7 | ------------------
1737
+ ------------------ |sum wt:| 1.6 |
1738
+ ------------------
1739
+
1740
+ Impurity is found in the same way:
1741
+ Left node Median = 6
1742
+ Total error = (Absolute(6 - 3) * 0.1)
1743
+ + (Absolute(6 - 6) * 0.6)
1744
+ = 0.3
1745
+
1746
+ Left Impurity = Total error / total weight
1747
+ = 0.3 / 0.7
1748
+ = 0.428571428571429
1749
+ -------------------
1750
+
1751
+ Likewise for Right node:
1752
+ Right node Median = 4
1753
+ Total error = (Absolute(4 - 3) * 0.3)
1754
+ + (Absolute(4 - 4) * 1.0)
1755
+ + (Absolute(4 - 7) * 0.3)
1756
+ = 1.2
1757
+
1758
+ Right Impurity = Total error / total weight
1759
+ = 1.2 / 1.6
1760
+ = 0.75
1761
+ ------
1762
+ """
1763
+ dt_mae = DecisionTreeRegressor(
1764
+ random_state=0, criterion="absolute_error", max_leaf_nodes=2
1765
+ )
1766
+
1767
+ # Test MAE where sample weights are non-uniform (as illustrated above):
1768
+ dt_mae.fit(
1769
+ X=[[3], [5], [3], [8], [5]],
1770
+ y=[6, 7, 3, 4, 3],
1771
+ sample_weight=[0.6, 0.3, 0.1, 1.0, 0.3],
1772
+ )
1773
+ assert_allclose(dt_mae.tree_.impurity, [2.5 / 2.3, 0.3 / 0.7, 1.2 / 1.6])
1774
+ assert_array_equal(dt_mae.tree_.value.flat, [4.0, 6.0, 4.0])
1775
+
1776
+ # Test MAE where all sample weights are uniform:
1777
+ dt_mae.fit(X=[[3], [5], [3], [8], [5]], y=[6, 7, 3, 4, 3], sample_weight=np.ones(5))
1778
+ assert_array_equal(dt_mae.tree_.impurity, [1.4, 1.5, 4.0 / 3.0])
1779
+ assert_array_equal(dt_mae.tree_.value.flat, [4, 4.5, 4.0])
1780
+
1781
+ # Test MAE where a `sample_weight` is not explicitly provided.
1782
+ # This is equivalent to providing uniform sample weights, though
1783
+ # the internal logic is different:
1784
+ dt_mae.fit(X=[[3], [5], [3], [8], [5]], y=[6, 7, 3, 4, 3])
1785
+ assert_array_equal(dt_mae.tree_.impurity, [1.4, 1.5, 4.0 / 3.0])
1786
+ assert_array_equal(dt_mae.tree_.value.flat, [4, 4.5, 4.0])
1787
+
1788
+
1789
+ def test_criterion_copy():
1790
+ # Let's check whether copy of our criterion has the same type
1791
+ # and properties as original
1792
+ n_outputs = 3
1793
+ n_classes = np.arange(3, dtype=np.intp)
1794
+ n_samples = 100
1795
+
1796
+ def _pickle_copy(obj):
1797
+ return pickle.loads(pickle.dumps(obj))
1798
+
1799
+ for copy_func in [copy.copy, copy.deepcopy, _pickle_copy]:
1800
+ for _, typename in CRITERIA_CLF.items():
1801
+ criteria = typename(n_outputs, n_classes)
1802
+ result = copy_func(criteria).__reduce__()
1803
+ typename_, (n_outputs_, n_classes_), _ = result
1804
+ assert typename == typename_
1805
+ assert n_outputs == n_outputs_
1806
+ assert_array_equal(n_classes, n_classes_)
1807
+
1808
+ for _, typename in CRITERIA_REG.items():
1809
+ criteria = typename(n_outputs, n_samples)
1810
+ result = copy_func(criteria).__reduce__()
1811
+ typename_, (n_outputs_, n_samples_), _ = result
1812
+ assert typename == typename_
1813
+ assert n_outputs == n_outputs_
1814
+ assert n_samples == n_samples_
1815
+
1816
+
1817
+ def test_empty_leaf_infinite_threshold():
1818
+ # try to make empty leaf by using near infinite value.
1819
+ data = np.random.RandomState(0).randn(100, 11) * 2e38
1820
+ data = np.nan_to_num(data.astype("float32"))
1821
+ X_full = data[:, :-1]
1822
+ X_sparse = csc_matrix(X_full)
1823
+ y = data[:, -1]
1824
+ for X in [X_full, X_sparse]:
1825
+ tree = DecisionTreeRegressor(random_state=0).fit(X, y)
1826
+ terminal_regions = tree.apply(X)
1827
+ left_leaf = set(np.where(tree.tree_.children_left == TREE_LEAF)[0])
1828
+ empty_leaf = left_leaf.difference(terminal_regions)
1829
+ infinite_threshold = np.where(~np.isfinite(tree.tree_.threshold))[0]
1830
+ assert len(infinite_threshold) == 0
1831
+ assert len(empty_leaf) == 0
1832
+
1833
+
1834
+ @pytest.mark.parametrize("criterion", CLF_CRITERIONS)
1835
+ @pytest.mark.parametrize(
1836
+ "dataset", sorted(set(DATASETS.keys()) - {"reg_small", "diabetes"})
1837
+ )
1838
+ @pytest.mark.parametrize("tree_cls", [DecisionTreeClassifier, ExtraTreeClassifier])
1839
+ def test_prune_tree_classifier_are_subtrees(criterion, dataset, tree_cls):
1840
+ dataset = DATASETS[dataset]
1841
+ X, y = dataset["X"], dataset["y"]
1842
+ est = tree_cls(max_leaf_nodes=20, random_state=0)
1843
+ info = est.cost_complexity_pruning_path(X, y)
1844
+
1845
+ pruning_path = info.ccp_alphas
1846
+ impurities = info.impurities
1847
+ assert np.all(np.diff(pruning_path) >= 0)
1848
+ assert np.all(np.diff(impurities) >= 0)
1849
+
1850
+ assert_pruning_creates_subtree(tree_cls, X, y, pruning_path)
1851
+
1852
+
1853
+ @pytest.mark.parametrize("criterion", REG_CRITERIONS)
1854
+ @pytest.mark.parametrize("dataset", DATASETS.keys())
1855
+ @pytest.mark.parametrize("tree_cls", [DecisionTreeRegressor, ExtraTreeRegressor])
1856
+ def test_prune_tree_regression_are_subtrees(criterion, dataset, tree_cls):
1857
+ dataset = DATASETS[dataset]
1858
+ X, y = dataset["X"], dataset["y"]
1859
+
1860
+ est = tree_cls(max_leaf_nodes=20, random_state=0)
1861
+ info = est.cost_complexity_pruning_path(X, y)
1862
+
1863
+ pruning_path = info.ccp_alphas
1864
+ impurities = info.impurities
1865
+ assert np.all(np.diff(pruning_path) >= 0)
1866
+ assert np.all(np.diff(impurities) >= 0)
1867
+
1868
+ assert_pruning_creates_subtree(tree_cls, X, y, pruning_path)
1869
+
1870
+
1871
+ def test_prune_single_node_tree():
1872
+ # single node tree
1873
+ clf1 = DecisionTreeClassifier(random_state=0)
1874
+ clf1.fit([[0], [1]], [0, 0])
1875
+
1876
+ # pruned single node tree
1877
+ clf2 = DecisionTreeClassifier(random_state=0, ccp_alpha=10)
1878
+ clf2.fit([[0], [1]], [0, 0])
1879
+
1880
+ assert_is_subtree(clf1.tree_, clf2.tree_)
1881
+
1882
+
1883
+ def assert_pruning_creates_subtree(estimator_cls, X, y, pruning_path):
1884
+ # generate trees with increasing alphas
1885
+ estimators = []
1886
+ for ccp_alpha in pruning_path:
1887
+ est = estimator_cls(max_leaf_nodes=20, ccp_alpha=ccp_alpha, random_state=0).fit(
1888
+ X, y
1889
+ )
1890
+ estimators.append(est)
1891
+
1892
+ # A pruned tree must be a subtree of the previous tree (which had a
1893
+ # smaller ccp_alpha)
1894
+ for prev_est, next_est in zip(estimators, estimators[1:]):
1895
+ assert_is_subtree(prev_est.tree_, next_est.tree_)
1896
+
1897
+
1898
+ def assert_is_subtree(tree, subtree):
1899
+ assert tree.node_count >= subtree.node_count
1900
+ assert tree.max_depth >= subtree.max_depth
1901
+
1902
+ tree_c_left = tree.children_left
1903
+ tree_c_right = tree.children_right
1904
+ subtree_c_left = subtree.children_left
1905
+ subtree_c_right = subtree.children_right
1906
+
1907
+ stack = [(0, 0)]
1908
+ while stack:
1909
+ tree_node_idx, subtree_node_idx = stack.pop()
1910
+ assert_array_almost_equal(
1911
+ tree.value[tree_node_idx], subtree.value[subtree_node_idx]
1912
+ )
1913
+ assert_almost_equal(
1914
+ tree.impurity[tree_node_idx], subtree.impurity[subtree_node_idx]
1915
+ )
1916
+ assert_almost_equal(
1917
+ tree.n_node_samples[tree_node_idx], subtree.n_node_samples[subtree_node_idx]
1918
+ )
1919
+ assert_almost_equal(
1920
+ tree.weighted_n_node_samples[tree_node_idx],
1921
+ subtree.weighted_n_node_samples[subtree_node_idx],
1922
+ )
1923
+
1924
+ if subtree_c_left[subtree_node_idx] == subtree_c_right[subtree_node_idx]:
1925
+ # is a leaf
1926
+ assert_almost_equal(TREE_UNDEFINED, subtree.threshold[subtree_node_idx])
1927
+ else:
1928
+ # not a leaf
1929
+ assert_almost_equal(
1930
+ tree.threshold[tree_node_idx], subtree.threshold[subtree_node_idx]
1931
+ )
1932
+ stack.append((tree_c_left[tree_node_idx], subtree_c_left[subtree_node_idx]))
1933
+ stack.append(
1934
+ (tree_c_right[tree_node_idx], subtree_c_right[subtree_node_idx])
1935
+ )
1936
+
1937
+
1938
+ @pytest.mark.parametrize("name", ALL_TREES)
1939
+ @pytest.mark.parametrize("splitter", ["best", "random"])
1940
+ @pytest.mark.parametrize("X_format", ["dense", "csr", "csc"])
1941
+ def test_apply_path_readonly_all_trees(name, splitter, X_format):
1942
+ dataset = DATASETS["clf_small"]
1943
+ X_small = dataset["X"].astype(tree._tree.DTYPE, copy=False)
1944
+ if X_format == "dense":
1945
+ X_readonly = create_memmap_backed_data(X_small)
1946
+ else:
1947
+ X_readonly = dataset["X_sparse"] # CSR
1948
+ if X_format == "csc":
1949
+ # Cheap CSR to CSC conversion
1950
+ X_readonly = X_readonly.tocsc()
1951
+
1952
+ X_readonly.data = np.array(X_readonly.data, dtype=tree._tree.DTYPE)
1953
+ (
1954
+ X_readonly.data,
1955
+ X_readonly.indices,
1956
+ X_readonly.indptr,
1957
+ ) = create_memmap_backed_data(
1958
+ (X_readonly.data, X_readonly.indices, X_readonly.indptr)
1959
+ )
1960
+
1961
+ y_readonly = create_memmap_backed_data(np.array(y_small, dtype=tree._tree.DTYPE))
1962
+ est = ALL_TREES[name](splitter=splitter)
1963
+ est.fit(X_readonly, y_readonly)
1964
+ assert_array_equal(est.predict(X_readonly), est.predict(X_small))
1965
+ assert_array_equal(
1966
+ est.decision_path(X_readonly).todense(), est.decision_path(X_small).todense()
1967
+ )
1968
+
1969
+
1970
+ @pytest.mark.parametrize("criterion", ["squared_error", "friedman_mse", "poisson"])
1971
+ @pytest.mark.parametrize("Tree", REG_TREES.values())
1972
+ def test_balance_property(criterion, Tree):
1973
+ # Test that sum(y_pred)=sum(y_true) on training set.
1974
+ # This works if the mean is predicted (should even be true for each leaf).
1975
+ # MAE predicts the median and is therefore excluded from this test.
1976
+
1977
+ # Choose a training set with non-negative targets (for poisson)
1978
+ X, y = diabetes.data, diabetes.target
1979
+ reg = Tree(criterion=criterion)
1980
+ reg.fit(X, y)
1981
+ assert np.sum(reg.predict(X)) == pytest.approx(np.sum(y))
1982
+
1983
+
1984
+ @pytest.mark.parametrize("seed", range(3))
1985
+ def test_poisson_zero_nodes(seed):
1986
+ # Test that sum(y)=0 and therefore y_pred=0 is forbidden on nodes.
1987
+ X = [[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 2], [1, 2], [1, 3]]
1988
+ y = [0, 0, 0, 0, 1, 2, 3, 4]
1989
+ # Note that X[:, 0] == 0 is a 100% indicator for y == 0. The tree can
1990
+ # easily learn that:
1991
+ reg = DecisionTreeRegressor(criterion="squared_error", random_state=seed)
1992
+ reg.fit(X, y)
1993
+ assert np.amin(reg.predict(X)) == 0
1994
+ # whereas Poisson must predict strictly positive numbers
1995
+ reg = DecisionTreeRegressor(criterion="poisson", random_state=seed)
1996
+ reg.fit(X, y)
1997
+ assert np.all(reg.predict(X) > 0)
1998
+
1999
+ # Test additional dataset where something could go wrong.
2000
+ n_features = 10
2001
+ X, y = datasets.make_regression(
2002
+ effective_rank=n_features * 2 // 3,
2003
+ tail_strength=0.6,
2004
+ n_samples=1_000,
2005
+ n_features=n_features,
2006
+ n_informative=n_features * 2 // 3,
2007
+ random_state=seed,
2008
+ )
2009
+ # some excess zeros
2010
+ y[(-1 < y) & (y < 0)] = 0
2011
+ # make sure the target is positive
2012
+ y = np.abs(y)
2013
+ reg = DecisionTreeRegressor(criterion="poisson", random_state=seed)
2014
+ reg.fit(X, y)
2015
+ assert np.all(reg.predict(X) > 0)
2016
+
2017
+
2018
+ def test_poisson_vs_mse():
2019
+ # For a Poisson distributed target, Poisson loss should give better results
2020
+ # than squared error measured in Poisson deviance as metric.
2021
+ # We have a similar test, test_poisson(), in
2022
+ # sklearn/ensemble/_hist_gradient_boosting/tests/test_gradient_boosting.py
2023
+ rng = np.random.RandomState(42)
2024
+ n_train, n_test, n_features = 500, 500, 10
2025
+ X = datasets.make_low_rank_matrix(
2026
+ n_samples=n_train + n_test, n_features=n_features, random_state=rng
2027
+ )
2028
+ # We create a log-linear Poisson model and downscale coef as it will get
2029
+ # exponentiated.
2030
+ coef = rng.uniform(low=-2, high=2, size=n_features) / np.max(X, axis=0)
2031
+ y = rng.poisson(lam=np.exp(X @ coef))
2032
+ X_train, X_test, y_train, y_test = train_test_split(
2033
+ X, y, test_size=n_test, random_state=rng
2034
+ )
2035
+ # We prevent some overfitting by setting min_samples_split=10.
2036
+ tree_poi = DecisionTreeRegressor(
2037
+ criterion="poisson", min_samples_split=10, random_state=rng
2038
+ )
2039
+ tree_mse = DecisionTreeRegressor(
2040
+ criterion="squared_error", min_samples_split=10, random_state=rng
2041
+ )
2042
+
2043
+ tree_poi.fit(X_train, y_train)
2044
+ tree_mse.fit(X_train, y_train)
2045
+ dummy = DummyRegressor(strategy="mean").fit(X_train, y_train)
2046
+
2047
+ for X, y, val in [(X_train, y_train, "train"), (X_test, y_test, "test")]:
2048
+ metric_poi = mean_poisson_deviance(y, tree_poi.predict(X))
2049
+ # squared_error might produce non-positive predictions => clip
2050
+ metric_mse = mean_poisson_deviance(y, np.clip(tree_mse.predict(X), 1e-15, None))
2051
+ metric_dummy = mean_poisson_deviance(y, dummy.predict(X))
2052
+ # As squared_error might correctly predict 0 in train set, its train
2053
+ # score can be better than Poisson. This is no longer the case for the
2054
+ # test set.
2055
+ if val == "test":
2056
+ assert metric_poi < 0.5 * metric_mse
2057
+ assert metric_poi < 0.75 * metric_dummy
2058
+
2059
+
2060
+ @pytest.mark.parametrize("criterion", REG_CRITERIONS)
2061
+ def test_decision_tree_regressor_sample_weight_consistency(criterion):
2062
+ """Test that the impact of sample_weight is consistent."""
2063
+ tree_params = dict(criterion=criterion)
2064
+ tree = DecisionTreeRegressor(**tree_params, random_state=42)
2065
+ for kind in ["zeros", "ones"]:
2066
+ check_sample_weights_invariance(
2067
+ "DecisionTreeRegressor_" + criterion, tree, kind="zeros"
2068
+ )
2069
+
2070
+ rng = np.random.RandomState(0)
2071
+ n_samples, n_features = 10, 5
2072
+
2073
+ X = rng.rand(n_samples, n_features)
2074
+ y = np.mean(X, axis=1) + rng.rand(n_samples)
2075
+ # make it positive in order to work also for poisson criterion
2076
+ y += np.min(y) + 0.1
2077
+
2078
+ # check that multiplying sample_weight by 2 is equivalent
2079
+ # to repeating corresponding samples twice
2080
+ X2 = np.concatenate([X, X[: n_samples // 2]], axis=0)
2081
+ y2 = np.concatenate([y, y[: n_samples // 2]])
2082
+ sample_weight_1 = np.ones(len(y))
2083
+ sample_weight_1[: n_samples // 2] = 2
2084
+
2085
+ tree1 = DecisionTreeRegressor(**tree_params).fit(
2086
+ X, y, sample_weight=sample_weight_1
2087
+ )
2088
+
2089
+ tree2 = DecisionTreeRegressor(**tree_params).fit(X2, y2, sample_weight=None)
2090
+
2091
+ assert tree1.tree_.node_count == tree2.tree_.node_count
2092
+ # Thresholds, tree.tree_.threshold, and values, tree.tree_.value, are not
2093
+ # exactly the same, but on the training set, those differences do not
2094
+ # matter and thus predictions are the same.
2095
+ assert_allclose(tree1.predict(X), tree2.predict(X))
2096
+
2097
+
2098
+ @pytest.mark.parametrize("Tree", [DecisionTreeClassifier, ExtraTreeClassifier])
2099
+ @pytest.mark.parametrize("n_classes", [2, 4])
2100
+ def test_criterion_entropy_same_as_log_loss(Tree, n_classes):
2101
+ """Test that criterion=entropy gives same as log_loss."""
2102
+ n_samples, n_features = 50, 5
2103
+ X, y = datasets.make_classification(
2104
+ n_classes=n_classes,
2105
+ n_samples=n_samples,
2106
+ n_features=n_features,
2107
+ n_informative=n_features,
2108
+ n_redundant=0,
2109
+ random_state=42,
2110
+ )
2111
+ tree_log_loss = Tree(criterion="log_loss", random_state=43).fit(X, y)
2112
+ tree_entropy = Tree(criterion="entropy", random_state=43).fit(X, y)
2113
+
2114
+ assert_tree_equal(
2115
+ tree_log_loss.tree_,
2116
+ tree_entropy.tree_,
2117
+ f"{Tree!r} with criterion 'entropy' and 'log_loss' gave different trees.",
2118
+ )
2119
+ assert_allclose(tree_log_loss.predict(X), tree_entropy.predict(X))
2120
+
2121
+
2122
+ def test_different_endianness_pickle():
2123
+ X, y = datasets.make_classification(random_state=0)
2124
+
2125
+ clf = DecisionTreeClassifier(random_state=0, max_depth=3)
2126
+ clf.fit(X, y)
2127
+ score = clf.score(X, y)
2128
+
2129
+ def reduce_ndarray(arr):
2130
+ return arr.byteswap().newbyteorder().__reduce__()
2131
+
2132
+ def get_pickle_non_native_endianness():
2133
+ f = io.BytesIO()
2134
+ p = pickle.Pickler(f)
2135
+ p.dispatch_table = copyreg.dispatch_table.copy()
2136
+ p.dispatch_table[np.ndarray] = reduce_ndarray
2137
+
2138
+ p.dump(clf)
2139
+ f.seek(0)
2140
+ return f
2141
+
2142
+ new_clf = pickle.load(get_pickle_non_native_endianness())
2143
+ new_score = new_clf.score(X, y)
2144
+ assert np.isclose(score, new_score)
2145
+
2146
+
2147
+ def test_different_endianness_joblib_pickle():
2148
+ X, y = datasets.make_classification(random_state=0)
2149
+
2150
+ clf = DecisionTreeClassifier(random_state=0, max_depth=3)
2151
+ clf.fit(X, y)
2152
+ score = clf.score(X, y)
2153
+
2154
+ class NonNativeEndiannessNumpyPickler(NumpyPickler):
2155
+ def save(self, obj):
2156
+ if isinstance(obj, np.ndarray):
2157
+ obj = obj.byteswap().newbyteorder()
2158
+ super().save(obj)
2159
+
2160
+ def get_joblib_pickle_non_native_endianness():
2161
+ f = io.BytesIO()
2162
+ p = NonNativeEndiannessNumpyPickler(f)
2163
+
2164
+ p.dump(clf)
2165
+ f.seek(0)
2166
+ return f
2167
+
2168
+ new_clf = joblib.load(get_joblib_pickle_non_native_endianness())
2169
+ new_score = new_clf.score(X, y)
2170
+ assert np.isclose(score, new_score)
2171
+
2172
+
2173
+ def get_different_bitness_node_ndarray(node_ndarray):
2174
+ new_dtype_for_indexing_fields = np.int64 if _IS_32BIT else np.int32
2175
+
2176
+ # field names in Node struct with SIZE_t types (see sklearn/tree/_tree.pxd)
2177
+ indexing_field_names = ["left_child", "right_child", "feature", "n_node_samples"]
2178
+
2179
+ new_dtype_dict = {
2180
+ name: dtype for name, (dtype, _) in node_ndarray.dtype.fields.items()
2181
+ }
2182
+ for name in indexing_field_names:
2183
+ new_dtype_dict[name] = new_dtype_for_indexing_fields
2184
+
2185
+ new_dtype = np.dtype(
2186
+ {"names": list(new_dtype_dict.keys()), "formats": list(new_dtype_dict.values())}
2187
+ )
2188
+ return node_ndarray.astype(new_dtype, casting="same_kind")
2189
+
2190
+
2191
+ def get_different_alignment_node_ndarray(node_ndarray):
2192
+ new_dtype_dict = {
2193
+ name: dtype for name, (dtype, _) in node_ndarray.dtype.fields.items()
2194
+ }
2195
+ offsets = [offset for dtype, offset in node_ndarray.dtype.fields.values()]
2196
+ shifted_offsets = [8 + offset for offset in offsets]
2197
+
2198
+ new_dtype = np.dtype(
2199
+ {
2200
+ "names": list(new_dtype_dict.keys()),
2201
+ "formats": list(new_dtype_dict.values()),
2202
+ "offsets": shifted_offsets,
2203
+ }
2204
+ )
2205
+ return node_ndarray.astype(new_dtype, casting="same_kind")
2206
+
2207
+
2208
+ def reduce_tree_with_different_bitness(tree):
2209
+ new_dtype = np.int64 if _IS_32BIT else np.int32
2210
+ tree_cls, (n_features, n_classes, n_outputs), state = tree.__reduce__()
2211
+ new_n_classes = n_classes.astype(new_dtype, casting="same_kind")
2212
+
2213
+ new_state = state.copy()
2214
+ new_state["nodes"] = get_different_bitness_node_ndarray(new_state["nodes"])
2215
+
2216
+ return (tree_cls, (n_features, new_n_classes, n_outputs), new_state)
2217
+
2218
+
2219
+ def test_different_bitness_pickle():
2220
+ X, y = datasets.make_classification(random_state=0)
2221
+
2222
+ clf = DecisionTreeClassifier(random_state=0, max_depth=3)
2223
+ clf.fit(X, y)
2224
+ score = clf.score(X, y)
2225
+
2226
+ def pickle_dump_with_different_bitness():
2227
+ f = io.BytesIO()
2228
+ p = pickle.Pickler(f)
2229
+ p.dispatch_table = copyreg.dispatch_table.copy()
2230
+ p.dispatch_table[CythonTree] = reduce_tree_with_different_bitness
2231
+
2232
+ p.dump(clf)
2233
+ f.seek(0)
2234
+ return f
2235
+
2236
+ new_clf = pickle.load(pickle_dump_with_different_bitness())
2237
+ new_score = new_clf.score(X, y)
2238
+ assert score == pytest.approx(new_score)
2239
+
2240
+
2241
+ def test_different_bitness_joblib_pickle():
2242
+ # Make sure that a platform specific pickle generated on a 64 bit
2243
+ # platform can be converted at pickle load time into an estimator
2244
+ # with Cython code that works with the host's native integer precision
2245
+ # to index nodes in the tree data structure when the host is a 32 bit
2246
+ # platform (and vice versa).
2247
+ X, y = datasets.make_classification(random_state=0)
2248
+
2249
+ clf = DecisionTreeClassifier(random_state=0, max_depth=3)
2250
+ clf.fit(X, y)
2251
+ score = clf.score(X, y)
2252
+
2253
+ def joblib_dump_with_different_bitness():
2254
+ f = io.BytesIO()
2255
+ p = NumpyPickler(f)
2256
+ p.dispatch_table = copyreg.dispatch_table.copy()
2257
+ p.dispatch_table[CythonTree] = reduce_tree_with_different_bitness
2258
+
2259
+ p.dump(clf)
2260
+ f.seek(0)
2261
+ return f
2262
+
2263
+ new_clf = joblib.load(joblib_dump_with_different_bitness())
2264
+ new_score = new_clf.score(X, y)
2265
+ assert score == pytest.approx(new_score)
2266
+
2267
+
2268
+ def test_check_n_classes():
2269
+ expected_dtype = np.dtype(np.int32) if _IS_32BIT else np.dtype(np.int64)
2270
+ allowed_dtypes = [np.dtype(np.int32), np.dtype(np.int64)]
2271
+ allowed_dtypes += [dt.newbyteorder() for dt in allowed_dtypes]
2272
+
2273
+ n_classes = np.array([0, 1], dtype=expected_dtype)
2274
+ for dt in allowed_dtypes:
2275
+ _check_n_classes(n_classes.astype(dt), expected_dtype)
2276
+
2277
+ with pytest.raises(ValueError, match="Wrong dimensions.+n_classes"):
2278
+ wrong_dim_n_classes = np.array([[0, 1]], dtype=expected_dtype)
2279
+ _check_n_classes(wrong_dim_n_classes, expected_dtype)
2280
+
2281
+ with pytest.raises(ValueError, match="n_classes.+incompatible dtype"):
2282
+ wrong_dtype_n_classes = n_classes.astype(np.float64)
2283
+ _check_n_classes(wrong_dtype_n_classes, expected_dtype)
2284
+
2285
+
2286
+ def test_check_value_ndarray():
2287
+ expected_dtype = np.dtype(np.float64)
2288
+ expected_shape = (5, 1, 2)
2289
+ value_ndarray = np.zeros(expected_shape, dtype=expected_dtype)
2290
+
2291
+ allowed_dtypes = [expected_dtype, expected_dtype.newbyteorder()]
2292
+
2293
+ for dt in allowed_dtypes:
2294
+ _check_value_ndarray(
2295
+ value_ndarray, expected_dtype=dt, expected_shape=expected_shape
2296
+ )
2297
+
2298
+ with pytest.raises(ValueError, match="Wrong shape.+value array"):
2299
+ _check_value_ndarray(
2300
+ value_ndarray, expected_dtype=expected_dtype, expected_shape=(1, 2)
2301
+ )
2302
+
2303
+ for problematic_arr in [value_ndarray[:, :, :1], np.asfortranarray(value_ndarray)]:
2304
+ with pytest.raises(ValueError, match="value array.+C-contiguous"):
2305
+ _check_value_ndarray(
2306
+ problematic_arr,
2307
+ expected_dtype=expected_dtype,
2308
+ expected_shape=problematic_arr.shape,
2309
+ )
2310
+
2311
+ with pytest.raises(ValueError, match="value array.+incompatible dtype"):
2312
+ _check_value_ndarray(
2313
+ value_ndarray.astype(np.float32),
2314
+ expected_dtype=expected_dtype,
2315
+ expected_shape=expected_shape,
2316
+ )
2317
+
2318
+
2319
+ def test_check_node_ndarray():
2320
+ expected_dtype = NODE_DTYPE
2321
+
2322
+ node_ndarray = np.zeros((5,), dtype=expected_dtype)
2323
+
2324
+ valid_node_ndarrays = [
2325
+ node_ndarray,
2326
+ get_different_bitness_node_ndarray(node_ndarray),
2327
+ get_different_alignment_node_ndarray(node_ndarray),
2328
+ ]
2329
+ valid_node_ndarrays += [
2330
+ arr.astype(arr.dtype.newbyteorder()) for arr in valid_node_ndarrays
2331
+ ]
2332
+
2333
+ for arr in valid_node_ndarrays:
2334
+ _check_node_ndarray(node_ndarray, expected_dtype=expected_dtype)
2335
+
2336
+ with pytest.raises(ValueError, match="Wrong dimensions.+node array"):
2337
+ problematic_node_ndarray = np.zeros((5, 2), dtype=expected_dtype)
2338
+ _check_node_ndarray(problematic_node_ndarray, expected_dtype=expected_dtype)
2339
+
2340
+ with pytest.raises(ValueError, match="node array.+C-contiguous"):
2341
+ problematic_node_ndarray = node_ndarray[::2]
2342
+ _check_node_ndarray(problematic_node_ndarray, expected_dtype=expected_dtype)
2343
+
2344
+ dtype_dict = {name: dtype for name, (dtype, _) in node_ndarray.dtype.fields.items()}
2345
+
2346
+ # array with wrong 'threshold' field dtype (int64 rather than float64)
2347
+ new_dtype_dict = dtype_dict.copy()
2348
+ new_dtype_dict["threshold"] = np.int64
2349
+
2350
+ new_dtype = np.dtype(
2351
+ {"names": list(new_dtype_dict.keys()), "formats": list(new_dtype_dict.values())}
2352
+ )
2353
+ problematic_node_ndarray = node_ndarray.astype(new_dtype)
2354
+
2355
+ with pytest.raises(ValueError, match="node array.+incompatible dtype"):
2356
+ _check_node_ndarray(problematic_node_ndarray, expected_dtype=expected_dtype)
2357
+
2358
+ # array with wrong 'left_child' field dtype (float64 rather than int64 or int32)
2359
+ new_dtype_dict = dtype_dict.copy()
2360
+ new_dtype_dict["left_child"] = np.float64
2361
+ new_dtype = np.dtype(
2362
+ {"names": list(new_dtype_dict.keys()), "formats": list(new_dtype_dict.values())}
2363
+ )
2364
+
2365
+ problematic_node_ndarray = node_ndarray.astype(new_dtype)
2366
+
2367
+ with pytest.raises(ValueError, match="node array.+incompatible dtype"):
2368
+ _check_node_ndarray(problematic_node_ndarray, expected_dtype=expected_dtype)
2369
+
2370
+
2371
+ # TODO(1.3): Remove
2372
+ def test_max_features_auto_deprecated():
2373
+ for Tree in CLF_TREES.values():
2374
+ tree = Tree(max_features="auto")
2375
+ msg = (
2376
+ "`max_features='auto'` has been deprecated in 1.1 and will be removed in"
2377
+ " 1.3. To keep the past behaviour, explicitly set `max_features='sqrt'`."
2378
+ )
2379
+ with pytest.warns(FutureWarning, match=msg):
2380
+ tree.fit(X, y)
2381
+
2382
+ for Tree in REG_TREES.values():
2383
+ tree = Tree(max_features="auto")
2384
+ msg = (
2385
+ "`max_features='auto'` has been deprecated in 1.1 and will be removed in"
2386
+ " 1.3. To keep the past behaviour, explicitly set `max_features=1.0'`."
2387
+ )
2388
+ with pytest.warns(FutureWarning, match=msg):
2389
+ tree.fit(X, y)
2390
+
2391
+
2392
+ def test_tree_deserialization_from_read_only_buffer(tmpdir):
2393
+ """Check that Trees can be deserialized with read only buffers.
2394
+
2395
+ Non-regression test for gh-25584.
2396
+ """
2397
+ pickle_path = str(tmpdir.join("clf.joblib"))
2398
+ clf = DecisionTreeClassifier(random_state=0)
2399
+ clf.fit(X_small, y_small)
2400
+
2401
+ joblib.dump(clf, pickle_path)
2402
+ loaded_clf = joblib.load(pickle_path, mmap_mode="r")
2403
+
2404
+ assert_tree_equal(
2405
+ loaded_clf.tree_,
2406
+ clf.tree_,
2407
+ "The trees of the original and loaded classifiers are not equal.",
2408
+ )
2409
+
2410
+
2411
+ @pytest.mark.parametrize("Tree", ALL_TREES.values())
2412
+ def test_min_sample_split_1_error(Tree):
2413
+ """Check that an error is raised when min_sample_split=1.
2414
+
2415
+ non-regression test for issue gh-25481.
2416
+ """
2417
+ X = np.array([[0, 0], [1, 1]])
2418
+ y = np.array([0, 1])
2419
+
2420
+ # min_samples_split=1.0 is valid
2421
+ Tree(min_samples_split=1.0).fit(X, y)
2422
+
2423
+ # min_samples_split=1 is invalid
2424
+ tree = Tree(min_samples_split=1)
2425
+ msg = (
2426
+ r"'min_samples_split' .* must be an int in the range \[2, inf\) "
2427
+ r"or a float in the range \(0.0, 1.0\]"
2428
+ )
2429
+ with pytest.raises(ValueError, match=msg):
2430
+ tree.fit(X, y)
videollama2/lib/python3.10/site-packages/sklearn/utils/_arpack.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .validation import check_random_state
2
+
3
+
4
+ def _init_arpack_v0(size, random_state):
5
+ """Initialize the starting vector for iteration in ARPACK functions.
6
+
7
+ Initialize a ndarray with values sampled from the uniform distribution on
8
+ [-1, 1]. This initialization model has been chosen to be consistent with
9
+ the ARPACK one as another initialization can lead to convergence issues.
10
+
11
+ Parameters
12
+ ----------
13
+ size : int
14
+ The size of the eigenvalue vector to be initialized.
15
+
16
+ random_state : int, RandomState instance or None, default=None
17
+ The seed of the pseudo random number generator used to generate a
18
+ uniform distribution. If int, random_state is the seed used by the
19
+ random number generator; If RandomState instance, random_state is the
20
+ random number generator; If None, the random number generator is the
21
+ RandomState instance used by `np.random`.
22
+
23
+ Returns
24
+ -------
25
+ v0 : ndarray of shape (size,)
26
+ The initialized vector.
27
+ """
28
+ random_state = check_random_state(random_state)
29
+ v0 = random_state.uniform(-1, 1, size)
30
+ return v0
videollama2/lib/python3.10/site-packages/sklearn/utils/_array_api.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tools to support array_api."""
2
+ import numpy
3
+ from .._config import get_config
4
+ import scipy.special as special
5
+
6
+
7
+ class _ArrayAPIWrapper:
8
+ """sklearn specific Array API compatibility wrapper
9
+
10
+ This wrapper makes it possible for scikit-learn maintainers to
11
+ deal with discrepancies between different implementations of the
12
+ Python array API standard and its evolution over time.
13
+
14
+ The Python array API standard specification:
15
+ https://data-apis.org/array-api/latest/
16
+
17
+ Documentation of the NumPy implementation:
18
+ https://numpy.org/neps/nep-0047-array-api-standard.html
19
+ """
20
+
21
+ def __init__(self, array_namespace):
22
+ self._namespace = array_namespace
23
+
24
+ def __getattr__(self, name):
25
+ return getattr(self._namespace, name)
26
+
27
+ def take(self, X, indices, *, axis):
28
+ # When array_api supports `take` we can use this directly
29
+ # https://github.com/data-apis/array-api/issues/177
30
+ if self._namespace.__name__ == "numpy.array_api":
31
+ X_np = numpy.take(X, indices, axis=axis)
32
+ return self._namespace.asarray(X_np)
33
+
34
+ # We only support axis in (0, 1) and ndim in (1, 2) because that is all we need
35
+ # in scikit-learn
36
+ if axis not in {0, 1}:
37
+ raise ValueError(f"Only axis in (0, 1) is supported. Got {axis}")
38
+
39
+ if X.ndim not in {1, 2}:
40
+ raise ValueError(f"Only X.ndim in (1, 2) is supported. Got {X.ndim}")
41
+
42
+ if axis == 0:
43
+ if X.ndim == 1:
44
+ selected = [X[i] for i in indices]
45
+ else: # X.ndim == 2
46
+ selected = [X[i, :] for i in indices]
47
+ else: # axis == 1
48
+ selected = [X[:, i] for i in indices]
49
+ return self._namespace.stack(selected, axis=axis)
50
+
51
+
52
+ class _NumPyApiWrapper:
53
+ """Array API compat wrapper for any numpy version
54
+
55
+ NumPy < 1.22 does not expose the numpy.array_api namespace. This
56
+ wrapper makes it possible to write code that uses the standard
57
+ Array API while working with any version of NumPy supported by
58
+ scikit-learn.
59
+
60
+ See the `get_namespace()` public function for more details.
61
+ """
62
+
63
+ def __getattr__(self, name):
64
+ return getattr(numpy, name)
65
+
66
+ def astype(self, x, dtype, *, copy=True, casting="unsafe"):
67
+ # astype is not defined in the top level NumPy namespace
68
+ return x.astype(dtype, copy=copy, casting=casting)
69
+
70
+ def asarray(self, x, *, dtype=None, device=None, copy=None):
71
+ # Support copy in NumPy namespace
72
+ if copy is True:
73
+ return numpy.array(x, copy=True, dtype=dtype)
74
+ else:
75
+ return numpy.asarray(x, dtype=dtype)
76
+
77
+ def unique_inverse(self, x):
78
+ return numpy.unique(x, return_inverse=True)
79
+
80
+ def unique_counts(self, x):
81
+ return numpy.unique(x, return_counts=True)
82
+
83
+ def unique_values(self, x):
84
+ return numpy.unique(x)
85
+
86
+ def concat(self, arrays, *, axis=None):
87
+ return numpy.concatenate(arrays, axis=axis)
88
+
89
+
90
+ def get_namespace(*arrays):
91
+ """Get namespace of arrays.
92
+
93
+ Introspect `arrays` arguments and return their common Array API
94
+ compatible namespace object, if any. NumPy 1.22 and later can
95
+ construct such containers using the `numpy.array_api` namespace
96
+ for instance.
97
+
98
+ See: https://numpy.org/neps/nep-0047-array-api-standard.html
99
+
100
+ If `arrays` are regular numpy arrays, an instance of the
101
+ `_NumPyApiWrapper` compatibility wrapper is returned instead.
102
+
103
+ Namespace support is not enabled by default. To enabled it
104
+ call:
105
+
106
+ sklearn.set_config(array_api_dispatch=True)
107
+
108
+ or:
109
+
110
+ with sklearn.config_context(array_api_dispatch=True):
111
+ # your code here
112
+
113
+ Otherwise an instance of the `_NumPyApiWrapper`
114
+ compatibility wrapper is always returned irrespective of
115
+ the fact that arrays implement the `__array_namespace__`
116
+ protocol or not.
117
+
118
+ Parameters
119
+ ----------
120
+ *arrays : array objects
121
+ Array objects.
122
+
123
+ Returns
124
+ -------
125
+ namespace : module
126
+ Namespace shared by array objects.
127
+
128
+ is_array_api : bool
129
+ True of the arrays are containers that implement the Array API spec.
130
+ """
131
+ # `arrays` contains one or more arrays, or possibly Python scalars (accepting
132
+ # those is a matter of taste, but doesn't seem unreasonable).
133
+ # Returns a tuple: (array_namespace, is_array_api)
134
+
135
+ if not get_config()["array_api_dispatch"]:
136
+ return _NumPyApiWrapper(), False
137
+
138
+ namespaces = {
139
+ x.__array_namespace__() if hasattr(x, "__array_namespace__") else None
140
+ for x in arrays
141
+ if not isinstance(x, (bool, int, float, complex))
142
+ }
143
+
144
+ if not namespaces:
145
+ # one could special-case np.ndarray above or use np.asarray here if
146
+ # older numpy versions need to be supported.
147
+ raise ValueError("Unrecognized array input")
148
+
149
+ if len(namespaces) != 1:
150
+ raise ValueError(f"Multiple namespaces for array inputs: {namespaces}")
151
+
152
+ (xp,) = namespaces
153
+ if xp is None:
154
+ # Use numpy as default
155
+ return _NumPyApiWrapper(), False
156
+
157
+ return _ArrayAPIWrapper(xp), True
158
+
159
+
160
+ def _expit(X):
161
+ xp, _ = get_namespace(X)
162
+ if xp.__name__ in {"numpy", "numpy.array_api"}:
163
+ return xp.asarray(special.expit(numpy.asarray(X)))
164
+
165
+ return 1.0 / (1.0 + xp.exp(-X))
166
+
167
+
168
+ def _asarray_with_order(array, dtype=None, order=None, copy=None, xp=None):
169
+ """Helper to support the order kwarg only for NumPy-backed arrays
170
+
171
+ Memory layout parameter `order` is not exposed in the Array API standard,
172
+ however some input validation code in scikit-learn needs to work both
173
+ for classes and functions that will leverage Array API only operations
174
+ and for code that inherently relies on NumPy backed data containers with
175
+ specific memory layout constraints (e.g. our own Cython code). The
176
+ purpose of this helper is to make it possible to share code for data
177
+ container validation without memory copies for both downstream use cases:
178
+ the `order` parameter is only enforced if the input array implementation
179
+ is NumPy based, otherwise `order` is just silently ignored.
180
+ """
181
+ if xp is None:
182
+ xp, _ = get_namespace(array)
183
+ if xp.__name__ in {"numpy", "numpy.array_api"}:
184
+ # Use NumPy API to support order
185
+ array = numpy.asarray(array, order=order, dtype=dtype)
186
+ return xp.asarray(array, copy=copy)
187
+ else:
188
+ return xp.asarray(array, dtype=dtype, copy=copy)
189
+
190
+
191
+ def _convert_to_numpy(array, xp):
192
+ """Convert X into a NumPy ndarray.
193
+
194
+ Only works on cupy.array_api and numpy.array_api and is used for testing.
195
+ """
196
+ supported_array_api = ["numpy.array_api", "cupy.array_api"]
197
+ if xp.__name__ not in supported_array_api:
198
+ support_array_api_str = ", ".join(supported_array_api)
199
+ raise ValueError(f"Supported namespaces are: {support_array_api_str}")
200
+
201
+ if xp.__name__ == "cupy.array_api":
202
+ return array._array.get()
203
+ else:
204
+ return numpy.asarray(array)
205
+
206
+
207
+ def _estimator_with_converted_arrays(estimator, converter):
208
+ """Create new estimator which converting all attributes that are arrays.
209
+
210
+ Parameters
211
+ ----------
212
+ estimator : Estimator
213
+ Estimator to convert
214
+
215
+ converter : callable
216
+ Callable that takes an array attribute and returns the converted array.
217
+
218
+ Returns
219
+ -------
220
+ new_estimator : Estimator
221
+ Convert estimator
222
+ """
223
+ from sklearn.base import clone
224
+
225
+ new_estimator = clone(estimator)
226
+ for key, attribute in vars(estimator).items():
227
+ if hasattr(attribute, "__array_namespace__") or isinstance(
228
+ attribute, numpy.ndarray
229
+ ):
230
+ attribute = converter(attribute)
231
+ setattr(new_estimator, key, attribute)
232
+ return new_estimator
videollama2/lib/python3.10/site-packages/sklearn/utils/_joblib.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings as _warnings
2
+
3
+ with _warnings.catch_warnings():
4
+ _warnings.simplefilter("ignore")
5
+ # joblib imports may raise DeprecationWarning on certain Python
6
+ # versions
7
+ import joblib
8
+ from joblib import logger
9
+ from joblib import dump, load
10
+ from joblib import __version__
11
+ from joblib import effective_n_jobs
12
+ from joblib import hash
13
+ from joblib import cpu_count, Parallel, Memory, delayed
14
+ from joblib import parallel_backend, register_parallel_backend
15
+
16
+
17
+ __all__ = [
18
+ "parallel_backend",
19
+ "register_parallel_backend",
20
+ "cpu_count",
21
+ "Parallel",
22
+ "Memory",
23
+ "delayed",
24
+ "effective_n_jobs",
25
+ "hash",
26
+ "logger",
27
+ "dump",
28
+ "load",
29
+ "joblib",
30
+ "__version__",
31
+ ]
videollama2/lib/python3.10/site-packages/sklearn/utils/_logistic_sigmoid.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a289dcf0576538ce83dae8afd304a7eabfae9ac387e1c2603cc0acde379d6c73
3
+ size 187849
videollama2/lib/python3.10/site-packages/sklearn/utils/_mask.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy import sparse as sp
3
+ from contextlib import suppress
4
+
5
+ from . import is_scalar_nan
6
+ from .fixes import _object_dtype_isnan
7
+
8
+
9
+ def _get_dense_mask(X, value_to_mask):
10
+ with suppress(ImportError, AttributeError):
11
+ # We also suppress `AttributeError` because older versions of pandas do
12
+ # not have `NA`.
13
+ import pandas
14
+
15
+ if value_to_mask is pandas.NA:
16
+ return pandas.isna(X)
17
+
18
+ if is_scalar_nan(value_to_mask):
19
+ if X.dtype.kind == "f":
20
+ Xt = np.isnan(X)
21
+ elif X.dtype.kind in ("i", "u"):
22
+ # can't have NaNs in integer array.
23
+ Xt = np.zeros(X.shape, dtype=bool)
24
+ else:
25
+ # np.isnan does not work on object dtypes.
26
+ Xt = _object_dtype_isnan(X)
27
+ else:
28
+ Xt = X == value_to_mask
29
+
30
+ return Xt
31
+
32
+
33
+ def _get_mask(X, value_to_mask):
34
+ """Compute the boolean mask X == value_to_mask.
35
+
36
+ Parameters
37
+ ----------
38
+ X : {ndarray, sparse matrix} of shape (n_samples, n_features)
39
+ Input data, where ``n_samples`` is the number of samples and
40
+ ``n_features`` is the number of features.
41
+
42
+ value_to_mask : {int, float}
43
+ The value which is to be masked in X.
44
+
45
+ Returns
46
+ -------
47
+ X_mask : {ndarray, sparse matrix} of shape (n_samples, n_features)
48
+ Missing mask.
49
+ """
50
+ if not sp.issparse(X):
51
+ # For all cases apart of a sparse input where we need to reconstruct
52
+ # a sparse output
53
+ return _get_dense_mask(X, value_to_mask)
54
+
55
+ Xt = _get_dense_mask(X.data, value_to_mask)
56
+
57
+ sparse_constructor = sp.csr_matrix if X.format == "csr" else sp.csc_matrix
58
+ Xt_sparse = sparse_constructor(
59
+ (Xt, X.indices.copy(), X.indptr.copy()), shape=X.shape, dtype=bool
60
+ )
61
+
62
+ return Xt_sparse
videollama2/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (47.2 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/_openmp_helpers.pxd ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Helpers to access OpenMP threads information
2
+ #
3
+ # Those interfaces act as indirections which allows the non-support of OpenMP
4
+ # for implementations which have been written for it.
5
+
6
+ cdef int _openmp_thread_num() nogil
videollama2/lib/python3.10/site-packages/sklearn/utils/_param_validation.py ADDED
@@ -0,0 +1,943 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC
2
+ from abc import abstractmethod
3
+ from collections.abc import Iterable
4
+ import functools
5
+ import math
6
+ from inspect import signature
7
+ from numbers import Integral
8
+ from numbers import Real
9
+ import operator
10
+ import re
11
+ import warnings
12
+
13
+ import numpy as np
14
+ from scipy.sparse import issparse
15
+ from scipy.sparse import csr_matrix
16
+
17
+ from .validation import _is_arraylike_not_scalar
18
+
19
+
20
+ class InvalidParameterError(ValueError, TypeError):
21
+ """Custom exception to be raised when the parameter of a class/method/function
22
+ does not have a valid type or value.
23
+ """
24
+
25
+ # Inherits from ValueError and TypeError to keep backward compatibility.
26
+
27
+
28
+ def validate_parameter_constraints(parameter_constraints, params, caller_name):
29
+ """Validate types and values of given parameters.
30
+
31
+ Parameters
32
+ ----------
33
+ parameter_constraints : dict or {"no_validation"}
34
+ If "no_validation", validation is skipped for this parameter.
35
+
36
+ If a dict, it must be a dictionary `param_name: list of constraints`.
37
+ A parameter is valid if it satisfies one of the constraints from the list.
38
+ Constraints can be:
39
+ - an Interval object, representing a continuous or discrete range of numbers
40
+ - the string "array-like"
41
+ - the string "sparse matrix"
42
+ - the string "random_state"
43
+ - callable
44
+ - None, meaning that None is a valid value for the parameter
45
+ - any type, meaning that any instance of this type is valid
46
+ - an Options object, representing a set of elements of a given type
47
+ - a StrOptions object, representing a set of strings
48
+ - the string "boolean"
49
+ - the string "verbose"
50
+ - the string "cv_object"
51
+ - the string "missing_values"
52
+ - a HasMethods object, representing method(s) an object must have
53
+ - a Hidden object, representing a constraint not meant to be exposed to the user
54
+
55
+ params : dict
56
+ A dictionary `param_name: param_value`. The parameters to validate against the
57
+ constraints.
58
+
59
+ caller_name : str
60
+ The name of the estimator or function or method that called this function.
61
+ """
62
+ for param_name, param_val in params.items():
63
+ # We allow parameters to not have a constraint so that third party estimators
64
+ # can inherit from sklearn estimators without having to necessarily use the
65
+ # validation tools.
66
+ if param_name not in parameter_constraints:
67
+ continue
68
+
69
+ constraints = parameter_constraints[param_name]
70
+
71
+ if constraints == "no_validation":
72
+ continue
73
+
74
+ constraints = [make_constraint(constraint) for constraint in constraints]
75
+
76
+ for constraint in constraints:
77
+ if constraint.is_satisfied_by(param_val):
78
+ # this constraint is satisfied, no need to check further.
79
+ break
80
+ else:
81
+ # No constraint is satisfied, raise with an informative message.
82
+
83
+ # Ignore constraints that we don't want to expose in the error message,
84
+ # i.e. options that are for internal purpose or not officially supported.
85
+ constraints = [
86
+ constraint for constraint in constraints if not constraint.hidden
87
+ ]
88
+
89
+ if len(constraints) == 1:
90
+ constraints_str = f"{constraints[0]}"
91
+ else:
92
+ constraints_str = (
93
+ f"{', '.join([str(c) for c in constraints[:-1]])} or"
94
+ f" {constraints[-1]}"
95
+ )
96
+
97
+ raise InvalidParameterError(
98
+ f"The {param_name!r} parameter of {caller_name} must be"
99
+ f" {constraints_str}. Got {param_val!r} instead."
100
+ )
101
+
102
+
103
+ def make_constraint(constraint):
104
+ """Convert the constraint into the appropriate Constraint object.
105
+
106
+ Parameters
107
+ ----------
108
+ constraint : object
109
+ The constraint to convert.
110
+
111
+ Returns
112
+ -------
113
+ constraint : instance of _Constraint
114
+ The converted constraint.
115
+ """
116
+ if isinstance(constraint, str) and constraint == "array-like":
117
+ return _ArrayLikes()
118
+ if isinstance(constraint, str) and constraint == "sparse matrix":
119
+ return _SparseMatrices()
120
+ if isinstance(constraint, str) and constraint == "random_state":
121
+ return _RandomStates()
122
+ if constraint is callable:
123
+ return _Callables()
124
+ if constraint is None:
125
+ return _NoneConstraint()
126
+ if isinstance(constraint, type):
127
+ return _InstancesOf(constraint)
128
+ if isinstance(constraint, (Interval, StrOptions, Options, HasMethods)):
129
+ return constraint
130
+ if isinstance(constraint, str) and constraint == "boolean":
131
+ return _Booleans()
132
+ if isinstance(constraint, str) and constraint == "verbose":
133
+ return _VerboseHelper()
134
+ if isinstance(constraint, str) and constraint == "missing_values":
135
+ return _MissingValues()
136
+ if isinstance(constraint, str) and constraint == "cv_object":
137
+ return _CVObjects()
138
+ if isinstance(constraint, Hidden):
139
+ constraint = make_constraint(constraint.constraint)
140
+ constraint.hidden = True
141
+ return constraint
142
+ raise ValueError(f"Unknown constraint type: {constraint}")
143
+
144
+
145
+ def validate_params(parameter_constraints):
146
+ """Decorator to validate types and values of functions and methods.
147
+
148
+ Parameters
149
+ ----------
150
+ parameter_constraints : dict
151
+ A dictionary `param_name: list of constraints`. See the docstring of
152
+ `validate_parameter_constraints` for a description of the accepted constraints.
153
+
154
+ Note that the *args and **kwargs parameters are not validated and must not be
155
+ present in the parameter_constraints dictionary.
156
+
157
+ Returns
158
+ -------
159
+ decorated_function : function or method
160
+ The decorated function.
161
+ """
162
+
163
+ def decorator(func):
164
+ # The dict of parameter constraints is set as an attribute of the function
165
+ # to make it possible to dynamically introspect the constraints for
166
+ # automatic testing.
167
+ setattr(func, "_skl_parameter_constraints", parameter_constraints)
168
+
169
+ @functools.wraps(func)
170
+ def wrapper(*args, **kwargs):
171
+
172
+ func_sig = signature(func)
173
+
174
+ # Map *args/**kwargs to the function signature
175
+ params = func_sig.bind(*args, **kwargs)
176
+ params.apply_defaults()
177
+
178
+ # ignore self/cls and positional/keyword markers
179
+ to_ignore = [
180
+ p.name
181
+ for p in func_sig.parameters.values()
182
+ if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD)
183
+ ]
184
+ to_ignore += ["self", "cls"]
185
+ params = {k: v for k, v in params.arguments.items() if k not in to_ignore}
186
+
187
+ validate_parameter_constraints(
188
+ parameter_constraints, params, caller_name=func.__qualname__
189
+ )
190
+
191
+ try:
192
+ return func(*args, **kwargs)
193
+ except InvalidParameterError as e:
194
+ # When the function is just a wrapper around an estimator, we allow
195
+ # the function to delegate validation to the estimator, but we replace
196
+ # the name of the estimator by the name of the function in the error
197
+ # message to avoid confusion.
198
+ msg = re.sub(
199
+ r"parameter of \w+ must be",
200
+ f"parameter of {func.__qualname__} must be",
201
+ str(e),
202
+ )
203
+ raise InvalidParameterError(msg) from e
204
+
205
+ return wrapper
206
+
207
+ return decorator
208
+
209
+
210
+ def _type_name(t):
211
+ """Convert type into human readable string."""
212
+ module = t.__module__
213
+ qualname = t.__qualname__
214
+ if module == "builtins":
215
+ return qualname
216
+ elif t == Real:
217
+ return "float"
218
+ elif t == Integral:
219
+ return "int"
220
+ return f"{module}.{qualname}"
221
+
222
+
223
+ class _Constraint(ABC):
224
+ """Base class for the constraint objects."""
225
+
226
+ def __init__(self):
227
+ self.hidden = False
228
+
229
+ @abstractmethod
230
+ def is_satisfied_by(self, val):
231
+ """Whether or not a value satisfies the constraint.
232
+
233
+ Parameters
234
+ ----------
235
+ val : object
236
+ The value to check.
237
+
238
+ Returns
239
+ -------
240
+ is_satisfied : bool
241
+ Whether or not the constraint is satisfied by this value.
242
+ """
243
+
244
+ @abstractmethod
245
+ def __str__(self):
246
+ """A human readable representational string of the constraint."""
247
+
248
+
249
+ class _InstancesOf(_Constraint):
250
+ """Constraint representing instances of a given type.
251
+
252
+ Parameters
253
+ ----------
254
+ type : type
255
+ The valid type.
256
+ """
257
+
258
+ def __init__(self, type):
259
+ super().__init__()
260
+ self.type = type
261
+
262
+ def is_satisfied_by(self, val):
263
+ return isinstance(val, self.type)
264
+
265
+ def __str__(self):
266
+ return f"an instance of {_type_name(self.type)!r}"
267
+
268
+
269
+ class _NoneConstraint(_Constraint):
270
+ """Constraint representing the None singleton."""
271
+
272
+ def is_satisfied_by(self, val):
273
+ return val is None
274
+
275
+ def __str__(self):
276
+ return "None"
277
+
278
+
279
+ class _NanConstraint(_Constraint):
280
+ """Constraint representing the indicator `np.nan`."""
281
+
282
+ def is_satisfied_by(self, val):
283
+ return isinstance(val, Real) and math.isnan(val)
284
+
285
+ def __str__(self):
286
+ return "numpy.nan"
287
+
288
+
289
+ class _PandasNAConstraint(_Constraint):
290
+ """Constraint representing the indicator `pd.NA`."""
291
+
292
+ def is_satisfied_by(self, val):
293
+ try:
294
+ import pandas as pd
295
+
296
+ return isinstance(val, type(pd.NA)) and pd.isna(val)
297
+ except ImportError:
298
+ return False
299
+
300
+ def __str__(self):
301
+ return "pandas.NA"
302
+
303
+
304
+ class Options(_Constraint):
305
+ """Constraint representing a finite set of instances of a given type.
306
+
307
+ Parameters
308
+ ----------
309
+ type : type
310
+
311
+ options : set
312
+ The set of valid scalars.
313
+
314
+ deprecated : set or None, default=None
315
+ A subset of the `options` to mark as deprecated in the string
316
+ representation of the constraint.
317
+ """
318
+
319
+ def __init__(self, type, options, *, deprecated=None):
320
+ super().__init__()
321
+ self.type = type
322
+ self.options = options
323
+ self.deprecated = deprecated or set()
324
+
325
+ if self.deprecated - self.options:
326
+ raise ValueError("The deprecated options must be a subset of the options.")
327
+
328
+ def is_satisfied_by(self, val):
329
+ return isinstance(val, self.type) and val in self.options
330
+
331
+ def _mark_if_deprecated(self, option):
332
+ """Add a deprecated mark to an option if needed."""
333
+ option_str = f"{option!r}"
334
+ if option in self.deprecated:
335
+ option_str = f"{option_str} (deprecated)"
336
+ return option_str
337
+
338
+ def __str__(self):
339
+ options_str = (
340
+ f"{', '.join([self._mark_if_deprecated(o) for o in self.options])}"
341
+ )
342
+ return f"a {_type_name(self.type)} among {{{options_str}}}"
343
+
344
+
345
+ class StrOptions(Options):
346
+ """Constraint representing a finite set of strings.
347
+
348
+ Parameters
349
+ ----------
350
+ options : set of str
351
+ The set of valid strings.
352
+
353
+ deprecated : set of str or None, default=None
354
+ A subset of the `options` to mark as deprecated in the string
355
+ representation of the constraint.
356
+ """
357
+
358
+ def __init__(self, options, *, deprecated=None):
359
+ super().__init__(type=str, options=options, deprecated=deprecated)
360
+
361
+
362
+ class Interval(_Constraint):
363
+ """Constraint representing a typed interval.
364
+
365
+ Parameters
366
+ ----------
367
+ type : {numbers.Integral, numbers.Real, "real_not_int"}
368
+ The set of numbers in which to set the interval.
369
+
370
+ If "real_not_int", only reals that don't have the integer type
371
+ are allowed. For example 1.0 is allowed but 1 is not.
372
+
373
+ left : float or int or None
374
+ The left bound of the interval. None means left bound is -∞.
375
+
376
+ right : float, int or None
377
+ The right bound of the interval. None means right bound is +∞.
378
+
379
+ closed : {"left", "right", "both", "neither"}
380
+ Whether the interval is open or closed. Possible choices are:
381
+
382
+ - `"left"`: the interval is closed on the left and open on the right.
383
+ It is equivalent to the interval `[ left, right )`.
384
+ - `"right"`: the interval is closed on the right and open on the left.
385
+ It is equivalent to the interval `( left, right ]`.
386
+ - `"both"`: the interval is closed.
387
+ It is equivalent to the interval `[ left, right ]`.
388
+ - `"neither"`: the interval is open.
389
+ It is equivalent to the interval `( left, right )`.
390
+
391
+ Notes
392
+ -----
393
+ Setting a bound to `None` and setting the interval closed is valid. For instance,
394
+ strictly speaking, `Interval(Real, 0, None, closed="both")` corresponds to
395
+ `[0, +∞) U {+∞}`.
396
+ """
397
+
398
+ def __init__(self, type, left, right, *, closed):
399
+ super().__init__()
400
+ self.type = type
401
+ self.left = left
402
+ self.right = right
403
+ self.closed = closed
404
+
405
+ self._check_params()
406
+
407
+ def _check_params(self):
408
+ if self.type not in (Integral, Real, "real_not_int"):
409
+ raise ValueError(
410
+ "type must be either numbers.Integral, numbers.Real or 'real_not_int'."
411
+ f" Got {self.type} instead."
412
+ )
413
+
414
+ if self.closed not in ("left", "right", "both", "neither"):
415
+ raise ValueError(
416
+ "closed must be either 'left', 'right', 'both' or 'neither'. "
417
+ f"Got {self.closed} instead."
418
+ )
419
+
420
+ if self.type is Integral:
421
+ suffix = "for an interval over the integers."
422
+ if self.left is not None and not isinstance(self.left, Integral):
423
+ raise TypeError(f"Expecting left to be an int {suffix}")
424
+ if self.right is not None and not isinstance(self.right, Integral):
425
+ raise TypeError(f"Expecting right to be an int {suffix}")
426
+ if self.left is None and self.closed in ("left", "both"):
427
+ raise ValueError(
428
+ f"left can't be None when closed == {self.closed} {suffix}"
429
+ )
430
+ if self.right is None and self.closed in ("right", "both"):
431
+ raise ValueError(
432
+ f"right can't be None when closed == {self.closed} {suffix}"
433
+ )
434
+ else:
435
+ if self.left is not None and not isinstance(self.left, Real):
436
+ raise TypeError("Expecting left to be a real number.")
437
+ if self.right is not None and not isinstance(self.right, Real):
438
+ raise TypeError("Expecting right to be a real number.")
439
+
440
+ if self.right is not None and self.left is not None and self.right <= self.left:
441
+ raise ValueError(
442
+ f"right can't be less than left. Got left={self.left} and "
443
+ f"right={self.right}"
444
+ )
445
+
446
+ def __contains__(self, val):
447
+ if np.isnan(val):
448
+ return False
449
+
450
+ left_cmp = operator.lt if self.closed in ("left", "both") else operator.le
451
+ right_cmp = operator.gt if self.closed in ("right", "both") else operator.ge
452
+
453
+ left = -np.inf if self.left is None else self.left
454
+ right = np.inf if self.right is None else self.right
455
+
456
+ if left_cmp(val, left):
457
+ return False
458
+ if right_cmp(val, right):
459
+ return False
460
+ return True
461
+
462
+ def _has_valid_type(self, val):
463
+ if self.type == "real_not_int":
464
+ return isinstance(val, Real) and not isinstance(val, Integral)
465
+ return isinstance(val, self.type)
466
+
467
+ def is_satisfied_by(self, val):
468
+ if not self._has_valid_type(val):
469
+ return False
470
+
471
+ return val in self
472
+
473
+ def __str__(self):
474
+ type_str = "an int" if self.type is Integral else "a float"
475
+ left_bracket = "[" if self.closed in ("left", "both") else "("
476
+ left_bound = "-inf" if self.left is None else self.left
477
+ right_bound = "inf" if self.right is None else self.right
478
+ right_bracket = "]" if self.closed in ("right", "both") else ")"
479
+ return (
480
+ f"{type_str} in the range "
481
+ f"{left_bracket}{left_bound}, {right_bound}{right_bracket}"
482
+ )
483
+
484
+
485
+ class _ArrayLikes(_Constraint):
486
+ """Constraint representing array-likes"""
487
+
488
+ def is_satisfied_by(self, val):
489
+ return _is_arraylike_not_scalar(val)
490
+
491
+ def __str__(self):
492
+ return "an array-like"
493
+
494
+
495
+ class _SparseMatrices(_Constraint):
496
+ """Constraint representing sparse matrices."""
497
+
498
+ def is_satisfied_by(self, val):
499
+ return issparse(val)
500
+
501
+ def __str__(self):
502
+ return "a sparse matrix"
503
+
504
+
505
+ class _Callables(_Constraint):
506
+ """Constraint representing callables."""
507
+
508
+ def is_satisfied_by(self, val):
509
+ return callable(val)
510
+
511
+ def __str__(self):
512
+ return "a callable"
513
+
514
+
515
+ class _RandomStates(_Constraint):
516
+ """Constraint representing random states.
517
+
518
+ Convenience class for
519
+ [Interval(Integral, 0, 2**32 - 1, closed="both"), np.random.RandomState, None]
520
+ """
521
+
522
+ def __init__(self):
523
+ super().__init__()
524
+ self._constraints = [
525
+ Interval(Integral, 0, 2**32 - 1, closed="both"),
526
+ _InstancesOf(np.random.RandomState),
527
+ _NoneConstraint(),
528
+ ]
529
+
530
+ def is_satisfied_by(self, val):
531
+ return any(c.is_satisfied_by(val) for c in self._constraints)
532
+
533
+ def __str__(self):
534
+ return (
535
+ f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
536
+ f" {self._constraints[-1]}"
537
+ )
538
+
539
+
540
+ class _Booleans(_Constraint):
541
+ """Constraint representing boolean likes.
542
+
543
+ Convenience class for
544
+ [bool, np.bool_, Integral (deprecated)]
545
+ """
546
+
547
+ def __init__(self):
548
+ super().__init__()
549
+ self._constraints = [
550
+ _InstancesOf(bool),
551
+ _InstancesOf(np.bool_),
552
+ _InstancesOf(Integral),
553
+ ]
554
+
555
+ def is_satisfied_by(self, val):
556
+ # TODO(1.4) remove support for Integral.
557
+ if isinstance(val, Integral) and not isinstance(val, bool):
558
+ warnings.warn(
559
+ "Passing an int for a boolean parameter is deprecated in version 1.2 "
560
+ "and won't be supported anymore in version 1.4.",
561
+ FutureWarning,
562
+ )
563
+
564
+ return any(c.is_satisfied_by(val) for c in self._constraints)
565
+
566
+ def __str__(self):
567
+ return (
568
+ f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
569
+ f" {self._constraints[-1]}"
570
+ )
571
+
572
+
573
+ class _VerboseHelper(_Constraint):
574
+ """Helper constraint for the verbose parameter.
575
+
576
+ Convenience class for
577
+ [Interval(Integral, 0, None, closed="left"), bool, numpy.bool_]
578
+ """
579
+
580
+ def __init__(self):
581
+ super().__init__()
582
+ self._constraints = [
583
+ Interval(Integral, 0, None, closed="left"),
584
+ _InstancesOf(bool),
585
+ _InstancesOf(np.bool_),
586
+ ]
587
+
588
+ def is_satisfied_by(self, val):
589
+ return any(c.is_satisfied_by(val) for c in self._constraints)
590
+
591
+ def __str__(self):
592
+ return (
593
+ f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
594
+ f" {self._constraints[-1]}"
595
+ )
596
+
597
+
598
+ class _MissingValues(_Constraint):
599
+ """Helper constraint for the `missing_values` parameters.
600
+
601
+ Convenience for
602
+ [
603
+ Integral,
604
+ Interval(Real, None, None, closed="both"),
605
+ str,
606
+ None,
607
+ _NanConstraint(),
608
+ _PandasNAConstraint(),
609
+ ]
610
+ """
611
+
612
+ def __init__(self):
613
+ super().__init__()
614
+ self._constraints = [
615
+ _InstancesOf(Integral),
616
+ # we use an interval of Real to ignore np.nan that has its own constraint
617
+ Interval(Real, None, None, closed="both"),
618
+ _InstancesOf(str),
619
+ _NoneConstraint(),
620
+ _NanConstraint(),
621
+ _PandasNAConstraint(),
622
+ ]
623
+
624
+ def is_satisfied_by(self, val):
625
+ return any(c.is_satisfied_by(val) for c in self._constraints)
626
+
627
+ def __str__(self):
628
+ return (
629
+ f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
630
+ f" {self._constraints[-1]}"
631
+ )
632
+
633
+
634
+ class HasMethods(_Constraint):
635
+ """Constraint representing objects that expose specific methods.
636
+
637
+ It is useful for parameters following a protocol and where we don't want to impose
638
+ an affiliation to a specific module or class.
639
+
640
+ Parameters
641
+ ----------
642
+ methods : str or list of str
643
+ The method(s) that the object is expected to expose.
644
+ """
645
+
646
+ @validate_params({"methods": [str, list]})
647
+ def __init__(self, methods):
648
+ super().__init__()
649
+ if isinstance(methods, str):
650
+ methods = [methods]
651
+ self.methods = methods
652
+
653
+ def is_satisfied_by(self, val):
654
+ return all(callable(getattr(val, method, None)) for method in self.methods)
655
+
656
+ def __str__(self):
657
+ if len(self.methods) == 1:
658
+ methods = f"{self.methods[0]!r}"
659
+ else:
660
+ methods = (
661
+ f"{', '.join([repr(m) for m in self.methods[:-1]])} and"
662
+ f" {self.methods[-1]!r}"
663
+ )
664
+ return f"an object implementing {methods}"
665
+
666
+
667
+ class _IterablesNotString(_Constraint):
668
+ """Constraint representing iterables that are not strings."""
669
+
670
+ def is_satisfied_by(self, val):
671
+ return isinstance(val, Iterable) and not isinstance(val, str)
672
+
673
+ def __str__(self):
674
+ return "an iterable"
675
+
676
+
677
+ class _CVObjects(_Constraint):
678
+ """Constraint representing cv objects.
679
+
680
+ Convenient class for
681
+ [
682
+ Interval(Integral, 2, None, closed="left"),
683
+ HasMethods(["split", "get_n_splits"]),
684
+ _IterablesNotString(),
685
+ None,
686
+ ]
687
+ """
688
+
689
+ def __init__(self):
690
+ super().__init__()
691
+ self._constraints = [
692
+ Interval(Integral, 2, None, closed="left"),
693
+ HasMethods(["split", "get_n_splits"]),
694
+ _IterablesNotString(),
695
+ _NoneConstraint(),
696
+ ]
697
+
698
+ def is_satisfied_by(self, val):
699
+ return any(c.is_satisfied_by(val) for c in self._constraints)
700
+
701
+ def __str__(self):
702
+ return (
703
+ f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
704
+ f" {self._constraints[-1]}"
705
+ )
706
+
707
+
708
+ class Hidden:
709
+ """Class encapsulating a constraint not meant to be exposed to the user.
710
+
711
+ Parameters
712
+ ----------
713
+ constraint : str or _Constraint instance
714
+ The constraint to be used internally.
715
+ """
716
+
717
+ def __init__(self, constraint):
718
+ self.constraint = constraint
719
+
720
+
721
+ def generate_invalid_param_val(constraint, constraints=None):
722
+ """Return a value that does not satisfy the constraint.
723
+
724
+ Raises a NotImplementedError if there exists no invalid value for this constraint.
725
+
726
+ This is only useful for testing purpose.
727
+
728
+ Parameters
729
+ ----------
730
+ constraint : _Constraint instance
731
+ The constraint to generate a value for.
732
+
733
+ constraints : list of _Constraint instances or None, default=None
734
+ The list of all constraints for this parameter. If None, the list only
735
+ containing `constraint` is used.
736
+
737
+ Returns
738
+ -------
739
+ val : object
740
+ A value that does not satisfy the constraint.
741
+ """
742
+ if isinstance(constraint, StrOptions):
743
+ return f"not {' or '.join(constraint.options)}"
744
+
745
+ if isinstance(constraint, _MissingValues):
746
+ return np.array([1, 2, 3])
747
+
748
+ if isinstance(constraint, _VerboseHelper):
749
+ return -1
750
+
751
+ if isinstance(constraint, HasMethods):
752
+ return type("HasNotMethods", (), {})()
753
+
754
+ if isinstance(constraint, _IterablesNotString):
755
+ return "a string"
756
+
757
+ if isinstance(constraint, _CVObjects):
758
+ return "not a cv object"
759
+
760
+ if not isinstance(constraint, Interval):
761
+ raise NotImplementedError
762
+
763
+ # constraint is an interval
764
+ constraints = [constraint] if constraints is None else constraints
765
+ return _generate_invalid_param_val_interval(constraint, constraints)
766
+
767
+
768
+ def _generate_invalid_param_val_interval(interval, constraints):
769
+ """Return a value that does not satisfy an interval constraint.
770
+
771
+ Generating an invalid value for an integer interval depends on the other constraints
772
+ since an int is a real, meaning that it can be valid for a real interval.
773
+ Assumes that there can be at most 2 interval constraints: one integer interval
774
+ and/or one real interval.
775
+
776
+ This is only useful for testing purpose.
777
+
778
+ Parameters
779
+ ----------
780
+ interval : Interval instance
781
+ The interval to generate a value for.
782
+
783
+ constraints : list of _Constraint instances
784
+ The list of all constraints for this parameter.
785
+
786
+ Returns
787
+ -------
788
+ val : object
789
+ A value that does not satisfy the interval constraint.
790
+ """
791
+ if interval.type is Real:
792
+ # generate a non-integer value such that it can't be valid even if there's also
793
+ # an integer interval constraint.
794
+ if interval.left is None and interval.right is None:
795
+ if interval.closed in ("left", "neither"):
796
+ return np.inf
797
+ elif interval.closed in ("right", "neither"):
798
+ return -np.inf
799
+ else:
800
+ raise NotImplementedError
801
+
802
+ if interval.left is not None:
803
+ return np.floor(interval.left) - 0.5
804
+ else: # right is not None
805
+ return np.ceil(interval.right) + 0.5
806
+
807
+ else: # interval.type is Integral
808
+ if interval.left is None and interval.right is None:
809
+ raise NotImplementedError
810
+
811
+ # We need to check if there's also a real interval constraint to generate a
812
+ # value that is not valid for any of the 2 interval constraints.
813
+ real_intervals = [
814
+ i for i in constraints if isinstance(i, Interval) and i.type is Real
815
+ ]
816
+ real_interval = real_intervals[0] if real_intervals else None
817
+
818
+ if real_interval is None:
819
+ # Only the integer interval constraint -> easy
820
+ if interval.left is not None:
821
+ return interval.left - 1
822
+ else: # interval.right is not None
823
+ return interval.right + 1
824
+
825
+ # There's also a real interval constraint. Try to find a value left to both or
826
+ # right to both or in between them.
827
+
828
+ # redefine left and right bounds to be smallest and largest valid integers in
829
+ # both intervals.
830
+ int_left = interval.left
831
+ if int_left is not None and interval.closed in ("right", "neither"):
832
+ int_left = int_left + 1
833
+
834
+ int_right = interval.right
835
+ if int_right is not None and interval.closed in ("left", "neither"):
836
+ int_right = int_right - 1
837
+
838
+ real_left = real_interval.left
839
+ if real_interval.left is not None:
840
+ real_left = int(np.ceil(real_interval.left))
841
+ if real_interval.closed in ("right", "neither"):
842
+ real_left = real_left + 1
843
+
844
+ real_right = real_interval.right
845
+ if real_interval.right is not None:
846
+ real_right = int(np.floor(real_interval.right))
847
+ if real_interval.closed in ("left", "neither"):
848
+ real_right = real_right - 1
849
+
850
+ if int_left is not None and real_left is not None:
851
+ # there exists an int left to both intervals
852
+ return min(int_left, real_left) - 1
853
+
854
+ if int_right is not None and real_right is not None:
855
+ # there exists an int right to both intervals
856
+ return max(int_right, real_right) + 1
857
+
858
+ if int_left is not None:
859
+ if real_right is not None and int_left - real_right >= 2:
860
+ # there exists an int between the 2 intervals
861
+ return int_left - 1
862
+ else:
863
+ raise NotImplementedError
864
+ else: # int_right is not None
865
+ if real_left is not None and real_left - int_right >= 2:
866
+ # there exists an int between the 2 intervals
867
+ return int_right + 1
868
+ else:
869
+ raise NotImplementedError
870
+
871
+
872
+ def generate_valid_param(constraint):
873
+ """Return a value that does satisfy a constraint.
874
+
875
+ This is only useful for testing purpose.
876
+
877
+ Parameters
878
+ ----------
879
+ constraint : Constraint instance
880
+ The constraint to generate a value for.
881
+
882
+ Returns
883
+ -------
884
+ val : object
885
+ A value that does satisfy the constraint.
886
+ """
887
+ if isinstance(constraint, _ArrayLikes):
888
+ return np.array([1, 2, 3])
889
+
890
+ if isinstance(constraint, _SparseMatrices):
891
+ return csr_matrix([[0, 1], [1, 0]])
892
+
893
+ if isinstance(constraint, _RandomStates):
894
+ return np.random.RandomState(42)
895
+
896
+ if isinstance(constraint, _Callables):
897
+ return lambda x: x
898
+
899
+ if isinstance(constraint, _NoneConstraint):
900
+ return None
901
+
902
+ if isinstance(constraint, _InstancesOf):
903
+ return constraint.type()
904
+
905
+ if isinstance(constraint, _Booleans):
906
+ return True
907
+
908
+ if isinstance(constraint, _VerboseHelper):
909
+ return 1
910
+
911
+ if isinstance(constraint, _MissingValues):
912
+ return np.nan
913
+
914
+ if isinstance(constraint, HasMethods):
915
+ return type(
916
+ "ValidHasMethods", (), {m: lambda self: None for m in constraint.methods}
917
+ )()
918
+
919
+ if isinstance(constraint, _IterablesNotString):
920
+ return [1, 2, 3]
921
+
922
+ if isinstance(constraint, _CVObjects):
923
+ return 5
924
+
925
+ if isinstance(constraint, Options): # includes StrOptions
926
+ for option in constraint.options:
927
+ return option
928
+
929
+ if isinstance(constraint, Interval):
930
+ interval = constraint
931
+ if interval.left is None and interval.right is None:
932
+ return 0
933
+ elif interval.left is None:
934
+ return interval.right - 1
935
+ elif interval.right is None:
936
+ return interval.left + 1
937
+ else:
938
+ if interval.type is Real:
939
+ return (interval.left + interval.right) / 2
940
+ else:
941
+ return interval.left + 1
942
+
943
+ raise ValueError(f"Unknown constraint type: {constraint}")
videollama2/lib/python3.10/site-packages/sklearn/utils/_random.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a9c4f5f42a71d5792e4b1f8abd4f21f4bec97f97760346667faa773f35b1070a
3
+ size 109121
videollama2/lib/python3.10/site-packages/sklearn/utils/_readonly_array_wrapper.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de92483727ba785a6a37bf6d157763cf5e743f632437bcbf25d8a5d81448a8f4
3
+ size 237217
videollama2/lib/python3.10/site-packages/sklearn/utils/_seq_dataset.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:41af9dbb90669834261523880b5bbb692b99d301148fa010b3eed979e8c99303
3
+ size 158369
videollama2/lib/python3.10/site-packages/sklearn/utils/_show_versions.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility methods to print system info for debugging
3
+
4
+ adapted from :func:`pandas.show_versions`
5
+ """
6
+ # License: BSD 3 clause
7
+
8
+ import platform
9
+ import sys
10
+ from ..utils.fixes import threadpool_info
11
+ from .. import __version__
12
+
13
+
14
+ from ._openmp_helpers import _openmp_parallelism_enabled
15
+
16
+
17
+ def _get_sys_info():
18
+ """System information
19
+
20
+ Returns
21
+ -------
22
+ sys_info : dict
23
+ system and Python version information
24
+
25
+ """
26
+ python = sys.version.replace("\n", " ")
27
+
28
+ blob = [
29
+ ("python", python),
30
+ ("executable", sys.executable),
31
+ ("machine", platform.platform()),
32
+ ]
33
+
34
+ return dict(blob)
35
+
36
+
37
+ def _get_deps_info():
38
+ """Overview of the installed version of main dependencies
39
+
40
+ This function does not import the modules to collect the version numbers
41
+ but instead relies on standard Python package metadata.
42
+
43
+ Returns
44
+ -------
45
+ deps_info: dict
46
+ version information on relevant Python libraries
47
+
48
+ """
49
+ deps = [
50
+ "pip",
51
+ "setuptools",
52
+ "numpy",
53
+ "scipy",
54
+ "Cython",
55
+ "pandas",
56
+ "matplotlib",
57
+ "joblib",
58
+ "threadpoolctl",
59
+ ]
60
+
61
+ deps_info = {
62
+ "sklearn": __version__,
63
+ }
64
+
65
+ from importlib.metadata import version, PackageNotFoundError
66
+
67
+ for modname in deps:
68
+ try:
69
+ deps_info[modname] = version(modname)
70
+ except PackageNotFoundError:
71
+ deps_info[modname] = None
72
+ return deps_info
73
+
74
+
75
+ def show_versions():
76
+ """Print useful debugging information"
77
+
78
+ .. versionadded:: 0.20
79
+ """
80
+
81
+ sys_info = _get_sys_info()
82
+ deps_info = _get_deps_info()
83
+
84
+ print("\nSystem:")
85
+ for k, stat in sys_info.items():
86
+ print("{k:>10}: {stat}".format(k=k, stat=stat))
87
+
88
+ print("\nPython dependencies:")
89
+ for k, stat in deps_info.items():
90
+ print("{k:>13}: {stat}".format(k=k, stat=stat))
91
+
92
+ print(
93
+ "\n{k}: {stat}".format(
94
+ k="Built with OpenMP", stat=_openmp_parallelism_enabled()
95
+ )
96
+ )
97
+
98
+ # show threadpoolctl results
99
+ threadpool_results = threadpool_info()
100
+ if threadpool_results:
101
+ print()
102
+ print("threadpoolctl info:")
103
+
104
+ for i, result in enumerate(threadpool_results):
105
+ for key, val in result.items():
106
+ print(f"{key:>15}: {val}")
107
+ if i != len(threadpool_results) - 1:
108
+ print()
videollama2/lib/python3.10/site-packages/sklearn/utils/_sorting.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (38.6 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/utils/_tags.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ _DEFAULT_TAGS = {
4
+ "non_deterministic": False,
5
+ "requires_positive_X": False,
6
+ "requires_positive_y": False,
7
+ "X_types": ["2darray"],
8
+ "poor_score": False,
9
+ "no_validation": False,
10
+ "multioutput": False,
11
+ "allow_nan": False,
12
+ "stateless": False,
13
+ "multilabel": False,
14
+ "_skip_test": False,
15
+ "_xfail_checks": False,
16
+ "multioutput_only": False,
17
+ "binary_only": False,
18
+ "requires_fit": True,
19
+ "preserves_dtype": [np.float64],
20
+ "requires_y": False,
21
+ "pairwise": False,
22
+ }
23
+
24
+
25
+ def _safe_tags(estimator, key=None):
26
+ """Safely get estimator tags.
27
+
28
+ :class:`~sklearn.BaseEstimator` provides the estimator tags machinery.
29
+ However, if an estimator does not inherit from this base class, we should
30
+ fall-back to the default tags.
31
+
32
+ For scikit-learn built-in estimators, we should still rely on
33
+ `self._get_tags()`. `_safe_tags(est)` should be used when we are not sure
34
+ where `est` comes from: typically `_safe_tags(self.base_estimator)` where
35
+ `self` is a meta-estimator, or in the common checks.
36
+
37
+ Parameters
38
+ ----------
39
+ estimator : estimator object
40
+ The estimator from which to get the tag.
41
+
42
+ key : str, default=None
43
+ Tag name to get. By default (`None`), all tags are returned.
44
+
45
+ Returns
46
+ -------
47
+ tags : dict or tag value
48
+ The estimator tags. A single value is returned if `key` is not None.
49
+ """
50
+ if hasattr(estimator, "_get_tags"):
51
+ tags_provider = "_get_tags()"
52
+ tags = estimator._get_tags()
53
+ elif hasattr(estimator, "_more_tags"):
54
+ tags_provider = "_more_tags()"
55
+ tags = {**_DEFAULT_TAGS, **estimator._more_tags()}
56
+ else:
57
+ tags_provider = "_DEFAULT_TAGS"
58
+ tags = _DEFAULT_TAGS
59
+
60
+ if key is not None:
61
+ if key not in tags:
62
+ raise ValueError(
63
+ f"The key {key} is not defined in {tags_provider} for the "
64
+ f"class {estimator.__class__.__name__}."
65
+ )
66
+ return tags[key]
67
+ return tags
videollama2/lib/python3.10/site-packages/sklearn/utils/_testing.py ADDED
@@ -0,0 +1,1057 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Testing utilities."""
2
+
3
+ # Copyright (c) 2011, 2012
4
+ # Authors: Pietro Berkes,
5
+ # Andreas Muller
6
+ # Mathieu Blondel
7
+ # Olivier Grisel
8
+ # Arnaud Joly
9
+ # Denis Engemann
10
+ # Giorgio Patrini
11
+ # Thierry Guillemot
12
+ # License: BSD 3 clause
13
+ import os
14
+ import os.path as op
15
+ import inspect
16
+ import warnings
17
+ import sys
18
+ import functools
19
+ import tempfile
20
+ from subprocess import check_output, STDOUT, CalledProcessError
21
+ from subprocess import TimeoutExpired
22
+ import re
23
+ import contextlib
24
+ from collections.abc import Iterable
25
+ from collections.abc import Sequence
26
+
27
+ import scipy as sp
28
+ from functools import wraps
29
+ from inspect import signature
30
+
31
+ import shutil
32
+ import atexit
33
+ import unittest
34
+ from unittest import TestCase
35
+
36
+ # WindowsError only exist on Windows
37
+ try:
38
+ WindowsError # type: ignore
39
+ except NameError:
40
+ WindowsError = None
41
+
42
+ from numpy.testing import assert_allclose as np_assert_allclose
43
+ from numpy.testing import assert_almost_equal
44
+ from numpy.testing import assert_approx_equal
45
+ from numpy.testing import assert_array_equal
46
+ from numpy.testing import assert_array_almost_equal
47
+ from numpy.testing import assert_array_less
48
+ import numpy as np
49
+ import joblib
50
+
51
+ import sklearn
52
+ from sklearn.utils import (
53
+ IS_PYPY,
54
+ _IS_32BIT,
55
+ _in_unstable_openblas_configuration,
56
+ )
57
+ from sklearn.utils.multiclass import check_classification_targets
58
+ from sklearn.utils.validation import (
59
+ check_array,
60
+ check_is_fitted,
61
+ check_X_y,
62
+ )
63
+ from sklearn.utils.fixes import threadpool_info
64
+
65
+
66
+ __all__ = [
67
+ "assert_raises",
68
+ "assert_raises_regexp",
69
+ "assert_array_equal",
70
+ "assert_almost_equal",
71
+ "assert_array_almost_equal",
72
+ "assert_array_less",
73
+ "assert_approx_equal",
74
+ "assert_allclose",
75
+ "assert_run_python_script",
76
+ "SkipTest",
77
+ ]
78
+
79
+ _dummy = TestCase("__init__")
80
+ assert_raises = _dummy.assertRaises
81
+ SkipTest = unittest.case.SkipTest
82
+ assert_dict_equal = _dummy.assertDictEqual
83
+
84
+ assert_raises_regex = _dummy.assertRaisesRegex
85
+ # assert_raises_regexp is deprecated in Python 3.4 in favor of
86
+ # assert_raises_regex but lets keep the backward compat in scikit-learn with
87
+ # the old name for now
88
+ assert_raises_regexp = assert_raises_regex
89
+
90
+
91
+ # To remove when we support numpy 1.7
92
+ def assert_no_warnings(func, *args, **kw):
93
+ """
94
+ Parameters
95
+ ----------
96
+ func
97
+ *args
98
+ **kw
99
+ """
100
+ # very important to avoid uncontrolled state propagation
101
+ with warnings.catch_warnings(record=True) as w:
102
+ warnings.simplefilter("always")
103
+
104
+ result = func(*args, **kw)
105
+ if hasattr(np, "FutureWarning"):
106
+ # Filter out numpy-specific warnings in numpy >= 1.9
107
+ w = [e for e in w if e.category is not np.VisibleDeprecationWarning]
108
+
109
+ if len(w) > 0:
110
+ raise AssertionError(
111
+ "Got warnings when calling %s: [%s]"
112
+ % (func.__name__, ", ".join(str(warning) for warning in w))
113
+ )
114
+ return result
115
+
116
+
117
+ def ignore_warnings(obj=None, category=Warning):
118
+ """Context manager and decorator to ignore warnings.
119
+
120
+ Note: Using this (in both variants) will clear all warnings
121
+ from all python modules loaded. In case you need to test
122
+ cross-module-warning-logging, this is not your tool of choice.
123
+
124
+ Parameters
125
+ ----------
126
+ obj : callable, default=None
127
+ callable where you want to ignore the warnings.
128
+ category : warning class, default=Warning
129
+ The category to filter. If Warning, all categories will be muted.
130
+
131
+ Examples
132
+ --------
133
+ >>> import warnings
134
+ >>> from sklearn.utils._testing import ignore_warnings
135
+ >>> with ignore_warnings():
136
+ ... warnings.warn('buhuhuhu')
137
+
138
+ >>> def nasty_warn():
139
+ ... warnings.warn('buhuhuhu')
140
+ ... print(42)
141
+
142
+ >>> ignore_warnings(nasty_warn)()
143
+ 42
144
+ """
145
+ if isinstance(obj, type) and issubclass(obj, Warning):
146
+ # Avoid common pitfall of passing category as the first positional
147
+ # argument which result in the test not being run
148
+ warning_name = obj.__name__
149
+ raise ValueError(
150
+ "'obj' should be a callable where you want to ignore warnings. "
151
+ "You passed a warning class instead: 'obj={warning_name}'. "
152
+ "If you want to pass a warning class to ignore_warnings, "
153
+ "you should use 'category={warning_name}'".format(warning_name=warning_name)
154
+ )
155
+ elif callable(obj):
156
+ return _IgnoreWarnings(category=category)(obj)
157
+ else:
158
+ return _IgnoreWarnings(category=category)
159
+
160
+
161
+ class _IgnoreWarnings:
162
+ """Improved and simplified Python warnings context manager and decorator.
163
+
164
+ This class allows the user to ignore the warnings raised by a function.
165
+ Copied from Python 2.7.5 and modified as required.
166
+
167
+ Parameters
168
+ ----------
169
+ category : tuple of warning class, default=Warning
170
+ The category to filter. By default, all the categories will be muted.
171
+
172
+ """
173
+
174
+ def __init__(self, category):
175
+ self._record = True
176
+ self._module = sys.modules["warnings"]
177
+ self._entered = False
178
+ self.log = []
179
+ self.category = category
180
+
181
+ def __call__(self, fn):
182
+ """Decorator to catch and hide warnings without visual nesting."""
183
+
184
+ @wraps(fn)
185
+ def wrapper(*args, **kwargs):
186
+ with warnings.catch_warnings():
187
+ warnings.simplefilter("ignore", self.category)
188
+ return fn(*args, **kwargs)
189
+
190
+ return wrapper
191
+
192
+ def __repr__(self):
193
+ args = []
194
+ if self._record:
195
+ args.append("record=True")
196
+ if self._module is not sys.modules["warnings"]:
197
+ args.append("module=%r" % self._module)
198
+ name = type(self).__name__
199
+ return "%s(%s)" % (name, ", ".join(args))
200
+
201
+ def __enter__(self):
202
+ if self._entered:
203
+ raise RuntimeError("Cannot enter %r twice" % self)
204
+ self._entered = True
205
+ self._filters = self._module.filters
206
+ self._module.filters = self._filters[:]
207
+ self._showwarning = self._module.showwarning
208
+ warnings.simplefilter("ignore", self.category)
209
+
210
+ def __exit__(self, *exc_info):
211
+ if not self._entered:
212
+ raise RuntimeError("Cannot exit %r without entering first" % self)
213
+ self._module.filters = self._filters
214
+ self._module.showwarning = self._showwarning
215
+ self.log[:] = []
216
+
217
+
218
+ def assert_raise_message(exceptions, message, function, *args, **kwargs):
219
+ """Helper function to test the message raised in an exception.
220
+
221
+ Given an exception, a callable to raise the exception, and
222
+ a message string, tests that the correct exception is raised and
223
+ that the message is a substring of the error thrown. Used to test
224
+ that the specific message thrown during an exception is correct.
225
+
226
+ Parameters
227
+ ----------
228
+ exceptions : exception or tuple of exception
229
+ An Exception object.
230
+
231
+ message : str
232
+ The error message or a substring of the error message.
233
+
234
+ function : callable
235
+ Callable object to raise error.
236
+
237
+ *args : the positional arguments to `function`.
238
+
239
+ **kwargs : the keyword arguments to `function`.
240
+ """
241
+ try:
242
+ function(*args, **kwargs)
243
+ except exceptions as e:
244
+ error_message = str(e)
245
+ if message not in error_message:
246
+ raise AssertionError(
247
+ "Error message does not include the expected"
248
+ " string: %r. Observed error message: %r" % (message, error_message)
249
+ )
250
+ else:
251
+ # concatenate exception names
252
+ if isinstance(exceptions, tuple):
253
+ names = " or ".join(e.__name__ for e in exceptions)
254
+ else:
255
+ names = exceptions.__name__
256
+
257
+ raise AssertionError("%s not raised by %s" % (names, function.__name__))
258
+
259
+
260
+ def assert_allclose(
261
+ actual, desired, rtol=None, atol=0.0, equal_nan=True, err_msg="", verbose=True
262
+ ):
263
+ """dtype-aware variant of numpy.testing.assert_allclose
264
+
265
+ This variant introspects the least precise floating point dtype
266
+ in the input argument and automatically sets the relative tolerance
267
+ parameter to 1e-4 float32 and use 1e-7 otherwise (typically float64
268
+ in scikit-learn).
269
+
270
+ `atol` is always left to 0. by default. It should be adjusted manually
271
+ to an assertion-specific value in case there are null values expected
272
+ in `desired`.
273
+
274
+ The aggregate tolerance is `atol + rtol * abs(desired)`.
275
+
276
+ Parameters
277
+ ----------
278
+ actual : array_like
279
+ Array obtained.
280
+ desired : array_like
281
+ Array desired.
282
+ rtol : float, optional, default=None
283
+ Relative tolerance.
284
+ If None, it is set based on the provided arrays' dtypes.
285
+ atol : float, optional, default=0.
286
+ Absolute tolerance.
287
+ equal_nan : bool, optional, default=True
288
+ If True, NaNs will compare equal.
289
+ err_msg : str, optional, default=''
290
+ The error message to be printed in case of failure.
291
+ verbose : bool, optional, default=True
292
+ If True, the conflicting values are appended to the error message.
293
+
294
+ Raises
295
+ ------
296
+ AssertionError
297
+ If actual and desired are not equal up to specified precision.
298
+
299
+ See Also
300
+ --------
301
+ numpy.testing.assert_allclose
302
+
303
+ Examples
304
+ --------
305
+ >>> import numpy as np
306
+ >>> from sklearn.utils._testing import assert_allclose
307
+ >>> x = [1e-5, 1e-3, 1e-1]
308
+ >>> y = np.arccos(np.cos(x))
309
+ >>> assert_allclose(x, y, rtol=1e-5, atol=0)
310
+ >>> a = np.full(shape=10, fill_value=1e-5, dtype=np.float32)
311
+ >>> assert_allclose(a, 1e-5)
312
+ """
313
+ dtypes = []
314
+
315
+ actual, desired = np.asanyarray(actual), np.asanyarray(desired)
316
+ dtypes = [actual.dtype, desired.dtype]
317
+
318
+ if rtol is None:
319
+ rtols = [1e-4 if dtype == np.float32 else 1e-7 for dtype in dtypes]
320
+ rtol = max(rtols)
321
+
322
+ np_assert_allclose(
323
+ actual,
324
+ desired,
325
+ rtol=rtol,
326
+ atol=atol,
327
+ equal_nan=equal_nan,
328
+ err_msg=err_msg,
329
+ verbose=verbose,
330
+ )
331
+
332
+
333
+ def assert_allclose_dense_sparse(x, y, rtol=1e-07, atol=1e-9, err_msg=""):
334
+ """Assert allclose for sparse and dense data.
335
+
336
+ Both x and y need to be either sparse or dense, they
337
+ can't be mixed.
338
+
339
+ Parameters
340
+ ----------
341
+ x : {array-like, sparse matrix}
342
+ First array to compare.
343
+
344
+ y : {array-like, sparse matrix}
345
+ Second array to compare.
346
+
347
+ rtol : float, default=1e-07
348
+ relative tolerance; see numpy.allclose.
349
+
350
+ atol : float, default=1e-9
351
+ absolute tolerance; see numpy.allclose. Note that the default here is
352
+ more tolerant than the default for numpy.testing.assert_allclose, where
353
+ atol=0.
354
+
355
+ err_msg : str, default=''
356
+ Error message to raise.
357
+ """
358
+ if sp.sparse.issparse(x) and sp.sparse.issparse(y):
359
+ x = x.tocsr()
360
+ y = y.tocsr()
361
+ x.sum_duplicates()
362
+ y.sum_duplicates()
363
+ assert_array_equal(x.indices, y.indices, err_msg=err_msg)
364
+ assert_array_equal(x.indptr, y.indptr, err_msg=err_msg)
365
+ assert_allclose(x.data, y.data, rtol=rtol, atol=atol, err_msg=err_msg)
366
+ elif not sp.sparse.issparse(x) and not sp.sparse.issparse(y):
367
+ # both dense
368
+ assert_allclose(x, y, rtol=rtol, atol=atol, err_msg=err_msg)
369
+ else:
370
+ raise ValueError(
371
+ "Can only compare two sparse matrices, not a sparse matrix and an array."
372
+ )
373
+
374
+
375
+ def set_random_state(estimator, random_state=0):
376
+ """Set random state of an estimator if it has the `random_state` param.
377
+
378
+ Parameters
379
+ ----------
380
+ estimator : object
381
+ The estimator.
382
+ random_state : int, RandomState instance or None, default=0
383
+ Pseudo random number generator state.
384
+ Pass an int for reproducible results across multiple function calls.
385
+ See :term:`Glossary <random_state>`.
386
+ """
387
+ if "random_state" in estimator.get_params():
388
+ estimator.set_params(random_state=random_state)
389
+
390
+
391
+ try:
392
+ import pytest
393
+
394
+ skip_if_32bit = pytest.mark.skipif(_IS_32BIT, reason="skipped on 32bit platforms")
395
+ fails_if_pypy = pytest.mark.xfail(IS_PYPY, reason="not compatible with PyPy")
396
+ fails_if_unstable_openblas = pytest.mark.xfail(
397
+ _in_unstable_openblas_configuration(),
398
+ reason="OpenBLAS is unstable for this configuration",
399
+ )
400
+ skip_if_no_parallel = pytest.mark.skipif(
401
+ not joblib.parallel.mp, reason="joblib is in serial mode"
402
+ )
403
+
404
+ # Decorator for tests involving both BLAS calls and multiprocessing.
405
+ #
406
+ # Under POSIX (e.g. Linux or OSX), using multiprocessing in conjunction
407
+ # with some implementation of BLAS (or other libraries that manage an
408
+ # internal posix thread pool) can cause a crash or a freeze of the Python
409
+ # process.
410
+ #
411
+ # In practice all known packaged distributions (from Linux distros or
412
+ # Anaconda) of BLAS under Linux seems to be safe. So we this problem seems
413
+ # to only impact OSX users.
414
+ #
415
+ # This wrapper makes it possible to skip tests that can possibly cause
416
+ # this crash under OS X with.
417
+ #
418
+ # Under Python 3.4+ it is possible to use the `forkserver` start method
419
+ # for multiprocessing to avoid this issue. However it can cause pickling
420
+ # errors on interactively defined functions. It therefore not enabled by
421
+ # default.
422
+
423
+ if_safe_multiprocessing_with_blas = pytest.mark.skipif(
424
+ sys.platform == "darwin", reason="Possible multi-process bug with some BLAS"
425
+ )
426
+ except ImportError:
427
+ pass
428
+
429
+
430
+ def check_skip_network():
431
+ if int(os.environ.get("SKLEARN_SKIP_NETWORK_TESTS", 0)):
432
+ raise SkipTest("Text tutorial requires large dataset download")
433
+
434
+
435
+ def _delete_folder(folder_path, warn=False):
436
+ """Utility function to cleanup a temporary folder if still existing.
437
+
438
+ Copy from joblib.pool (for independence).
439
+ """
440
+ try:
441
+ if os.path.exists(folder_path):
442
+ # This can fail under windows,
443
+ # but will succeed when called by atexit
444
+ shutil.rmtree(folder_path)
445
+ except WindowsError:
446
+ if warn:
447
+ warnings.warn("Could not delete temporary folder %s" % folder_path)
448
+
449
+
450
+ class TempMemmap:
451
+ """
452
+ Parameters
453
+ ----------
454
+ data
455
+ mmap_mode : str, default='r'
456
+ """
457
+
458
+ def __init__(self, data, mmap_mode="r"):
459
+ self.mmap_mode = mmap_mode
460
+ self.data = data
461
+
462
+ def __enter__(self):
463
+ data_read_only, self.temp_folder = create_memmap_backed_data(
464
+ self.data, mmap_mode=self.mmap_mode, return_folder=True
465
+ )
466
+ return data_read_only
467
+
468
+ def __exit__(self, exc_type, exc_val, exc_tb):
469
+ _delete_folder(self.temp_folder)
470
+
471
+
472
+ def _create_memmap_backed_array(array, filename, mmap_mode):
473
+ # https://numpy.org/doc/stable/reference/generated/numpy.memmap.html
474
+ fp = np.memmap(filename, dtype=array.dtype, mode="w+", shape=array.shape)
475
+ fp[:] = array[:] # write array to memmap array
476
+ fp.flush()
477
+ memmap_backed_array = np.memmap(
478
+ filename, dtype=array.dtype, mode=mmap_mode, shape=array.shape
479
+ )
480
+ return memmap_backed_array
481
+
482
+
483
+ def _create_aligned_memmap_backed_arrays(data, mmap_mode, folder):
484
+ if isinstance(data, np.ndarray):
485
+ filename = op.join(folder, "data.dat")
486
+ return _create_memmap_backed_array(data, filename, mmap_mode)
487
+
488
+ if isinstance(data, Sequence) and all(
489
+ isinstance(each, np.ndarray) for each in data
490
+ ):
491
+ return [
492
+ _create_memmap_backed_array(
493
+ array, op.join(folder, f"data{index}.dat"), mmap_mode
494
+ )
495
+ for index, array in enumerate(data)
496
+ ]
497
+
498
+ raise ValueError(
499
+ "When creating aligned memmap-backed arrays, input must be a single array or a"
500
+ " sequence of arrays"
501
+ )
502
+
503
+
504
+ def create_memmap_backed_data(data, mmap_mode="r", return_folder=False, aligned=False):
505
+ """
506
+ Parameters
507
+ ----------
508
+ data
509
+ mmap_mode : str, default='r'
510
+ return_folder : bool, default=False
511
+ aligned : bool, default=False
512
+ If True, if input is a single numpy array and if the input array is aligned,
513
+ the memory mapped array will also be aligned. This is a workaround for
514
+ https://github.com/joblib/joblib/issues/563.
515
+ """
516
+ temp_folder = tempfile.mkdtemp(prefix="sklearn_testing_")
517
+ atexit.register(functools.partial(_delete_folder, temp_folder, warn=True))
518
+ # OpenBLAS is known to segfault with unaligned data on the Prescott
519
+ # architecture so force aligned=True on Prescott. For more details, see:
520
+ # https://github.com/scipy/scipy/issues/14886
521
+ has_prescott_openblas = any(
522
+ True
523
+ for info in threadpool_info()
524
+ if info["internal_api"] == "openblas"
525
+ # Prudently assume Prescott might be the architecture if it is unknown.
526
+ and info.get("architecture", "prescott").lower() == "prescott"
527
+ )
528
+ if has_prescott_openblas:
529
+ aligned = True
530
+
531
+ if aligned:
532
+ memmap_backed_data = _create_aligned_memmap_backed_arrays(
533
+ data, mmap_mode, temp_folder
534
+ )
535
+ else:
536
+ filename = op.join(temp_folder, "data.pkl")
537
+ joblib.dump(data, filename)
538
+ memmap_backed_data = joblib.load(filename, mmap_mode=mmap_mode)
539
+ result = (
540
+ memmap_backed_data if not return_folder else (memmap_backed_data, temp_folder)
541
+ )
542
+ return result
543
+
544
+
545
+ # Utils to test docstrings
546
+
547
+
548
+ def _get_args(function, varargs=False):
549
+ """Helper to get function arguments."""
550
+
551
+ try:
552
+ params = signature(function).parameters
553
+ except ValueError:
554
+ # Error on builtin C function
555
+ return []
556
+ args = [
557
+ key
558
+ for key, param in params.items()
559
+ if param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)
560
+ ]
561
+ if varargs:
562
+ varargs = [
563
+ param.name
564
+ for param in params.values()
565
+ if param.kind == param.VAR_POSITIONAL
566
+ ]
567
+ if len(varargs) == 0:
568
+ varargs = None
569
+ return args, varargs
570
+ else:
571
+ return args
572
+
573
+
574
+ def _get_func_name(func):
575
+ """Get function full name.
576
+
577
+ Parameters
578
+ ----------
579
+ func : callable
580
+ The function object.
581
+
582
+ Returns
583
+ -------
584
+ name : str
585
+ The function name.
586
+ """
587
+ parts = []
588
+ module = inspect.getmodule(func)
589
+ if module:
590
+ parts.append(module.__name__)
591
+
592
+ qualname = func.__qualname__
593
+ if qualname != func.__name__:
594
+ parts.append(qualname[: qualname.find(".")])
595
+
596
+ parts.append(func.__name__)
597
+ return ".".join(parts)
598
+
599
+
600
+ def check_docstring_parameters(func, doc=None, ignore=None):
601
+ """Helper to check docstring.
602
+
603
+ Parameters
604
+ ----------
605
+ func : callable
606
+ The function object to test.
607
+ doc : str, default=None
608
+ Docstring if it is passed manually to the test.
609
+ ignore : list, default=None
610
+ Parameters to ignore.
611
+
612
+ Returns
613
+ -------
614
+ incorrect : list
615
+ A list of string describing the incorrect results.
616
+ """
617
+ from numpydoc import docscrape
618
+
619
+ incorrect = []
620
+ ignore = [] if ignore is None else ignore
621
+
622
+ func_name = _get_func_name(func)
623
+ if not func_name.startswith("sklearn.") or func_name.startswith(
624
+ "sklearn.externals"
625
+ ):
626
+ return incorrect
627
+ # Don't check docstring for property-functions
628
+ if inspect.isdatadescriptor(func):
629
+ return incorrect
630
+ # Don't check docstring for setup / teardown pytest functions
631
+ if func_name.split(".")[-1] in ("setup_module", "teardown_module"):
632
+ return incorrect
633
+ # Dont check estimator_checks module
634
+ if func_name.split(".")[2] == "estimator_checks":
635
+ return incorrect
636
+ # Get the arguments from the function signature
637
+ param_signature = list(filter(lambda x: x not in ignore, _get_args(func)))
638
+ # drop self
639
+ if len(param_signature) > 0 and param_signature[0] == "self":
640
+ param_signature.remove("self")
641
+
642
+ # Analyze function's docstring
643
+ if doc is None:
644
+ records = []
645
+ with warnings.catch_warnings(record=True):
646
+ warnings.simplefilter("error", UserWarning)
647
+ try:
648
+ doc = docscrape.FunctionDoc(func)
649
+ except UserWarning as exp:
650
+ if "potentially wrong underline length" in str(exp):
651
+ # Catch warning raised as of numpydoc 1.2 when
652
+ # the underline length for a section of a docstring
653
+ # is not consistent.
654
+ message = str(exp).split("\n")[:3]
655
+ incorrect += [f"In function: {func_name}"] + message
656
+ return incorrect
657
+ records.append(str(exp))
658
+ except Exception as exp:
659
+ incorrect += [func_name + " parsing error: " + str(exp)]
660
+ return incorrect
661
+ if len(records):
662
+ raise RuntimeError("Error for %s:\n%s" % (func_name, records[0]))
663
+
664
+ param_docs = []
665
+ for name, type_definition, param_doc in doc["Parameters"]:
666
+ # Type hints are empty only if parameter name ended with :
667
+ if not type_definition.strip():
668
+ if ":" in name and name[: name.index(":")][-1:].strip():
669
+ incorrect += [
670
+ func_name
671
+ + " There was no space between the param name and colon (%r)" % name
672
+ ]
673
+ elif name.rstrip().endswith(":"):
674
+ incorrect += [
675
+ func_name
676
+ + " Parameter %r has an empty type spec. Remove the colon"
677
+ % (name.lstrip())
678
+ ]
679
+
680
+ # Create a list of parameters to compare with the parameters gotten
681
+ # from the func signature
682
+ if "*" not in name:
683
+ param_docs.append(name.split(":")[0].strip("` "))
684
+
685
+ # If one of the docstring's parameters had an error then return that
686
+ # incorrect message
687
+ if len(incorrect) > 0:
688
+ return incorrect
689
+
690
+ # Remove the parameters that should be ignored from list
691
+ param_docs = list(filter(lambda x: x not in ignore, param_docs))
692
+
693
+ # The following is derived from pytest, Copyright (c) 2004-2017 Holger
694
+ # Krekel and others, Licensed under MIT License. See
695
+ # https://github.com/pytest-dev/pytest
696
+
697
+ message = []
698
+ for i in range(min(len(param_docs), len(param_signature))):
699
+ if param_signature[i] != param_docs[i]:
700
+ message += [
701
+ "There's a parameter name mismatch in function"
702
+ " docstring w.r.t. function signature, at index %s"
703
+ " diff: %r != %r" % (i, param_signature[i], param_docs[i])
704
+ ]
705
+ break
706
+ if len(param_signature) > len(param_docs):
707
+ message += [
708
+ "Parameters in function docstring have less items w.r.t."
709
+ " function signature, first missing item: %s"
710
+ % param_signature[len(param_docs)]
711
+ ]
712
+
713
+ elif len(param_signature) < len(param_docs):
714
+ message += [
715
+ "Parameters in function docstring have more items w.r.t."
716
+ " function signature, first extra item: %s"
717
+ % param_docs[len(param_signature)]
718
+ ]
719
+
720
+ # If there wasn't any difference in the parameters themselves between
721
+ # docstring and signature including having the same length then return
722
+ # empty list
723
+ if len(message) == 0:
724
+ return []
725
+
726
+ import difflib
727
+ import pprint
728
+
729
+ param_docs_formatted = pprint.pformat(param_docs).splitlines()
730
+ param_signature_formatted = pprint.pformat(param_signature).splitlines()
731
+
732
+ message += ["Full diff:"]
733
+
734
+ message.extend(
735
+ line.strip()
736
+ for line in difflib.ndiff(param_signature_formatted, param_docs_formatted)
737
+ )
738
+
739
+ incorrect.extend(message)
740
+
741
+ # Prepend function name
742
+ incorrect = ["In function: " + func_name] + incorrect
743
+
744
+ return incorrect
745
+
746
+
747
+ def assert_run_python_script(source_code, timeout=60):
748
+ """Utility to check assertions in an independent Python subprocess.
749
+
750
+ The script provided in the source code should return 0 and not print
751
+ anything on stderr or stdout.
752
+
753
+ This is a port from cloudpickle https://github.com/cloudpipe/cloudpickle
754
+
755
+ Parameters
756
+ ----------
757
+ source_code : str
758
+ The Python source code to execute.
759
+ timeout : int, default=60
760
+ Time in seconds before timeout.
761
+ """
762
+ fd, source_file = tempfile.mkstemp(suffix="_src_test_sklearn.py")
763
+ os.close(fd)
764
+ try:
765
+ with open(source_file, "wb") as f:
766
+ f.write(source_code.encode("utf-8"))
767
+ cmd = [sys.executable, source_file]
768
+ cwd = op.normpath(op.join(op.dirname(sklearn.__file__), ".."))
769
+ env = os.environ.copy()
770
+ try:
771
+ env["PYTHONPATH"] = os.pathsep.join([cwd, env["PYTHONPATH"]])
772
+ except KeyError:
773
+ env["PYTHONPATH"] = cwd
774
+ kwargs = {"cwd": cwd, "stderr": STDOUT, "env": env}
775
+ # If coverage is running, pass the config file to the subprocess
776
+ coverage_rc = os.environ.get("COVERAGE_PROCESS_START")
777
+ if coverage_rc:
778
+ kwargs["env"]["COVERAGE_PROCESS_START"] = coverage_rc
779
+
780
+ kwargs["timeout"] = timeout
781
+ try:
782
+ try:
783
+ out = check_output(cmd, **kwargs)
784
+ except CalledProcessError as e:
785
+ raise RuntimeError(
786
+ "script errored with output:\n%s" % e.output.decode("utf-8")
787
+ )
788
+ if out != b"":
789
+ raise AssertionError(out.decode("utf-8"))
790
+ except TimeoutExpired as e:
791
+ raise RuntimeError(
792
+ "script timeout, output so far:\n%s" % e.output.decode("utf-8")
793
+ )
794
+ finally:
795
+ os.unlink(source_file)
796
+
797
+
798
+ def _convert_container(container, constructor_name, columns_name=None, dtype=None):
799
+ """Convert a given container to a specific array-like with a dtype.
800
+
801
+ Parameters
802
+ ----------
803
+ container : array-like
804
+ The container to convert.
805
+ constructor_name : {"list", "tuple", "array", "sparse", "dataframe", \
806
+ "series", "index", "slice", "sparse_csr", "sparse_csc"}
807
+ The type of the returned container.
808
+ columns_name : index or array-like, default=None
809
+ For pandas container supporting `columns_names`, it will affect
810
+ specific names.
811
+ dtype : dtype, default=None
812
+ Force the dtype of the container. Does not apply to `"slice"`
813
+ container.
814
+
815
+ Returns
816
+ -------
817
+ converted_container
818
+ """
819
+ if constructor_name == "list":
820
+ if dtype is None:
821
+ return list(container)
822
+ else:
823
+ return np.asarray(container, dtype=dtype).tolist()
824
+ elif constructor_name == "tuple":
825
+ if dtype is None:
826
+ return tuple(container)
827
+ else:
828
+ return tuple(np.asarray(container, dtype=dtype).tolist())
829
+ elif constructor_name == "array":
830
+ return np.asarray(container, dtype=dtype)
831
+ elif constructor_name == "sparse":
832
+ return sp.sparse.csr_matrix(container, dtype=dtype)
833
+ elif constructor_name == "dataframe":
834
+ pd = pytest.importorskip("pandas")
835
+ return pd.DataFrame(container, columns=columns_name, dtype=dtype)
836
+ elif constructor_name == "series":
837
+ pd = pytest.importorskip("pandas")
838
+ return pd.Series(container, dtype=dtype)
839
+ elif constructor_name == "index":
840
+ pd = pytest.importorskip("pandas")
841
+ return pd.Index(container, dtype=dtype)
842
+ elif constructor_name == "slice":
843
+ return slice(container[0], container[1])
844
+ elif constructor_name == "sparse_csr":
845
+ return sp.sparse.csr_matrix(container, dtype=dtype)
846
+ elif constructor_name == "sparse_csc":
847
+ return sp.sparse.csc_matrix(container, dtype=dtype)
848
+
849
+
850
+ def raises(expected_exc_type, match=None, may_pass=False, err_msg=None):
851
+ """Context manager to ensure exceptions are raised within a code block.
852
+
853
+ This is similar to and inspired from pytest.raises, but supports a few
854
+ other cases.
855
+
856
+ This is only intended to be used in estimator_checks.py where we don't
857
+ want to use pytest. In the rest of the code base, just use pytest.raises
858
+ instead.
859
+
860
+ Parameters
861
+ ----------
862
+ excepted_exc_type : Exception or list of Exception
863
+ The exception that should be raised by the block. If a list, the block
864
+ should raise one of the exceptions.
865
+ match : str or list of str, default=None
866
+ A regex that the exception message should match. If a list, one of
867
+ the entries must match. If None, match isn't enforced.
868
+ may_pass : bool, default=False
869
+ If True, the block is allowed to not raise an exception. Useful in
870
+ cases where some estimators may support a feature but others must
871
+ fail with an appropriate error message. By default, the context
872
+ manager will raise an exception if the block does not raise an
873
+ exception.
874
+ err_msg : str, default=None
875
+ If the context manager fails (e.g. the block fails to raise the
876
+ proper exception, or fails to match), then an AssertionError is
877
+ raised with this message. By default, an AssertionError is raised
878
+ with a default error message (depends on the kind of failure). Use
879
+ this to indicate how users should fix their estimators to pass the
880
+ checks.
881
+
882
+ Attributes
883
+ ----------
884
+ raised_and_matched : bool
885
+ True if an exception was raised and a match was found, False otherwise.
886
+ """
887
+ return _Raises(expected_exc_type, match, may_pass, err_msg)
888
+
889
+
890
+ class _Raises(contextlib.AbstractContextManager):
891
+ # see raises() for parameters
892
+ def __init__(self, expected_exc_type, match, may_pass, err_msg):
893
+ self.expected_exc_types = (
894
+ expected_exc_type
895
+ if isinstance(expected_exc_type, Iterable)
896
+ else [expected_exc_type]
897
+ )
898
+ self.matches = [match] if isinstance(match, str) else match
899
+ self.may_pass = may_pass
900
+ self.err_msg = err_msg
901
+ self.raised_and_matched = False
902
+
903
+ def __exit__(self, exc_type, exc_value, _):
904
+ # see
905
+ # https://docs.python.org/2.5/whatsnew/pep-343.html#SECTION000910000000000000000
906
+
907
+ if exc_type is None: # No exception was raised in the block
908
+ if self.may_pass:
909
+ return True # CM is happy
910
+ else:
911
+ err_msg = self.err_msg or f"Did not raise: {self.expected_exc_types}"
912
+ raise AssertionError(err_msg)
913
+
914
+ if not any(
915
+ issubclass(exc_type, expected_type)
916
+ for expected_type in self.expected_exc_types
917
+ ):
918
+ if self.err_msg is not None:
919
+ raise AssertionError(self.err_msg) from exc_value
920
+ else:
921
+ return False # will re-raise the original exception
922
+
923
+ if self.matches is not None:
924
+ err_msg = self.err_msg or (
925
+ "The error message should contain one of the following "
926
+ "patterns:\n{}\nGot {}".format("\n".join(self.matches), str(exc_value))
927
+ )
928
+ if not any(re.search(match, str(exc_value)) for match in self.matches):
929
+ raise AssertionError(err_msg) from exc_value
930
+ self.raised_and_matched = True
931
+
932
+ return True
933
+
934
+
935
+ class MinimalClassifier:
936
+ """Minimal classifier implementation with inheriting from BaseEstimator.
937
+
938
+ This estimator should be tested with:
939
+
940
+ * `check_estimator` in `test_estimator_checks.py`;
941
+ * within a `Pipeline` in `test_pipeline.py`;
942
+ * within a `SearchCV` in `test_search.py`.
943
+ """
944
+
945
+ _estimator_type = "classifier"
946
+
947
+ def __init__(self, param=None):
948
+ self.param = param
949
+
950
+ def get_params(self, deep=True):
951
+ return {"param": self.param}
952
+
953
+ def set_params(self, **params):
954
+ for key, value in params.items():
955
+ setattr(self, key, value)
956
+ return self
957
+
958
+ def fit(self, X, y):
959
+ X, y = check_X_y(X, y)
960
+ check_classification_targets(y)
961
+ self.classes_, counts = np.unique(y, return_counts=True)
962
+ self._most_frequent_class_idx = counts.argmax()
963
+ return self
964
+
965
+ def predict_proba(self, X):
966
+ check_is_fitted(self)
967
+ X = check_array(X)
968
+ proba_shape = (X.shape[0], self.classes_.size)
969
+ y_proba = np.zeros(shape=proba_shape, dtype=np.float64)
970
+ y_proba[:, self._most_frequent_class_idx] = 1.0
971
+ return y_proba
972
+
973
+ def predict(self, X):
974
+ y_proba = self.predict_proba(X)
975
+ y_pred = y_proba.argmax(axis=1)
976
+ return self.classes_[y_pred]
977
+
978
+ def score(self, X, y):
979
+ from sklearn.metrics import accuracy_score
980
+
981
+ return accuracy_score(y, self.predict(X))
982
+
983
+
984
+ class MinimalRegressor:
985
+ """Minimal regressor implementation with inheriting from BaseEstimator.
986
+
987
+ This estimator should be tested with:
988
+
989
+ * `check_estimator` in `test_estimator_checks.py`;
990
+ * within a `Pipeline` in `test_pipeline.py`;
991
+ * within a `SearchCV` in `test_search.py`.
992
+ """
993
+
994
+ _estimator_type = "regressor"
995
+
996
+ def __init__(self, param=None):
997
+ self.param = param
998
+
999
+ def get_params(self, deep=True):
1000
+ return {"param": self.param}
1001
+
1002
+ def set_params(self, **params):
1003
+ for key, value in params.items():
1004
+ setattr(self, key, value)
1005
+ return self
1006
+
1007
+ def fit(self, X, y):
1008
+ X, y = check_X_y(X, y)
1009
+ self.is_fitted_ = True
1010
+ self._mean = np.mean(y)
1011
+ return self
1012
+
1013
+ def predict(self, X):
1014
+ check_is_fitted(self)
1015
+ X = check_array(X)
1016
+ return np.ones(shape=(X.shape[0],)) * self._mean
1017
+
1018
+ def score(self, X, y):
1019
+ from sklearn.metrics import r2_score
1020
+
1021
+ return r2_score(y, self.predict(X))
1022
+
1023
+
1024
+ class MinimalTransformer:
1025
+ """Minimal transformer implementation with inheriting from
1026
+ BaseEstimator.
1027
+
1028
+ This estimator should be tested with:
1029
+
1030
+ * `check_estimator` in `test_estimator_checks.py`;
1031
+ * within a `Pipeline` in `test_pipeline.py`;
1032
+ * within a `SearchCV` in `test_search.py`.
1033
+ """
1034
+
1035
+ def __init__(self, param=None):
1036
+ self.param = param
1037
+
1038
+ def get_params(self, deep=True):
1039
+ return {"param": self.param}
1040
+
1041
+ def set_params(self, **params):
1042
+ for key, value in params.items():
1043
+ setattr(self, key, value)
1044
+ return self
1045
+
1046
+ def fit(self, X, y=None):
1047
+ check_array(X)
1048
+ self.is_fitted_ = True
1049
+ return self
1050
+
1051
+ def transform(self, X, y=None):
1052
+ check_is_fitted(self)
1053
+ X = check_array(X)
1054
+ return X
1055
+
1056
+ def fit_transform(self, X, y=None):
1057
+ return self.fit(X, y).transform(X, y)
videollama2/lib/python3.10/site-packages/sklearn/utils/_typedefs.pxd ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!python
2
+ cimport numpy as cnp
3
+
4
+ # Floating point/data type
5
+ ctypedef cnp.float64_t DTYPE_t # WARNING: should match DTYPE in typedefs.pyx
6
+
7
+ cdef enum:
8
+ DTYPECODE = cnp.NPY_FLOAT64
9
+ ITYPECODE = cnp.NPY_INTP
10
+ INT32TYPECODE = cnp.NPY_INT32
11
+ INT64TYPECODE = cnp.NPY_INT64
12
+
13
+ # Index/integer type.
14
+ # WARNING: ITYPE_t must be a signed integer type or you will have a bad time!
15
+ ctypedef cnp.intp_t ITYPE_t # WARNING: should match ITYPE in typedefs.pyx
16
+ ctypedef cnp.int32_t INT32TYPE_t # WARNING: should match INT32TYPE in typedefs.pyx
17
+ ctypedef cnp.int64_t INT64TYPE_t # WARNING: should match INT32TYPE in typedefs.pyx
18
+
19
+ # scipy matrices indices dtype (namely for indptr and indices arrays)
20
+ #
21
+ # Note that indices might need to be represented as cnp.int64_t.
22
+ # Currently, we use Cython classes which do not handle fused types
23
+ # so we hardcode this type to cnp.int32_t, supporting all but edge
24
+ # cases.
25
+ #
26
+ # TODO: support cnp.int64_t for this case
27
+ # See: https://github.com/scikit-learn/scikit-learn/issues/23653
28
+ ctypedef cnp.int32_t SPARSE_INDEX_TYPE_t
videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.pxd ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cimport numpy as cnp
2
+
3
+ from libcpp.vector cimport vector
4
+ from ..utils._typedefs cimport ITYPE_t, DTYPE_t, INT32TYPE_t, INT64TYPE_t
5
+
6
+ ctypedef fused vector_typed:
7
+ vector[DTYPE_t]
8
+ vector[ITYPE_t]
9
+ vector[INT32TYPE_t]
10
+ vector[INT64TYPE_t]
11
+
12
+ cdef cnp.ndarray vector_to_nd_array(vector_typed * vect_ptr)
videollama2/lib/python3.10/site-packages/sklearn/utils/discovery.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pkgutil
2
+ import inspect
3
+ from importlib import import_module
4
+ from operator import itemgetter
5
+ from pathlib import Path
6
+
7
+ _MODULE_TO_IGNORE = {
8
+ "tests",
9
+ "externals",
10
+ "setup",
11
+ "conftest",
12
+ "experimental",
13
+ "estimator_checks",
14
+ }
15
+
16
+
17
+ def all_estimators(type_filter=None):
18
+ """Get a list of all estimators from `sklearn`.
19
+
20
+ This function crawls the module and gets all classes that inherit
21
+ from BaseEstimator. Classes that are defined in test-modules are not
22
+ included.
23
+
24
+ Parameters
25
+ ----------
26
+ type_filter : {"classifier", "regressor", "cluster", "transformer"} \
27
+ or list of such str, default=None
28
+ Which kind of estimators should be returned. If None, no filter is
29
+ applied and all estimators are returned. Possible values are
30
+ 'classifier', 'regressor', 'cluster' and 'transformer' to get
31
+ estimators only of these specific types, or a list of these to
32
+ get the estimators that fit at least one of the types.
33
+
34
+ Returns
35
+ -------
36
+ estimators : list of tuples
37
+ List of (name, class), where ``name`` is the class name as string
38
+ and ``class`` is the actual type of the class.
39
+ """
40
+ # lazy import to avoid circular imports from sklearn.base
41
+ from . import IS_PYPY
42
+ from ._testing import ignore_warnings
43
+ from ..base import (
44
+ BaseEstimator,
45
+ ClassifierMixin,
46
+ RegressorMixin,
47
+ TransformerMixin,
48
+ ClusterMixin,
49
+ )
50
+
51
+ def is_abstract(c):
52
+ if not (hasattr(c, "__abstractmethods__")):
53
+ return False
54
+ if not len(c.__abstractmethods__):
55
+ return False
56
+ return True
57
+
58
+ all_classes = []
59
+ root = str(Path(__file__).parent.parent) # sklearn package
60
+ # Ignore deprecation warnings triggered at import time and from walking
61
+ # packages
62
+ with ignore_warnings(category=FutureWarning):
63
+ for _, module_name, _ in pkgutil.walk_packages(path=[root], prefix="sklearn."):
64
+ module_parts = module_name.split(".")
65
+ if (
66
+ any(part in _MODULE_TO_IGNORE for part in module_parts)
67
+ or "._" in module_name
68
+ ):
69
+ continue
70
+ module = import_module(module_name)
71
+ classes = inspect.getmembers(module, inspect.isclass)
72
+ classes = [
73
+ (name, est_cls) for name, est_cls in classes if not name.startswith("_")
74
+ ]
75
+
76
+ # TODO: Remove when FeatureHasher is implemented in PYPY
77
+ # Skips FeatureHasher for PYPY
78
+ if IS_PYPY and "feature_extraction" in module_name:
79
+ classes = [
80
+ (name, est_cls)
81
+ for name, est_cls in classes
82
+ if name == "FeatureHasher"
83
+ ]
84
+
85
+ all_classes.extend(classes)
86
+
87
+ all_classes = set(all_classes)
88
+
89
+ estimators = [
90
+ c
91
+ for c in all_classes
92
+ if (issubclass(c[1], BaseEstimator) and c[0] != "BaseEstimator")
93
+ ]
94
+ # get rid of abstract base classes
95
+ estimators = [c for c in estimators if not is_abstract(c[1])]
96
+
97
+ if type_filter is not None:
98
+ if not isinstance(type_filter, list):
99
+ type_filter = [type_filter]
100
+ else:
101
+ type_filter = list(type_filter) # copy
102
+ filtered_estimators = []
103
+ filters = {
104
+ "classifier": ClassifierMixin,
105
+ "regressor": RegressorMixin,
106
+ "transformer": TransformerMixin,
107
+ "cluster": ClusterMixin,
108
+ }
109
+ for name, mixin in filters.items():
110
+ if name in type_filter:
111
+ type_filter.remove(name)
112
+ filtered_estimators.extend(
113
+ [est for est in estimators if issubclass(est[1], mixin)]
114
+ )
115
+ estimators = filtered_estimators
116
+ if type_filter:
117
+ raise ValueError(
118
+ "Parameter type_filter must be 'classifier', "
119
+ "'regressor', 'transformer', 'cluster' or "
120
+ "None, got"
121
+ f" {repr(type_filter)}."
122
+ )
123
+
124
+ # drop duplicates, sort for reproducibility
125
+ # itemgetter is used to ensure the sort does not extend to the 2nd item of
126
+ # the tuple
127
+ return sorted(set(estimators), key=itemgetter(0))
128
+
129
+
130
+ def all_displays():
131
+ """Get a list of all displays from `sklearn`.
132
+
133
+ Returns
134
+ -------
135
+ displays : list of tuples
136
+ List of (name, class), where ``name`` is the display class name as
137
+ string and ``class`` is the actual type of the class.
138
+ """
139
+ # lazy import to avoid circular imports from sklearn.base
140
+ from ._testing import ignore_warnings
141
+
142
+ all_classes = []
143
+ root = str(Path(__file__).parent.parent) # sklearn package
144
+ # Ignore deprecation warnings triggered at import time and from walking
145
+ # packages
146
+ with ignore_warnings(category=FutureWarning):
147
+ for _, module_name, _ in pkgutil.walk_packages(path=[root], prefix="sklearn."):
148
+ module_parts = module_name.split(".")
149
+ if (
150
+ any(part in _MODULE_TO_IGNORE for part in module_parts)
151
+ or "._" in module_name
152
+ ):
153
+ continue
154
+ module = import_module(module_name)
155
+ classes = inspect.getmembers(module, inspect.isclass)
156
+ classes = [
157
+ (name, display_class)
158
+ for name, display_class in classes
159
+ if not name.startswith("_") and name.endswith("Display")
160
+ ]
161
+ all_classes.extend(classes)
162
+
163
+ return sorted(set(all_classes), key=itemgetter(0))
164
+
165
+
166
+ def _is_checked_function(item):
167
+ if not inspect.isfunction(item):
168
+ return False
169
+
170
+ if item.__name__.startswith("_"):
171
+ return False
172
+
173
+ mod = item.__module__
174
+ if not mod.startswith("sklearn.") or mod.endswith("estimator_checks"):
175
+ return False
176
+
177
+ return True
178
+
179
+
180
+ def all_functions():
181
+ """Get a list of all functions from `sklearn`.
182
+
183
+ Returns
184
+ -------
185
+ functions : list of tuples
186
+ List of (name, function), where ``name`` is the function name as
187
+ string and ``function`` is the actual function.
188
+ """
189
+ # lazy import to avoid circular imports from sklearn.base
190
+ from ._testing import ignore_warnings
191
+
192
+ all_functions = []
193
+ root = str(Path(__file__).parent.parent) # sklearn package
194
+ # Ignore deprecation warnings triggered at import time and from walking
195
+ # packages
196
+ with ignore_warnings(category=FutureWarning):
197
+ for _, module_name, _ in pkgutil.walk_packages(path=[root], prefix="sklearn."):
198
+ module_parts = module_name.split(".")
199
+ if (
200
+ any(part in _MODULE_TO_IGNORE for part in module_parts)
201
+ or "._" in module_name
202
+ ):
203
+ continue
204
+
205
+ module = import_module(module_name)
206
+ functions = inspect.getmembers(module, _is_checked_function)
207
+ functions = [
208
+ (func.__name__, func)
209
+ for name, func in functions
210
+ if not name.startswith("_")
211
+ ]
212
+ all_functions.extend(functions)
213
+
214
+ # drop duplicates, sort for reproducibility
215
+ # itemgetter is used to ensure the sort does not extend to the 2nd item of
216
+ # the tuple
217
+ return sorted(set(all_functions), key=itemgetter(0))
videollama2/lib/python3.10/site-packages/sklearn/utils/estimator_checks.py ADDED
The diff for this file is too large to render. See raw diff
 
videollama2/lib/python3.10/site-packages/sklearn/utils/murmurhash.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:451f5dae12ddc37a669aa27561bb664bbee60a44ffb4d688d5507e9ac89f5f84
3
+ size 229345
videollama2/lib/python3.10/site-packages/sklearn/utils/parallel.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module that customize joblib tools for scikit-learn usage."""
2
+
3
+ import functools
4
+ import warnings
5
+ from functools import update_wrapper
6
+
7
+ import joblib
8
+
9
+ from .._config import config_context, get_config
10
+
11
+
12
+ def _with_config(delayed_func, config):
13
+ """Helper function that intends to attach a config to a delayed function."""
14
+ if hasattr(delayed_func, "with_config"):
15
+ return delayed_func.with_config(config)
16
+ else:
17
+ warnings.warn(
18
+ "`sklearn.utils.parallel.Parallel` needs to be used in "
19
+ "conjunction with `sklearn.utils.parallel.delayed` instead of "
20
+ "`joblib.delayed` to correctly propagate the scikit-learn "
21
+ "configuration to the joblib workers.",
22
+ UserWarning,
23
+ )
24
+ return delayed_func
25
+
26
+
27
+ class Parallel(joblib.Parallel):
28
+ """Tweak of :class:`joblib.Parallel` that propagates the scikit-learn configuration.
29
+
30
+ This subclass of :class:`joblib.Parallel` ensures that the active configuration
31
+ (thread-local) of scikit-learn is propagated to the parallel workers for the
32
+ duration of the execution of the parallel tasks.
33
+
34
+ The API does not change and you can refer to :class:`joblib.Parallel`
35
+ documentation for more details.
36
+
37
+ .. versionadded:: 1.3
38
+ """
39
+
40
+ def __call__(self, iterable):
41
+ """Dispatch the tasks and return the results.
42
+
43
+ Parameters
44
+ ----------
45
+ iterable : iterable
46
+ Iterable containing tuples of (delayed_function, args, kwargs) that should
47
+ be consumed.
48
+
49
+ Returns
50
+ -------
51
+ results : list
52
+ List of results of the tasks.
53
+ """
54
+ # Capture the thread-local scikit-learn configuration at the time
55
+ # Parallel.__call__ is issued since the tasks can be dispatched
56
+ # in a different thread depending on the backend and on the value of
57
+ # pre_dispatch and n_jobs.
58
+ config = get_config()
59
+ iterable_with_config = (
60
+ (_with_config(delayed_func, config), args, kwargs)
61
+ for delayed_func, args, kwargs in iterable
62
+ )
63
+ return super().__call__(iterable_with_config)
64
+
65
+
66
+ # remove when https://github.com/joblib/joblib/issues/1071 is fixed
67
+ def delayed(function):
68
+ """Decorator used to capture the arguments of a function.
69
+
70
+ This alternative to `joblib.delayed` is meant to be used in conjunction
71
+ with `sklearn.utils.parallel.Parallel`. The latter captures the the scikit-
72
+ learn configuration by calling `sklearn.get_config()` in the current
73
+ thread, prior to dispatching the first task. The captured configuration is
74
+ then propagated and enabled for the duration of the execution of the
75
+ delayed function in the joblib workers.
76
+
77
+ .. versionchanged:: 1.3
78
+ `delayed` was moved from `sklearn.utils.fixes` to `sklearn.utils.parallel`
79
+ in scikit-learn 1.3.
80
+
81
+ Parameters
82
+ ----------
83
+ function : callable
84
+ The function to be delayed.
85
+
86
+ Returns
87
+ -------
88
+ output: tuple
89
+ Tuple containing the delayed function, the positional arguments, and the
90
+ keyword arguments.
91
+ """
92
+
93
+ @functools.wraps(function)
94
+ def delayed_function(*args, **kwargs):
95
+ return _FuncWrapper(function), args, kwargs
96
+
97
+ return delayed_function
98
+
99
+
100
+ class _FuncWrapper:
101
+ """Load the global configuration before calling the function."""
102
+
103
+ def __init__(self, function):
104
+ self.function = function
105
+ update_wrapper(self, self.function)
106
+
107
+ def with_config(self, config):
108
+ self.config = config
109
+ return self
110
+
111
+ def __call__(self, *args, **kwargs):
112
+ config = getattr(self, "config", None)
113
+ if config is None:
114
+ warnings.warn(
115
+ "`sklearn.utils.parallel.delayed` should be used with "
116
+ "`sklearn.utils.parallel.Parallel` to make it possible to propagate "
117
+ "the scikit-learn configuration of the current thread to the "
118
+ "joblib workers.",
119
+ UserWarning,
120
+ )
121
+ config = {}
122
+ with config_context(**config):
123
+ return self.function(*args, **kwargs)